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,EAAQ9oE,IAAS8oE,EAAQ,GAAKA,OACzB,GAAI9oE,IAAS,KAAOA,IAAS,IAClC,EAAQA,OACH,GAAIA,IAAS,IAClB,GAAS,OACJ,GAAIA,IAAS,IAClB,SACK,GAAIA,IAAS,KAAO5rC,GAAS,EAAG,CACrCqjW,EAAe,EAEf,MACF,CAEA,GAAez3T,CACjB,CAAC,EAEDy3T,EAAe,EAER/jV,CACT,EAyBax6B,IAAOy+W,IAAI,MAdb,EAAM,EAAO,GAAGxrX,KAAA,EACzBu7S,kBACEx7S,EACA,OAAOhC,GAAO,OAAU,SAAW,CAAE,GAAGA,EAAO,MAAOstX,IAAWttX,EAAM,KAAK,CAAE,EAAIA,EAClF,GAAGiC,CACL,CAS4B,EClF9ByrX,IAAeN,GAIf,OAAO,IAAMA,GACb,OAAO,QAAU9nX,GASjB,OAAO,YAAc0E,UACrB,OAAO,cAAgBwzS,iBACvB,OAAO,EAAIA,iBACX,OAAO,GAAKmwE,YACZ,OAAO,KAAO3+W,IAKd,WAAWyW,KAAoBvb,WAS/B,OAAO,OAASi9T,GAChB,OAAO,UAAY31T,GAEI,SAAS,cAAc,kDAG7B,GACf,QAAQ,KACN,iJAEF,EAGF,IAAMo8W,GACJ,SAAS,cAAc,gCAAgC,EAOrDA,IAAe,OAAS,UAC1B,QAAQ,KACN,qKAEF,EAIA,SAAS,cAAc,0EAIM,GAC7B,QAAQ,KAAK,0DAA0D,EAMrE,CAAC,OAAO,kBAAoB,SAAS,eAAiBA,KACxDtoX,GAAK","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","setPrototypeOf","isFrozen","getPrototypeOf","getOwnPropertyDescriptor","freeze","seal","_ref","apply","construct","x","thisArg","Func","arrayForEach","unapply","arrayLastIndexOf","arrayPop","arrayPush","arraySplice","arrayIsArray","stringToLowerCase","stringToString","stringMatch","stringReplace","stringIndexOf","stringTrim","numberToString","booleanToString","bigintToString","symbolToString","objectHasOwnProperty","objectToString","regExpTest","typeErrorCreate","unconstruct","addToSet","transformCaseFunc","set","lcElement","cleanArray","clone","newObject","_ref2","_ref3","stringifyValue","valueAsRecord","valueToString","lookupGetter","stringified","desc","prop","fallbackValue","isRegex","html$1","svg$1","svgFilters","svgDisallowed","mathMl$1","mathMlDisallowed","text","html","svg","mathMl","xml","MUSTACHE_EXPR","ERB_EXPR","TMPLIT_EXPR","DATA_ATTR","ARIA_ATTR","IS_ALLOWED_URI","IS_SCRIPT_OR_DATA","ATTR_WHITESPACE","DOCTYPE_NAME","CUSTOM_ELEMENT","ELEMENT_MARKUP_PROBE","COMMENT_MARKUP_PROBE","FALLBACK_TAG_CLOSE","SELF_CLOSING_TAG","NODE_TYPE","LITERAL_TEXT_ELEMENT_NAMES","LITERAL_TEXT_ELEMENTS","LITERAL_TEXT_CLOSE","map","getGlobal","_createTrustedTypesPolicy","trustedTypes","suffix","ATTR_NAME","purifyHostElement","policyName","scriptUrl","_createHooksMap","_resolveSetOption","cfg","options","fallback","_resolveObjectOption","makeFallback","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","template","trustedTypesPolicy","emptyHTML","defaultTrustedTypesPolicy","defaultTrustedTypesPolicyResolved","IN_TRUSTED_TYPES_POLICY","_assertNotInTrustedTypesPolicy","_createTrustedHTML","_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","RETURN_TRUSTED_TYPE","SANITIZE_DOM","SANITIZE_NAMED_PROPS","SANITIZE_NAMED_PROPS_PREFIX","KEEP_CONTENT","IN_PLACE","USE_PROFILES","FORBID_CONTENTS","DEFAULT_FORBID_CONTENTS","DATA_URI_TAGS","DEFAULT_DATA_URI_TAGS","URI_SAFE_ATTRIBUTES","DEFAULT_URI_SAFE_ATTRIBUTES","MATHML_NAMESPACE","SVG_NAMESPACE","HTML_NAMESPACE","NAMESPACE","IS_EMPTY_INPUT","ALLOWED_NAMESPACES","DEFAULT_ALLOWED_NAMESPACES","DEFAULT_MATHML_TEXT_INTEGRATION_POINTS","MATHML_TEXT_INTEGRATION_POINTS","DEFAULT_HTML_INTEGRATION_POINTS","HTML_INTEGRATION_POINTS","COMMON_SVG_AND_HTML_ELEMENTS","PARSER_MEDIA_TYPE","SUPPORTED_PARSER_MEDIA_TYPES","CONFIG","formElement","isRegexOrFunction","testValue","_parseConfig","customElementHandling","previousTrustedTypesPolicy","ALL_SVG_TAGS","ALL_MATHML_TAGS","_checkSvgNamespace","parent","tagName","parentTagName","_checkMathMlNamespace","_checkHtmlNamespace","_checkValidNamespace","_forceRemove","_stripAttributeNode","attribute","_neutralizeRoot","_neutralizeSubtree","childNodes","snapshot","attributes","_removeAttribute","attr","_stripDisallowedAttributes","stack","_isPatchLinkageAttribute","lcName","lcTag","_neutralizePatchLinkage","nodeType","_initDocument","doc","leadingWhitespace","dirty","matches","dirtyPayload","body","_createNodeIterator","_stripTemplateExpressions","_scrubTemplateExpressions2","walker","currentNode","templates","_isDocumentFragment","tmpl","_isClobbered","realTagName","_isNode","_executeHooks","hook","data","_isUnsafeNode","_matchesNameCheck","check","_sanitizeDisallowedNode","_isBasicCustomElement","parentNode","childCount","hoisted","_forkSharedAllowlist","hookList","defaultSet","setConfigSet","_handleHookDetachedNode","_sanitizeElements","removed","content","_isValidAttribute","nameIsPermitted","RESERVED_CUSTOM_ELEMENT_NAMES","_applyTrustedTypesToAttribute","namespaceURI","_setAttributeValue","_sanitizeAttributes","hookEvent","attrValue","initValue","recreatedNamedProp","_sanitizeShadowDOM2","shadowNode","shadowIterator","fragment","innerSr","_sanitizeAttachedShadowRoots","item","isElement","rootName","sr","importedNode","returnNode","inPlace","nn","walkRoot","nodeIterator","entry","rootWasRemoved","serializedHTML","tag","hookFunction","entryPoint","purify_default","browser_default","sanitize","I","P","W","A","C","h","_e","N","$e","Le","ze","G","Ae","J","he","de","Ee","V","Me","Y","Ie","Ce","ee","Be","ke","De","qe","te","ue","Ze","He","Ge","Ne","ge","Qe","$","B","Q","je","Fe","fe","Ue","Ke","We","me","Xe","Je","Ye","xe","et","tt","rt","st","ot","at","ut","pt","ct","ht","dt","be","U","kt","gt","ft","pe","mt","xt","ce","Rt","ne","Tt","X","Ot","j","D","wt","Re","O","Te","re","se","L","ie","q","oe","ae","Oe","p","Pt","we","y","m","g","w","M","v","Z","le","Pe","ye","K","H","Se","R","S","z","T","_","F","_$2","E","k","yt","xn","bn","SHARED_REACT_KEY","isObject","input","toRaw","obj","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","MANAGED_EFFECT","CLEAN","DIRTY","MAYBE_DIRTY","INERT","DESTROYED","REACTION_RAN","DESTROYING","EFFECT_TRANSPARENT","HEAD_EFFECT","EFFECT_PRESERVED","USER_EFFECT","EFFECT_OFFSCREEN","REACTION_IS_UPDATING","ASYNC","ERROR_VALUE","STATE_SYMBOL","COMPONENT_SYMBOL","LEGACY_PROPS","LOADING_ATTR_SYMBOL","ATTRIBUTES_CACHE","CLASS_CACHE","STYLE_CACHE","TEXT_CACHE","FORM_RESET_HANDLER","STALE_REACTION","IS_XHTML","HYDRATION_ERROR","UNINITIALIZED","NAMESPACE_HTML","NAMESPACE_SVG","NAMESPACE_MATHML","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","read_hydration_instruction","equals","safe_not_equal","safe_equals","lifecycle_outside_component","async_derived_orphan","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","no_tojson","unwrapped","cloned","copy","original","path","paths","get_parent_context","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","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","defer_effect","effect","dirty_effects","maybe_dirty_effects","autofocus","dom","remove_textarea_child","get_first_child","clear_text_content","listening_to_form_reset","add_form_reset_listener","evt","without_reactive_context","previous_reaction","active_reaction","previous_effect","set_active_reaction","set_active_effect","listen_to_event_and_reset_event","handler","prev","on_reset","flatten","derived_safe_equal","pending","blockers","deriveds","sync","async","restore","capture","blocker_promise","finish","invoke_error_boundary","unset_context","decrement_pending","increment_pending","run","async_derived","expression","previous_component_context","previous_batch","current_batch","activate_batch","deactivate_batch","boundary","batch","blocking","flags","OBSOLETE","promise","source","should_suspend","deferreds","async_effect","internal_set","teardown","go","fulfil","user_derived","push_reaction_value","destroy_derived_effects","destroy_effect","execute_derived","prev_active_effect","is_destroying_effect","update_reaction","update_derived","increment_write_version","batch_values","effect_tracking","freeze_derived_effects","remove_reactions","destroy_effect_children","unfreeze_derived_effects","update_effect","last_batch","last_scheduled_effect","is_processing","collected_effects","legacy_updates","flush_count","uid","Batch","#next","#prev","#blocking_pending","skipped","#skipped_branches","#unskipped_branches","tracked","roots","#scheduled","covered","#started","#dirty_effects","#maybe_dirty_effects","render_effects","updates","#unlink","infinite_loop_guard","#resolve","#traverse","reset_all","#is_deferred","#defer_effects","reset_branch","#process","earlier_batch","#find_earlier_batch","#merge","#commit_callbacks","flush_queued_effects","#deferred","next_batch","#pending","old_values","is_branch","is_dirty","is_derived","mark","reactions","reaction","#discard_callbacks","#new_effects","blocking_pending_count","#decrement_queued","flushSync","was_flushing_sync","prev_previous_batch","eager_block_effects","length","unlink_effect","ordered_effects","ancestor","schedule_effect","eager_effects","eager_effects_deferred","state","mutable_source","initial_value","immutable","untracking","current_sources","should_proxy","proxy","seen","count_deps","mark_reactions","updated_during_traversal","untracked_writes","set_untracked_writes","flush_eager_effects","increment","set$1","runes","seen$1","not_dirty","prototype","sources","is_proxied_array","version","parent_version","update_version","with_parent","set_update_version","descriptor","exists","get","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","is_text","merge_text_nodes","first_child","first","only_child","sibling","next_sibling","last_sibling","should_defer_append","create_element","namespace","handle_error","validate_effect","rune","push_effect","parent_last","parent_effect","create_effect","user_effect","user_pre_effect","effect_root","component_root","pause_effect","render_effect","template_effect","flatten$1","values","deferred_template_effect","block","managed","branch","execute_effect_teardown","previously_destroying_effect","set_is_destroying_effect","controller","remove_dom","destroy_block_effect_children","remove_effect_dom","transitions","end","pause_children","destroy","remaining","local","transparent","resume_effect","resume_children","move_effect","captured_signals","new_deps","skipped_deps","write_version","read_version","dependencies","dependency","schedule_possible_effect_self_invalidation","previous_deps","previous_skipped_deps","previous_untracked_writes","previous_sources","previous_untracking","previous_update_version","update_dependencies","dep","is_fork","remove_reaction","new_length","start_index","tick","depends_on_old_values","should_connect","is_new","reconnect","untrack","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","all_registered_events","root_event_handles","replay_events","create_event","target_handler","handle_event_propagation","on","delegated","delegate","events","last_propagated_event","last_propagated_event_clear_scheduled","handler_element","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","start","comment","frag","anchor","append","props_id","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","handled","#pending_count","previous_ctx","#update_pending_count","#pending_count_update_queued","#effect_pending_subscriber","#handle_error","handle_error_result","transformed_error","set_text","str","mount","_mount","listeners","unmount","anchor_node","ctx","transformError","registered_events","event_handle","passive","counts","mounted_components","BranchManager","#transition","#batches","onscreen","#onscreen","#outroing","offscreen","#offscreen","on_destroy","keys","defer","#commit","#discard","PENDING","THEN","CATCH","await_block","branches","get_input","destroyed","mismatch","resolved","then_fn","catch_fn","pending_fn","if_block","marker","elseif","update_branch","has_branch","NAN","legacy","get_key","render_fn","css_props","styles","get_styles","pause_effects","to_destroy","group","groups","destroy_effects","fast_path","controlled_anchor","parent_node","preserved_effects","offscreen_anchor","each","items","each_array","collection","get_collection","first_run","commit","reconcile","move$1","discard","create_item","fallback_fn","skip_to_branch","is_animated","current","to_animate","matched","stashed","link$1","destroy_length","move","dest","next_node","link","is_controlled","get_value","hash","last","wrapper","mathml","snippet","get_snippet","hydration_start_node","get_component","now","raf","run_tasks","task","loop","fulfill","css_property_to_camelcase","style","parts","word","css_to_keyframe","keyframe","css","part","formatted_property","linear","animation_effect_override","set_animation_effect_override","animation","nodes","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","append_styles","attach","clsx","_clsx","whitespace","to_class","classname","directives","len","separator","important","to_css_name","to_style","new_style","normal_styles","important_styles","in_str","in_apo","in_comment","reserved_names","name_index","set_class","next_class_name","next_classes","is_html","prev_classes","is_present","update_styles","priority","set_style","next_style_attr","next_styles","prev_styles","set_selected","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_attribute","checked","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","previous","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","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","onMount","cleanup","onDestroy","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","inputDeclaration","localDeclaration","valueStart","name_","arg","sigil","functionRef","markup","identifier","options_","allowMarkup","attributes_","exp","isEmpty","esc","required","quotedLiteral","ws","hasWS","req","visit","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","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","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","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","handleKeyDown","activateKeyShortcuts","platformKeyShortcuts","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","isVisible","bottom","right","innerHeight","innerWidth","scheduleVisibilityCheck","waitForVisibility","previousResolve","mirrorPosition","mirrored","clipRect","anchorRect","viewport","flip","room","otherRoom","calculatePopupStyle","preferredPosition","rect","topMargin","bottomMargin","leftMargin","rightMargin","downwardMargin","upwardMargin","flipVertically","contentHeight","contentWidth","isShallowEqual","Popup","#open","activeElement","anchorElement","positionBaseElement","removeClickListener","removeKeyDownListener","hasModifier","removeTransitionStartListener","#removeAnchorListeners","popupElement","contentElement","identifiedElement","#removeEventListeners","appliedMaxHeight","appliedMaxWidth","removeListener","activatePopup","getLongestTime","getTransitionTimeout","transitionDuration","transitionDelay","Placeholder","RETAINER_KEY","Modal","dialogSnippet","dialog_1","event_handler","event_handler_1","downTarget","pointerDownTarget","dialog","lightDismiss","open","event_handler_2","escapeDismiss","event_handler_3","requestedOpen","setOpenClass","showBackdrop","setActiveClass","node_1","$$value","mounted","keepContent","restoreFocus","focus","close","visible","retainCount","parentRetainer","generation","lastActiveElement","restoreFocusTimer","moveFocusBack","waitForTransition","timeout","timer","openDialog","gen","closeDialog","wasOpen","placeholder","contentWrapper","$.set_class","contentType","classes","touch","popupInstance","hovered","parentDialogElement","hoveredTimeout","touchOptimized","dialogElement","touchEnabled","focusContent","focused","tabStopOnly","$.spread_props","Button","labelText","labelDir","className","valueType","hidden","readonly","pressed","keyShortcuts","iconic","pill","flex","popupPosition","showPopupBackdrop","button","$.first_child","fragment_1","span_1","consequent_2","consequent_1","alternate_1","node_8","Infobar","show","dismissible","root_1","div_1","node_2","div_2","node_3","$.clsx","Bottom_navigation","Button_group","ariaLabel","Floating_action_button_wrapper","scrollIntoViewIfNeeded","CONTEXT_KEY","OptionRegistry","#entries","#snapshotVersion","#version","#snapshot","#entrySet","createOptionRegistry","getOptionRegistry","getSelectedItemDetail","DIACRITIC_RE","fold","normalize","getArrowKeys","orientation","rtl","getLinearTargetIndex","prevKey","nextKey","getGridTargetIndex","lastIndex","backward","forward","columnCount","TypeAhead","#timer","#prefix","findTypeAheadMatch","cycling","char","needle","currentIndex","labels","activateBefore","widget","activateLater","isDestroyed","INACTIVE_MEMBER_SELECTOR","setTabIndex","tabIndex","FOCUSABLE_SELECTOR","focusAdjacentTabStop","candidate","step","backwards","getMenuOpener","opener","isSelectable","Group","raw","member","cached","#searchValueCache","normalized","controlTargetId","shown","panel","clickToSelect","childRoles","childSelectedAttr","focusChild","selectFirst","controlsPanel","rovingTabStop","#memberCache","records","#destroyed","defaultSelected","allMembers","isSelected","controlTarget","#getControlTarget","#setPanelShown","activeMembers","holders","tabStop","laidOut","firstTop","#members","all","innermost","outermost","menu","submenuId","submenu","#clickingRadio","isMenuItemRadio","selectable","multiSelect","singleSelect","targetSelectable","changed","isTarget","selecting","#setMemberSelected","#clickRadio","scrollTargets","affected","newTarget","targetAffected","targetRole","targetParent","#applySelection","#moveCursor","#moveFocus","#scrollTimer","elements","isMenu","currentTarget","#getCurrentTarget","fromMember","#getTypeAheadTarget","parentMenuItem","outOfSubmenuKey","intoSubmenuKey","#getArrowTarget","#typeAhead","members","list","terms","searchTerms","_terms","searchValue","#getNormalizedSearchValue","term","#hiddenState","activateGroup","isGetter","paramsOrGetter","Select_button_group","invalid","Select_button","Menu_button","popupPositionBaseElement","buttonElement","Split_button","endIcon","popup","$.set","Divider","Spacer","Checkbox_group","Checkbox","$.props_id","accessibleLabel","hasVisibleLabel","indeterminate","startIcon","$1","label_1","node_4","$.set_attribute","consequent_4","Modal_close_button","closeIcon","Dialog","ariaLabelledby","showClose","showOk","showCancel","okLabel","okShortcuts","okDisabled","cancelLabel","cancelShortcuts","cancelDisabled","focusInput","labelledby","modal","cancelled","root_4","fragment_2","div_3","node_7","div_4","root_3","node_11","consequent_5","consequent_6","Alert_dialog","Confirmation_dialog","MIRROR_STYLE_PROPERTIES","getFieldCaretRect","fieldRect","singleLine","mirror","mirrorRect","markerRects","markerRect","offsetTop","offsetLeft","offsetRight","EMOJI_DATA","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","dismissed","newTrigger","moveSelection","selectHighlighted","row","paddingTop","paddingBottom","borderTopWidth","borderBottomWidth","owner","reposition","onPointerDown","text_1","Emoji_autocomplete","findTrigger","selectionStart","selectionEnd","field","refresh","onKeyDown","onBlur","EmojiSuggestions","inserted","Text_input","showInlineLabel","inputmode","monospace","debounce","useEmojiAutocomplete","debounceTimer","fireInput","handleInput","inputEvent","Emoji_autocomplete$1","classes_1","Prompt_dialog","textboxAttrs","getSwipeDirection","getSwipeOffset","sign","addSwipeSample","samples","sample","getSwipeVelocity","shouldDismissSwipe","velocity","Drawer","title","swipeDismiss","EXCLUDED_SWIPE_TARGETS","swipe","swipeOffset","isPrimary","excluded","axis","clientY","clientX","pointerId","onPointerMove","timeStamp","onPointerUp","dismiss","node_5","consequent_3","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_row","Grid","Listbox","filtered","total","Option_group","Option","fallbackId","wrap","registry","newValue","rendered","Menu","Menu_item","isPopupOpen","isPopupHovered","hoverTimer","hasItems","scheduleHoverChange","Menu_item_checkable","roleClass","Menu_item_checkbox","Menu_item_radio","Progressbar","min","max","percentage","Radio_group","Radio","isGroupReadOnly","resolveToPercent","trimmed","matchedPercent","env","containerSize","matchedPx","matchedViewport","viewportValue","viewportSize","resolvePaneConstraints","paneDef","minSize","maxSize","spreadSize","amount","adjustable","indexes","share","moved","constraints","sizes","diff","sum","getInitialSizes","specified","resolvedDefaults","totalSpecified","unspecifiedCount","defaultSize","allConstraints","fitted","clampResizeDelta","canGrow","constraintsBefore","sizeBefore","sizeAfter","constraintsAfter","canShrink","deltaPercent","getHandleKeyAction","isHorizontal","Resizable_handle","showHandleBar","handleIndex","currentPaneSize","currentPaneConstraints","nextPaneConstraints","pairSize","currentPaneMin","currentPaneMax","dragging","startScreenPos","startPaneSize","targetPointerId","keyResizing","pixelDelta","screenX","screenY","percentDelta","Resizable_pane_group","direction","_paneDefs","_savedSizes","_handleCount","measurePaneSpace","groupSize","handleSize","getSizeEnvironment","getPaneConstraints","paneIndex","initSizes","resize","beforeIdx","afterIdx","prevBefore","prevAfter","idx","minBefore","Resizable_pane","sizeStyle","Infinite_scroll","itemChunkSize","loadedItemSize","spinner","loading","Search_bar","inputElement","Combobox","editable","filterThreshold","comboboxElement","popupContent","idleHost","optionHost","listboxSlot","showFilter","matchedOptions","hasMatchingOptions","_onChange","dispatchEntryChange","entryLabel","entryValue","_onSelect","detail","onTextInput","typeAhead","onComboboxKeyDown","getListbox","revealSelectedOption","listbox","$.CLASS","$2","div_7","cubicOut","params","ox","oy","zoom","get_zoom","sx","sy","fx","fy","tx","ty","dx","dy","dsx","dsy","Select","moveItem","newList","getKeyboardMoveTarget","getDropIndex","getDropTarget","dropIndex","fromIndex","Select_tags","optionMap","selectedValues","hasUnselectedOptions","wrapperElement","selectedValue","dragIndex","moveValue","newValues","moveAndFocus","span_2","span_3","toIndex","targetIndex","$$item","countFractionDigits","mantissa","exponent","num","getSliderSteps","stepRatio","stepCount","stepWidth","barWidth","emptyArray","decimals","toLogicalX","physicalX","findNearestStepIndex","positionList","logicalX","getSliderKeyDirection","getSliderKeyTargetIndex","page","wouldCrossThumbs","valueIndex","sliderPositions","targetPosition","getSliderCurrentIndex","valueList","decreasing","upperIndex","getNearestThumbIndex","position0","position1","diff0","diff1","Slider","sliderLabel","sliderLabels","optionLabels","multiThumb","base","getValueText","_value","startX","startScreenX","targetValueIndex","setValue","_values","moveThumb","screenDiff","slider","getPosition","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","mountCount","onToggle","onClose","acquireBase","releaseBase","Toast","popover","toast","held","mql","setMode","BACKTICKS","toCodeBlock","parseCodeBlock","markdown","o$3","i$2","l$3","c$4","f$3","h$3","E$3","Eu","iu","Q$3","nt","ot$2","it","lt","yl","wf","Ef","_t","ta","Qa","Wa","cu","ga","zi","Rc","St","Uu","Fa","Xc","Sl","Su","Ct","al","fs","ki","Qc","yt$5","sa","Oa","vt","Ct$5","bt","Nt","Ft","At","Et","Mt","Nt$5","Jt","Dt","Kt","Lt","zt","Kt$4","Bt","Wt","Yt","Gt","Xt","Qt","Zt","Ws","Sf","ve","\"$\"","Ec","Vs","tn","en","Ve","rn","sn","ln","cn","Dn","bf","an$2","mn","Sn","cn$2","Ta","an","un","dn","ka","hn","gn","vl","Va","_n","pn","Vu","yn","pn$2","vn","Mu","Nf","Cn","En","Zc","ju","gn$1","kn","Nn","Tn","On","Fl","wn","Aa","En$1","He$1","Mn","An","kn$1","na","Fn","mc","Pn","In","Ln","zn","Kn","Bn","Rn","Wn","$n","jn","Un","Vn","Jn","Hn","qn","Yn","Gn","Xn","Qn","Zn","eo","no","oo","ro","io","so","lo","co","ao","uo","fo","ho","_o","po","yo","mo","xo","So","Co","vo","ko","bo","To","No","wo","Eo","Oo","Mo","Ao","Fo","Do","Po","Io","Lo","zo","Ko","zo$1","Bo","Ro","Wo","$o","jo","Uo","Vo","Jo","Ro$1","kr","Ho","aa","Bc","Pu","Kc","qo","Yo","Dc","ra","Go","Xo","ol","Qo","ds","us","Ma","Zo","_u","Cu","Ju","tr","er","kf","Ei","nr","or","a$2","rr","gu","ir","Yc","Ea","m$3","ha","fr","za","jr","lr","dr","Vr","la","d$4","da","u$1","cr","ar","ur","vi","Bi","hr","gr","g$2","_r","pr","yr","mr","xr","Sr","Cr","vr","Za","Da","tu","Ic","ua","br","Tr","Nr","Pn$1","wr","Of","Ba","ps","hs","Jc","gs","Er","Or","Mr","Ar","Fr","_f","e$2","Tf","Vc","Ed","Td","js","qc","Ku","jf","Ou","Gu","Yu","uf","ff","gf","qa","Mf","Fi","Gc","oc","Dr","Ir","Lr","$r","Jr","Hr","qr","Yr","Gr","Xr","Qr","Zr","ti","ei","ni","ri","ii","re$4","ue$3","ie$5","Xt$5","Zt$4","Yt$5","si","li","ci","ba","ai","ui","fi","di","hi","mi","_i","Ci","gi","jc","ss","ys","bi","pi","yi","ks","xi","bu","Si","Ha","Ti","fe$2","Ni","wi","Oi","bd","Vl","Ll","Rs","Mi","Ai","Di","rc","Pi","Ii","ad","Kl","vd","Li","Df","Ki","rd","hd","_d","nd","Hl","Rl","Ui","If","Lf","rs","Bl","Ul","$i","Os","wu","Ns","Ts","Zl","zl","Al","Ms","Xa","Hi","su","ja","qi","Ji","Sd","Ga","ia","cs","Wl","Yi","Qi","Xi","Vi","es","Ri","Wi","ji","tc","ca","Gi","Zi","fd","ts","Ff","os","Pf","_s","xs","Ss","Wc","Ac","hu","lu","Ra","Ia","Cs","vs","bs","Es","$a","Jl","As","Fs","Ds","Ps","Is","Ls","zs","Ks","Bs","$s","Hs","Us","Js","vc","ou","Lc","Pc","qs","Ys","Gs","Xs","Qs","Zs","Vf","tl","cl","il","pc","Pd","nl","oa","rl","sl","ll","kl","bc","Mc","ul","fl","dl","hl","gl","_l","pl","ml","xl","Cl","wl","bl","Tl","Nl","El","Ol","Dl","Pl","Ml","Nu","Il","Ya","ud","ql","xd","Qf","$l","jl","Ua","Cd","Gl","Xl","Ql","Ja","ec","nc","$u","Ru","Wu","ic","yc","Oc","xc","fa","Sc","Cc","zd","zu","Ka","kc","Tc","Nc","ea","zc","$c","Uc","_a","Sa","Ca","va","wa","Pa","vu","eu","nu","ru","uu","fu","du","yu","ku","Tu","Du","Iu","Lu","Bu","Hu","qu","Xu","af","Jt$5","Qu","cf","lf","df","vf","xf","yf","Zu","tf","ef","of","hf","pf","mf","Af","zf","Kf","Bf","Rf","Wf","$f","Uf","Hf","qf","Yf","kd","Gf","Zf","Xf","td","ed","sd","ld","cd","dd","yd","gd","pd","Nd","wd","Od","Dd","Id","Ld","ie$4","jt","Vt","qt","r$1","h$2","g$1","f$1","t$1","b$1","m$1","ht$4","$t","$t$5","ft$4","tt$2","ie$3","Se$1","_e$1","de$2","Gt$3","ee$4","te$3","ft$3","It","Lt$5","Ht","Ut","un$1","oe$1","yt$3","Qt$5","gt$2","kt$2","Et$3","wt$3","Yt$2","Dt$2","pe$3","ht$1","bt$1","xe$3","Ft$1","EDITOR_THEME","AVAILABLE_BUTTONS","TEXT_FORMAT_BUTTON_TYPES","INLINE_BUTTON_TYPES","BLOCK_BUTTON_TYPES","NODE_MAP","HeadingNode","ListNode","ListItemNode","QuoteNode","CodeNode","CodeHighlightNode","LinkNode","TRANSFORMER_MAP","HEADING","UNORDERED_LIST","ORDERED_LIST","QUOTE","CODE","INLINE_CODE","BOLD_STAR","BOLD_UNDERSCORE","BOLD_ITALIC_STAR","BOLD_ITALIC_UNDERSCORE","ITALIC_UNDERSCORE","ITALIC_STAR","STRIKETHROUGH","LINK","DISABLED_MARKDOWN_TAGS","IMPORT_UPDATE_TAG","OPEN_LINK_EDITOR_COMMAND","createCommand","ce$3","escapeRegExp","truncate","chars","ellipsis","stripSlashes","sharedDOMParser","stripTags","isURL","getBackgroundUpdateTags","editor","tags","SKIP_DOM_SELECTION_TAG","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","cache","SHIKI_VERSION","LANGUAGES","\"id\"","\"name\"","\"aliases\"","THEMES","\"displayName\"","\"type\"","DATABASE_NAME","STORE_NAME","purgePromise","enabled","getKey","getDatabase","purgeStaleVersions","stale","db","getCachedPayload","cachePayload","UI_VERSION","SHIKI_CDN_BASE_URL","UI_CDN_BASE_URL","getEngineURL","getLanguageURL","getThemeURL","loaders","__vitePreload","getCodeHighlighterLoaders","CODE_THEME_LIGHT","CODE_THEME_DARK","getCodeTheme","theme","onCodeThemeChange","media","observeCodeTheme","isCodeNode","HISTORY_MERGE_TAG","PLAIN_LANGUAGES","DIFF_LANGUAGE_REGEX","engine","highlighter","engineUnavailable","getDiffedLanguage","isPlainLanguage","isEngineLoaded","isEngineUnavailable","isCodeLanguageLoaded","refreshCodeNode","codeNode","getNodeByKey","codeNodeKey","pendingLoads","loadOnce","targets","nodeKey","loadEngine","resolvePayload","module","load","loadAsset","findLanguage","normalizeCodeLanguage","loadCodeLanguage","isCodeThemeLoaded","loadCodeTheme","mapTokensToLexicalStructure","tokens","lineIndex","createLineBreakNode","tokenIndex","prefixes","prefixTypes","prefixIndex","createCodeHighlightNode","createTabNode","getHighlightNodes","diffedLanguage","getHighlightTheme","resolvedTheme","highlightCodeToHTML","highlightCodeToTokens","color","fg","fontStyle","ALLOWED_ATTRIBUTES","TEXT_FORMAT_TAGS","PASSTHROUGH_TAGS","DOCUMENT_TAGS","getCodeLanguage","removeExtraAttributes","allowedAttributes","exportElementNode","isHTMLElement","newElement","after","exportParagraphNode","TableCellNode","isParagraphNode","exportTextNode","exportCodeNode","TABLE_STRUCTURE_SELECTOR","HTML_EXPORT_MAP","TextNode","TabNode","ParagraphNode","HorizontalRuleNode","TableNode","colgroup","getTextWithLineBreaks","convertPreElement","createCodeNode","createTextNode","editorComponents","componentConversionMaps","getComponentConversionMap","elementComponents","getElementComponent","isInlineComponentElement","getEditor","findContentInLine","parentElement","display","isInlineDomNode","descendant","isDOMTextNode","isPreformatted","convertTextNode","textContent","domNode","drop","previousText","isEndOfLine","HTML_IMPORT_MAP","HTML_CODE_IMPORT_MAP","getComponentOnlyTagNames","components","componentNodes","otherTagNames","klass","findUnsupportedNode","componentOnlyTagNames","findWithin","exportHtml","generateHtmlFromNodes","splitMultilineFormatting","mapLinesOutsideCodeBlocks","openingFence","fence","increaseListIndentation","p1","p2","padBlankBlockquoteLines","trimBlankBlockquoteLines","shikiTokenizer","DEFAULT_CODE_LANGUAGE","plainifyCodeContent","updateCodeGutter","codeElement","gutter","isLineBreakNode","isEqual","isCodeHighlightNode","nodeA","nodeB","isTabNode","getDiffRange","leadingMatch","prevNodes","nextNodes","prevNodesLength","nextNodesLength","maxTrailingMatch","trailingMatch","updateAndRetainSelection","selection","getSelection","isRangeSelection","updateFn","anchorNode","anchorOffset","isNewLineAnchor","textOffset","node_","isTextNode","textContentSize","codeNodeTransform","transformState","tokenizer","isPlain","inFlight","nodesCurrentlyHighlighting","staleNode","highlightNodes","nodesForReplacement","textNodeTransform","registerCodeHighlighting","registrations","mutations","registerCodeIndentation","mergeRegister","escapeBlockSyntax","BLOCK_SYNTAX_ESCAPE","exportFormat","HR","isHorizontalRuleNode","createHorizontalRuleNode","isImport","TABLE_ROW_REG_EXP","TABLE_ROW_DIVIDER_REG_EXP","getTableColumnsSize","table","isTableRowNode","createTableCell","cell","createTableCellNode","TableCellHeaderStates","TRANSFORMERS","mapToTableCells","TABLE","TableRowNode","isTableNode","rowOutput","isHeaderRow","isTableCellNode","convertToMarkdownString","rows","lastRow","matchCells","maxCells","firstChild","cells","previousSibling","createTableNode","tableRow","createTableRowNode","HISTORY_MAX_DEPTH","DECORATOR_INTERACTIVE_SELECTOR","isStaticDecoratorContent","decorator","interactive","$moveCaretIntoBlock","getRoot","before","isElementNode","paragraph","createParagraphNode","updateNodeWithFocus","getNearestNodeFromDOMNode","placeCaretAfterDecorator","isDecoratorNode","placeCaretAtBlockEnd","handleEditorMouseDown","SAFE_LINK_URL_SCHEMES","isSafeLinkURL","normalizedURL","url","scheme","getNearestElementNode","ElementNode","getNearestNodeOfType","getSelectionTypes","inlineTypes","isLinkNode","isListItemNode","blockType","isHeadingNode","isListNode","isQuoteNode","exportMarkdown","enabledTransformers","onEditorUpdate","cachedValue","getComponentMarkdown","createMarkdown","createEditor","newNode","createNode","transformer","mergeUnregisters","unregisters","handlers","unregister","registerCodeEditorCommands","DELETE_CHARACTER_COMMAND","isBackward","KEY_ENTER_COMMAND","INSERT_PARAGRAPH_COMMAND","RootNode","defaultLanguage","registerLinkCommands","Xt$4","TOGGLE_LINK_COMMAND","xt$3","PASTE_COMMAND","objectKlassEquals","clipboardText","LIST_COMMANDS","INSERT_UNORDERED_LIST_COMMAND","INSERT_ORDERED_LIST_COMMAND","registerListCommands","enabledLists","enabledButtons","command","listType","Ot$3","handleListInsertParagraph","registerUpdateEvent","updateCount","contentChanged","lastValue","disposed","dirtyElements","dirtyLeaves","currentCount","registerTabIndentation","onKeydown","OUTDENT_CONTENT_COMMAND","INDENT_CONTENT_COMMAND","initEditor","hasCodeBlock","isCodeEditor","editorExtension","defineExtension","CodeExtension","transformers","buildEditorFromExtensions","registerRichText","registerDragonSupport","registerHistory","createEmptyHistoryState","useMarkdownShortcuts","registerMarkdownShortcuts","loadCodeHighlighter","latestImports","importValue","importId","isSuperseded","ex","$import","formatName","$export","convertMarkdownToLexical","convertHtmlToLexical","unsupportedNode","focusEditor","Lexical_root","editorStore","lexicalRoot","onUpdate","hasConverterError","useRichText","exportedValue","inputValue","onClick","onMouseDown","unregisterUpdateListener","dispose","createEditorStore","editorId","initialized","textArea","showConverterError","runningOperations","lastImport","importCount","importing","setConverterError","convertToLexical","originalValue","exported","hasChange","done","Code_language_switcher","codeLanguages","selectedLanguage","selectedKey","getCodeNode","blockNodeKey","changeLanguage","endOperation","Toolbar","Toolbar_wrapper","Code_editor_toolbar","Code_editor","showLanguageSwitcher","ariaDescribedby","ariaLabelAttr","ariaLabelledbyAttr","ariaDescribedbyAttr","labelAttrs","_lang","_code","Text_area","autoResize","highlight","cloneValue","highlightedTokens","cloneElement","textarea","onScroll","textarea_1","$.index","classes_2","getAnchorRect","domSelection","range","insertEmoji","registerCommands","whileOpen","KEY_ARROW_DOWN_COMMAND","KEY_ARROW_UP_COMMAND","KEY_TAB_COMMAND","KEY_ESCAPE_COMMAND","editorState","Floating_link_editor","currentLink","hasFocus","dismissedLinkKey","editTarget","popupHeight","editing","isValidURL","findLink","findMatchingParent","createDOMRange","startEditing","initialURL","stopEditing","refocusEditor","onOpenCommand","getPreviousSelection","applyURL","newURL","cancelEditing","removeLink","onInputKeyDown","unregisterCommand","unregisterEscape","unregisterEditableListener","isWithin","onFocusIn","onFocusOut","relatedTarget","fragment_4","node_6","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","lineEnd","level","getPrefix","newLines","oldPrefix","newPrefix","oldLineStart","oldContentStart","oldLineEnd","newContentStart","insertLink","insertMarkdown","trimmedStart","trimmedEnd","getRawTextState","focusTextArea","deadline","isRawTextEditable","readOnly","applyRawTextEdit","editRawText","getEdit","registerRawTextShortcut","insertComponent","isObjectArray","unique","Format_text_button","selectionTypeMatches","SHORTCUT_KEYS","FORMAT_TEXT_COMMAND","insertEditorComponent","Insert_item_button","Insert_link_button","hasAnchor","anchorURL","anchorText","openCreateDialog","createLink","getTextContent","onButtonClick","onDialogClose","_selection","createRangeSelection","_registerCommand","KEY_DOWN_COMMAND","Insert_menu_button","computed_const","Toggle_block_menu_item","NODE_FACTORIES","createQuoteNode","changeBlockType","headingLevel","createHeadingNode","Q$2","Text_editor_toolbar","buttons","menuitems","blockLevelButtons","isHtml","canFormat","inlineLevelButtons","node_12","node_14","consequent_7","Text_editor","modes","sourceLanguage","MAX_HIGHLIGHT_LENGTH","codeTheme","highlighterLoadCount","usePlainText","highlightSource","getMaximumFractionDigits","digits","parseNumber","toNumber","isAtMin","isAtMax","stepNumber","maximumFractionDigits","isInvalidNumber","Number_input","edited","isMin","isMax","stepValue","newInputValue","decrease","increase","canStep","Masked_input","Secret_input","Tree_item","handleChange","handleExpand","handleSelect","handleEvents","alternate_2","ITEM_SELECTOR","Tree","expandOnSelect","selectionFollowsFocus","collect","walk","allItems","activeItems","multi","anchorIndex","additive","parentItem","currentItem","backwardKey","forwardKey","newItem","childItem","activateTree","tree","TEXT_INPUT_TYPES","shouldAllowContextMenu","App_shell","fontLoaded","mediaQuery","applyTheme","dataset","fontTimer","Font_links","Empty_state","Visibility_observer","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\"","\"split_button\"","\"x_options\"","\"more_options\"","\"combobox\"","\"select_an_option\"","\"filter_options\"","\"no_matching_options\"","\"number_input\"","\"increase\"","\"decrease\"","\"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\"","\"blockquote\"","\"code_block\"","\"bold\"","\"italic\"","\"strikethrough\"","\"code\"","\"link\"","\"insert_link\"","\"edit_link\"","\"remove_link\"","\"text\"","\"url\"","\"edit_in_markdown\"","\"edit_in_html\"","\"converter_error\"","\"language\"","\"plain_text\"","pkg","UNPKG_BASE_URL","SCHEMA_URL","DEV$1","\"DEV\"","DEV_SITE_URL","DEV","VITE_SITE_URL","DEV_CONFIG_PATH","SUPPORTED_TYPES","equal","createState","staticKeys","$.snapshot","createRawState","createDeepState","createDerivedState","createStableDerivedState","createRootEffect","$.effect_root","watch","getDependencies","watchAsync","onResult","syncValues","updateInput","toInput","getInput","setInput","updateValue","toValue","cmsConfig","parsedCmsConfig","rawCmsConfig","cmsConfigVersion","cmsConfigErrors","cmsConfigLoaded","collectors","getBlobRegex","filePathRegEx","textFileTypes","isTextFileType","getPathInfo","dirname","basename","filename","extension","decodeFilePath","isValidFileType","specifiers","fileName","file","specifier","rawSpecifier","subtype","scanFiles","getFile","readEntries","reader","readEntry","readAsText","toBlob","encodeBase64","blob","decodeBase64","base64","saveFile","blobURL","isHighSurrogate","codePoint","isLowSurrogate","charLength","curByteLength","segment","getLength","byteLength","prevCodePoint","require_truncate","require_browser$2","require_browser$1","illegalRe","controlRe","reservedRe","windowsReservedRe","replaceTrailingDotsAndSpaces","replacement","sanitized","getOrCreate","getOrCreateBounded","shareInFlight","getOrCreateAsync","memoizeOnSource","getSource","build","createPathRegEx","replacer","encodeFilePath","hasAtPrefix","renameIfNeeded","otherNames","slug","regex","highest","otherName","sanitizeFileName","EQUIVALENT_FILE_EXTENSIONS","isEquivalentFileExtension","_b","createPath","segments","getDirName","stripPathPrefix","sanitizePath","resolvePath","nameFound","getBlob","getByteSize","computeGitHash","gitHashCache","getGitHash","normalizeRootDir","getRootDir","toRepoPath","rootDir","fromRepoPath","rootSegments","pathSegments","common","isInRootDir","toRepoChanges","changes","change","previousPath","getHandleByPath","normalizedPath","rootDirHandle","pathParts","getFileHandle","getDirectoryHandle","readFile","getScopedRootDirHandle","repoRootDirHandle","types","__classPrivateFieldGet","_Mime_extensionToType","_Mime_typeToExtension","_Mime_typeToExtensions","Mime","extensions","typeMap","ext","allExtensions","starred","currentType","force","hasPath","src_default$1","standardTypes","otherTypes","MEDIA_KINDS","THUMBNAIL_KINDS","hasPDFThumbnail","canCreateThumbnail","asset","ASSET_KINDS","DOC_EXTENSION_REGEX","MEDIA_TYPE_REGEX","isMediaKind","canPreviewFile","mime","canPreviewAsset","getMediaKindFromType","mimeType","subType","getMediaKindFromPath","hostname","pathname","getMediaKind","canEditAsset","getAssetKind","allAssets","publishedAssets","workflow","selectedAssets","selectedAssetPathSet","focusedAsset","selectedOrFocusedAssets","overlaidAsset","uploadingAssets","editingAsset","renamingAsset","CMS_FOLDER_NAMES","isCmsFolderName","isCmsFolderPath","dirPath","isInCmsFolder","assertOutsideCmsFolders","lockedBranch","mergeLockedBranch","recordBranchAccess","access","fetchAccess","TEMPLATE_TAG_REGEX","TEMPLATE_TAG_REPLACE_REGEX","ESCAPED_PLACEHOLDER_REGEX","DATE_TIME_FIELDS","DATE_TIME_TEMPLATE_REGEX","FIELD_TAG_PREFIX_REGEX","DEFAULT_TRANSFORMATION_REGEX","INNER_TAG_REGEX","UUID_TYPES","replaceTemplateTags","searchIndex","openIndex","quoteState","nextChar","closeIndex","hasLeadingQuote","hasTrailingQuote","openingDelimiter","closingDelimiter","isNestedTransformationArgument","hasTemplateTags","customComponentRegistry","customFieldTypeRegistry","customFileFormatRegistry","customPreviewStyleRegistry","customPreviewTemplateRegistry","eventHookRegistry","isBuffer","keyIdentity","delimiter","maxDepth","transformKey","isarray","isbuffer","isobject","currentDepth","unflatten","overwrite","getkey","parsedKey","addKeys","keyPrefix","recipient","isArray","split","key1","key2","isMultiLinePattern","multiline","dotAll","getSelectorSubjects","subjects","quote","afterCombinator","getSelectorTagNames","names","subject","isValidSelector","supportsHTML","htmlSelector","fromBlockHTML","toBlockHTML","normalizeProps","replaceQuotes","IMAGE_REGEX","GLOBAL_IMAGE_REGEX","IMAGE_OR_LINKED_IMAGE_REGEX","isNonEmptyString","escapeAttr","HTML_ESCAPE_MAP","escapeHTML","LINK_SANITIZE_OPTIONS","makeLink","href","sanitizeInlineMarkdown","parseInline","allowedTags","allowedAttr","getImageProps","img","createImageElement","src","IMAGE_COMPONENT","LINKED_IMAGE_COMPONENT","src2","alt2","title2","getBuiltInComponentDefs","commonImageProps","getCustomComponentName","unprefixedName","getComponentDef","customComponentName","customComponentDef","LOCALE_PLACEHOLDER","LOCALE_FOLDER_REGEX","hasLocalePlaceholder","isValidLocaleFolderPath","folderPath","omitLocalePlaceholder","canOmitLocalePlaceholder","fillLocalePlaceholder","omitLocale","getLocaleFolderPattern","localeFolderMatcher","localeFolderPrefixRegExpCache","stripLocaleFolderPath","filePath","DEFAULT_CMS_LABEL_PREFIX","LEGACY_CMS_LABEL_PREFIXES","WORKFLOW_STAGES","OPEN_AUTHORING_STAGES","WORKFLOW_STATUSES","WORKFLOW_STATUS_LABELS","forkedRepository","openAuthoring","openAuthoringInitialized","workflowStages","ENTRY_ALREADY_PUBLISHED","isEntryAlreadyPublished","getForkPath","fork","getForkURL","repository","repoURL","repo","forkPermissionRequest","requestForkPermission","granted","allAssetFolders","globalAssetFolder","collectionName","componentName","typedKeyPath","internalPath","selectedAssetFolder","targetAssetFolder","_selectedAssetFolder","getAssetFolder","cond","folder","getEntryRelativePathRegEx","localeMatcher","localeFolderNames","subPath","internalSubPath","firstSegment","subPathPattern","getAssetFolderPathCache","entryRelative","_allAssetFolders","isRelative","getAssetFoldersByPath","matchSubFolders","regexSub","regexExact","canCreateAsset","assetFolder","assetsLocked","hasReadonlyAsset","assets","TEMP_FILE_PREFIX","GIT_CONFIG_FILE_REGEX","gitConfigFiles","dataLoaded","dataLoadedProgress","allEntryFolders","allEntries","getEntriesByPath","findEntryByPaths","entriesByPath","entryParseErrors","STALE_TEMP_FILE_AGE","getPathRegex","deleteStaleTempFile","fileHandle","lastModified","dirHandle","scanDir","currentPath","hasMatchingPath","scanningPathsRegEx","fileHandles","pathRegexCache","scanningPaths","collectScanningPaths","entryPaths","filePathMap","folderPathMap","assetPaths","getAllFiles","runConcurrently","work","concurrency","mapConcurrently","results","isEntryCollection","isFileCollection","isSingletonCollection","isArrayFileCollection","isValidCollection","isValidCollectionFile","getValidCollectionFiles","DEFAULT_INDEX_FILE_NAME","indexFileCacheMap","getIndexFileName","indexFile","getIndexFile","appLocale","isCollectionIndexFilePath","isCollectionIndexFile","BUILTIN_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","warnedOnceMap","warningMessages","warnDeprecation","MARKDOWN_EXTENSIONS","TEMPLATE_ENGINE_EXTENSIONS","ALLOWED_FRONTMATTER_EXTENSIONS","FORMAT_EXTENSION_MAP","EXTENSION_FORMAT_MAP","FRONTMATTER_DELIMITER_MAP","FRONTMATTER_FORMATS","BUILTIN_FILE_FORMATS","TOML_FORMATS","DEFAULT_INDEX_FILE_NAMES","CONTENT_EXTENSIONS","normalizeIndexFileName","nestedFilterPath","getNestedConfig","rawCollection","nested","summary","subfolders","isNestedCollection","getMetaPathConfig","getNestedIndexFileName","getSharedEntryFileName","stripIndexFileName","indexFileName","usesCustomEntryPath","isNew","originalPath","getEntryDirPath","isDescendantPath","isNestedFolder","basePath","filterNestedEntries","LANG_FORMATTER_OPTIONS","getCanonicalLocale","canonicalLocale","getDirection","displayNamesCache","getLocaleLabel","displayLocale","formatterOptions","firstLetter","listFormatterCache","getListFormatter","effectiveOptions","getLocalePath","_i18n","omitDefaultLocaleFromFilePath","defaultLocale","detectFileExtension","detectFileFormat","getFilePathMatcher","escapedIndexFileName","separateIndex","indexSuffix","indexAlternative","entryMatcher","nestedDepth","fileMatcher","remainingDepth","entrySuffix","getEntryPathRegEx","allLocales","joinedNonDefaultLocales","localeFileMatcher","localeInBasePath","basePathMatcher","entryExtension","indexExtension","indexFileExtension","getSuffixMatcher","localeMatcherCopy","i18nMultiFile","i18nMultiRootFolder","i18nMultiFolder","getFrontMatterDelimiters","getIndexFileFormat","_indexExtension","_indexFormat","indexFormat","entryFormat","getFileConfig","dataFile","_extension","_format","_delimiter","bodyField","yamlQuote","_isEntryCollection","arrayFile","__extension","__format","_isFolderCollection","indexFileFormat","resolveFileConfig","collectionFile","isIndexFile","_file","I18N_STRUCTURES","LOCALE_ROOT_FOLDER_STRUCTURES","DEFAULT_LOCALE_KEY","DEFAULT_CANONICAL_SLUG","mergeI18nConfigs","siteConfig","collectionI18n","getOmitDefaultLocaleOption","DEFAULT_I18N_CONFIG","getDraftI18nConfig","draft","determineStructure","defaultStructure","createStructureMap","i18nEnabled","structure","determineDefaultLocale","specifiedDefault","determineInitialLocales","initialLocalesConfig","determineOmitDefaultLocale","omitDefaultLocale","structureMap","normalizeI18nConfig","specifiedDefaultLocale","saveAllLocalesConfig","canonicalSlugConfig","omitDefaultLocaleLegacy","omitDefaultLocaleFromPreviewPath","canonicalSlugKey","canonicalSlugTemplate","saveAllLocales","initialLocales","selectedCollection","collectionCacheMap","getValidCollections","collections","getFirstCollection","getThumbnailFieldNames","thumbnail","fields","fieldType","parseEntryCollection","parseFileCollection","__i18n","__file","getSingletonCollection","singletons","getCollection","entryCollection","fileCollection","getCollectionLabel","singularLabel","_type","useSingular","getCollectionIndex","getCollectionFile","_collection","resolveCollectionAndFile","getCollectionFileLabel","getCollectionFilesByEntry","getCollectionFileEntry","folderInfo","validPaths","getCollectionFileIndex","getWildcardKeyPathPattern","isKeyPathWithin","sortedKeyCacheMap","getSortedKeys","sorted","valueMap","getKeysByPrefix","live","low","high","mid","LIST_ITEM_KEY_REGEX","listItemKeyCacheMap","getListItemKeys","STRING_KEY_PREFIX","INDEX_KEY_REGEX","isNumericStringKey","prefixStringKey","restoreStringKeys","unflattenKeys","unflattenMap","isValueEmpty","isPlaceholder","getSubtreeEntries","getSubtree","deleteSubtree","setSubtree","hasMultipleInMediaLibraries","mediaLibraries","libs","lib","hasMultipleInMediaLibrary","mediaLibrary","isMultiple","_cmsConfig","fieldConfig","NUMERIC_VALUE_REGEX","isNumeric","toFixed","factor","TYPE_MATCH_REGEX","LIST_KEY_PATH_REGEX","fieldConfigCacheMap","hasRootField","isFieldMultiple","parseExplicitType","typeName","resolveNextSegment","explicitType","pendingExplicitType","isNumericKey","cleanKey","isWildcardKey","subField","subFields","subFieldName","keyPathArray","segmentIndex","resolvedType","typeKey","getField","cacheKey","regularFields","currentExplicitType","hasVariableTypeField","getTypedKeyPath","parentKeyPath","currentKeyPath","parentField","parentFieldType","getFieldKind","isFieldRequired","getCurrentValue","isList","isCustomFieldType","itemKeys","getLineColFromPtr","ptr","makeCodeBlock","codeblock","numberLen","column","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","parse","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","stringify","numbersAsFloat","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","ch","Directives","yaml","isValid","verbatim","tagEntries","tagNames","visit$1","anchorIsValid","anchorNames","anchors","findNewAnchor","exclude","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","indent","lineComment","FOLD_FLOW","FOLD_BLOCK","FOLD_QUOTED","foldFlowLines","lineWidth","minContentWidth","endStep","folds","escapedFolds","indentAtStart","overflow","escStart","escEnd","consumeMoreIndentedLines","onOverflow","onFold","getFoldOptions","isBlock","containsDocumentMarker","lineLengthOverLimit","limit","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","test","compat","stringifyString","_stringify","defaultKeyType","defaultStringType","createStringifyContext","getTagObject","testMatch","stringifyProps","stringifyPair","keyComment","simpleKeys","explicitKey","allNullValues","keyCommentDone","chompKeep","vsb","vcb","valueComment","indentSeq","valueCommentDone","valueStr","vs0","nl0","hasNewline","flow","hasPropsLine","sp0","warn","logLevel","warning","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","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","timestamp","year","month","day","hour","minute","second","millisec","schemas","schema$1","schema$2","tagsByName","float$1","floatExp$1","floatNaN$1","int$1","intHex$1","intOct$1","merge$2","coreKnownTags","getTags","schemaTags","schemaName","customTags","addMergeTag","sortMapEntriesByKey","Schema","resolveKnownTags","toStringDefaults","sortMapEntries","stringifyDocument","hasDirectives","contentComment","dc","Document","_replacer","assertCollection","asStr","anchorPrefix","setAnchors","sv","jsonArg","contents","YAMLError","YAMLParseError","YAMLWarning","prettifyError","col","lineStr","trimStart","pointer","resolveProps","spaceBefore","atNewline","startOnNewline","hasSpace","commentSep","reqSpace","tab","newlineAfterProp","comma","indicator","cb","parentIndent","containsNewline","flowIndentCheck","fc","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","splitLines","chompStart","trimIndent","prevMoreIndented","crlf","strict","resolveFlowScalar","_onError","rel","plainValue","singleQuotedValue","doubleQuotedValue","valueEnd","badChar","unfoldLines","trimEnd","trimBoth","lm","foldNewline","cc","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","lastChar","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","detectedFrontMatterFormats","getSavedFileConfig","parseJSON","parseTOML","libParseTOML","parseYAML","libParseYAML","detectFrontMatterFormat","DOUBLE_BRACE_JSON_FRONT_MATTER_REGEX","parseJSONFrontMatterHead","trimmedHead","frontMatterRegexCache","parseFrontMatter","bodyKey","bodyInline","startDelimiter","endDelimiter","fmDelimiters","parsedHead","parseEntryFile","customParser","detectedFormat","yieldToMain","scheduler","runInChunks","chunkSize","SLUG_TEMPLATE_TAG_REGEX","slugRegexCache","getSlug","subPathTemplate","regexPattern","parseFileContent","errors","transformRoot","fieldName","i18nSingleFile","rawContent","normalizeDefaultRootContent","nonDefaultLocales","defaultContent","transformRawContent","shouldSkipIndexFile","extractPathInfo","isMultiFileStructure","locPath","fullPathRegEx","processNonI18nEntry","processI18nSingleFileEntry","processI18nMultiFileEntry","canonicalSlug","localizedEntry","tempId","existingEntry","entryMap","arrayFileItems","createArrayItemEntry","i18nSingleFileDefaultRoot","prepareArrayFileEntries","prepareEntry","isArrayFile","effectiveRawContent","isI18nSingleFile","transformedContent","entryArgs","prepareEntries","entryFiles","getEntryFolderCache","fileMap","regexFolders","_allEntryFolders","getEntryFoldersByPath","createFileList","assetFiles","configFiles","fileInfo","entryFolder","allFiles","describeFileList","createDebugLogger","startTime","lastTime","details","MAX_FILE_SIZE","FILE_PROCESS_CONCURRENCY","parseTextFileInfo","parseAssetFileInfo","cachedHashes","sha","newHashes","readCachedHashes","hashCacheDB","updateCachedHashes","stalePaths","currentPaths","loadFiles","log","cachedHashesPromise","fileList","entryFileItems","configFileItems","LOCALHOST_REGEX","isSecureURL","baseURL","protocol","sendRequest","response","responseType","ok","retries","refreshAccessToken","initUserEnvDetection","userAgentData","brand","platform","mqlSmall","matchMedia","mqlMedium","mqlLarge","mqlPointer","isSmallScreenSetter","isMediumScreenSetter","isLargeScreenSetter","hasMouseSetter","opensOnClick","RENAME_ATTEMPTS","RENAME_RETRY_DELAY","canMoveFile","writeFile","writer","moveFile","newDirname","newBasename","oldDirname","oldBasename","newFileHandle","oldDirHandle","renameFile","attempt","pendingRename","isNotFoundError","deleteEmptyParentDirs","dirName","parentPath","parentHandle","_entry","deleteFile","deleteEmptyDirs","dirPaths","saveChange","isEntryChange","saveChangeBatch","saveChanges","assetChanges","entryChanges","BACKEND_NAME","BACKEND_LABEL","DEFAULT_API_ROOT","DEFAULT_AUTH_ROOT","DEFAULT_AUTH_PATH","MIN_GITEA_VERSION","USER_STORAGE_KEY","LEGACY_USER_STORAGE_KEYS","user","_user","apiConfig","graphqlVars","requestAccessToken","tokenURL","includeCredentials","pendingRefreshes","requestTokenRefresh","clientId","refreshToken","fetchAPI","isGraphQL","graphqlBaseURL","restBaseURL","authScheme","account","fetchGraphQL","fetchUserProfile","fieldMap","getUserProfile","inAuthPopup","createAbortError","openPopup","availHeight","availWidth","authURL","authorize","authPopup","backendName","origin","provider","resultStr","initServerSideAuth","siteDomain","createAuthSecrets","codeVerifier","codeChallenge","initClientSideAuth","redirectURL","csrfToken","sendMessage","_state","onMessage","finishClientSideAuth","handleClientSideAuthPopup","realAuthURL","handleAuthFlow","authType","backend","authArgs","authScope","inPopup","auto","getTokens","signInToBackend","sharedApiConfig","signOut","getTokenPageURL","signIn","getUserProfile$2","NOT_COLLABORATOR_ERROR_MESSAGE","LocalizedError","createLocalizedError","getErrorMessage","encodePath","PREFS_STORAGE_KEY","AUTO_PREF_VALUE","prefsError","prefs","storedLocaleApplied","navigatorLocale","_prefs","devMode","autoTheming","autoTheme","localePref","appLocales","previousLocale","switchedByUser","REPOSITORY_INFO_PLACEHOLDER","API_PATH_REGEX","getRepoURL","restApiRoot","repoPath","getScopedBaseURLs","urls","getBaseURLs","initRepositoryInfo","service","defaultApiRoot","applyDefaultBranch","repositoryInfoCache","lastBranchResponse","getRepositoryInfo","userId","fetchBranch","checkRepositoryAccess","permissions","checkBranchAccess","_branch","fetchDefaultBranchName","getBaseURLs$2","instance","FIRST_NEW_GITEA_MAJOR_VERSION","probeForgejo","redirected","checkInstanceVersion","versionStr","isForgejo","minVersion","FORK_POLL","isOpenAuthoringConfiguredFor","resolveWorkflowRepository","ensureForkPermission","allowForking","pollForFork","checkFork","attemptsLeft","runOpenAuthoringSetUp","setUp","checkPublishAllowed","checkDirectCommitAllowed","checkStatusAllowed","checkMergedBranch","fetchBranchHead","mergedSHA","deleteBranch","pruneForkBranches","leftover","classify","updateForkStatusWith","pullRequest","requestKey","createRequest","fetchRequest","merged","isEntryRequest","getMergedSHA","applyStatus","createDraftPullRequest","MAX_FORKS","isOpenAuthoringConfigured","getWorkflowRepository","toRepositoryPath","fullName","fetchRepositoryAccess","fetchForkByName","userName","fetchForkBySearch","login","fetchFork","fetchForkingAllowed","isRepositoryNameTaken","createFork","endpoint","retryEx","fetchForgejoSyncState","forkCommit","baseCommit","syncFork","checkForkBranch","setUpOpenAuthoring","canWrite","existingFork","initOpenAuthoring","DEFAULT_COMMIT_MESSAGES","SKIP_CI_REGEX","hasSkipCIMarker","fillTemplate","createCommitMessage","customCommitMessages","skipCIEnabled","autoDeploy","firstSlug","firstPath","remainingPaths","collectionLabel","commitType","authorValues","email","skipCI","dedupeFileCommits","commitMap","commits","assertBranchNotMoved","fetchLastCommit","expectedHead","fetchPerPathCommits","fetchHistory","parseCommit","repositoryHead","getKnownSha","previousSha","workflowBranch","knownPath","commitChanges","commitMessage","startBranch","savedFiles","fetchFileCommits","fetchAPIOrUndefined","deferRejection","getFileKey","arrayIndex","reconcileEntries","previousByPath","claimed","previousPaths","changedPaths","reconcileAssets","fetchedPaths","shadow","workflowAsset","published","previousPublished","getEntryPaths","includePrevious","getEntryFolderPath","canMergeFiles","planEntryReparse","sharedPaths","getReusableEntry","mergeable","_path","reusedEntries","dirtyFiles","mergeableCache","mergeableGroups","mergeEntries","parsedByPath","parsedEntries","reusedEntry","parseFileInfo","fetchedFileMap","getFilePaths","updateStores","applyFileMetadata","metadataMap","entriesChanged","assetsChanged","parseEntryFiles","parseFiles","getFileList","lastConfigHash","cachedConfigHash","cachedCommitHash","gitConfigFetched","metaEntries","lastCommitHash","cachedFileEntries","fetchFileList","saveFileListMeta","metaDB","advanceRepositoryHead","restoreCachedFileData","cachedFiles","updateCache","usedPaths","unusedPaths","fetchingFiles","cacheDB","readDatabaseEntries","completeMetadata","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","shas","resetDeployments","setLastCommitPublishHint","lastParseKey","getParseKey","resolveHead","lastCommit","accessPromise","branchPromise","lastCommitPromise","fetchedCommit","loadContents","contentFiles","finishLoad","updateStores$6","readyMessage","startCacheUpdate","fetchAndParseFiles","fetchers","incremental","initialLoad","checkAccess","databaseEntriesPromise","branchAccessPromise","finishArgs","fetchRepositoryFiles","toFileListItems","DEFAULT_MAX_BLOB_SIZE","dirLookups","MAX_DIR_LOOKUPS","lookUpDirSHA","fetchDirSHA","commitRef","treeSHA","requestPath","gitEntries","truncated","parseFileContents","encoding","fetchRawFile","createBatches","batchSize","encodedSize","maxItems","maxResponseSize","idField","textFiles","pagingNum","maxResponseItems","maxBlobSize","blobSizeLimit","oversizedFiles","fetchedCount","advanceProgress","itemMap","repositoryAccessPromise","fetchFiles","isOpenAuthoringConfigured$2","repository$3","checkBranchAccess$2","fetchDefaultBranchName$2","fetchLastCommit$2","fetchFileList$2","fetchFileContents$2","PULL_REQUEST_DESCRIPTION","isSquashMergeEnabled","deleteRemoteBranch","goneStatuses","openWorkflowPullRequest","createPullRequest","saveWorkflowBranch","commitToExistingBranch","commitToNewBranch","commitToNewWorkflowBranch","commitFromStart","branchExistsStatus","commitOnBranch","findOpenPullRequest","inUseMessage","assertBranchAtHead","headSHA","getParentDirs","toChangedFilesWithModes","changedFiles","statusMap","fetchFileModes","getLabelPrefix","getKnownLabelPrefixes","getStatusLabel","getAllStatusLabels","getStatusFromLabels","DEFAULT_MAX_RESPONSE_ITEMS","MAX_PAGES","pageSize","getPageSize","fetchPages","fetchAllPages","WIP_TITLE_REGEX","WIP_TITLE_PREFIX","STATUS_LABEL_COLORS","STATUS_LABEL_DESCRIPTION","stripWipPrefix","isSameRepositoryPullRequest","parsePullRequest","fetchPullRequestHeadRef","FILE_LIST_POLL","BOARD_FILE_LIST_ATTEMPTS","getListedCommit","fetchChangedFiles","listedCommits","complete","fetchPullRequestFileList","decodeFileText","fetchPullRequestFileContent","fetchPullRequestFileContents","deleted","createStatusLabel","applyLabels","statusLabel","updateLabels","cmsLabels","updateDraftState","isDraft","baseBranch","getSourcePath","fetchFileSHA","resolveChangeSHAs","shaMap","_previousPath","_previousSha","WORKFLOW_BRANCH_PREFIX","joinPrefix","getBranchPrefix","getBranchListPrefix","encodeSlug","decodeSlug","getBranchName","parseBranchName","listPrefix","isEntryBranch","fetchForkBranchList","isForkPullRequest","fetchForkPullRequestMap","existing","parseForkBranch","inReview","author","fetchForkBranchFileList","commitFiles","fetchForkPullRequests","pullRequests","mergedHeads","reopenPullRequest","fetchForkRequestState","applyForkStatus","updateForkStatus","fetchBranchHead$2","deleteBranch$2","fetchLabelledPullRequests","statusLabels","labelIds","numbers","fetchPullRequests","fetchOpenPullRequest","freshChanges","openPullRequest","getWorkflowRepository$2","savePullRequest","commitToNewBranch$1","commitToExistingBranch$1","createPullRequest$2","updateStatus","REST_FILE_STATUSES","CONTENT_TYPE_MODES","fetchMergeState","onConfiguredBranches","fetchFileModes$1","fetchUnchangedPaths","unchanged","isPullRequestMerged","workflow_default$2","fetchPullRequests$3","savePullRequest$2","updateStatus$2","fetchMergeState$2","fetchUnchangedPaths$2","squash","initGitBackend","authRoot","authPath","api","tokenPath","getPublishMode","isWorkflowConfigured","gitea_default","projectPath","getTokenPageURL$2","signIn$4","signOut$3","fetchFiles$5","fetchBlob$4","fetchDirSHA$2","commitChanges$4","fetchFileCommits$2","DEFAULT_PKCE_AUTH_ROOT","DEFAULT_PKCE_AUTH_PATH","normalizeRestBaseURL","normalizeGraphQLBaseURL","getUserProfile$1","NO_ACCESS_STATUSES","isRateLimited","headers","FETCH_BRANCH_ACCESS_QUERY","FETCH_DEFAULT_BRANCH_NAME_QUERY","getBaseURLs$1","hasPendingInvitation","invited","getNoAccessMessage","scopes","isPrivate","repoOwner","forkOwner","forkRepo","FETCH_USER_FORK_QUERY","fetchForkFromNetwork","waitForFork","toggleListItem","included","include","splitIntoChunks","buildAliasedQuery","innerQuery","useBranch","fetchAliasedBatch","getFragment","chunk","FETCH_LAST_COMMIT_QUERY","branchName","MAX_GRAPHQL_BLOB_SIZE","getExpectedHeadOid","headOid","splitAdditions","additions","deletedPaths","addition","createCommit","onWorkflowBranch","expectedHeadOid","deletions","fileShas","groupIndex","FILE_COMMITS_CHUNK_SIZE","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","description","best","resolveDeployments","validTargets","candidateMap","triggerDeployment","MAX_ITEMS","STATUS_STATE_MAP","DEPLOYMENT_STATE_MAP","CHECK_CONCLUSION_MAP","PREVIEW_CHECK_NAME_REGEX","fetchBranchHeadSHA","fetchCommits","SOURCES","mapped","targetUrl","latestStatus","environment","suite","conclusion","detailsUrl","askSeparately","collectTogether","collectOneByOne","collectCandidates","fetchDeployments","PROGRESS_TIME_PER_FILE","startSimulatedProgress","fileCount","progress","interval","fetchTree","recursive","treeRef","blobs","tooBig","subtrees","FETCH_DIR_SHA_QUERY","CHUNK_SIZE","getFileContentsFragment","getFileMetadataFragment","requestBlob","fetchBlobText","truncatedFiles","isTruncated","parseFileMetadata","committedDate","fetchInChunks","stopProgress","isOpenAuthoringConfigured$1","initOpenAuthoring$1","repository$2","checkBranchAccess$1","fetchDefaultBranchName$1","fetchLastCommit$1","fetchFileList$1","fetchFileContents$1","STATUS_DASHBOARD_URL","STATUS_CHECK_URL","checkStatus","parseFileNodes","changeType","parseRestFiles","FILES_CHUNK_SIZE","fetchPullRequestFiles","workflowRepository","FETCH_BRANCH_HEAD_QUERY","newLabels","getFetchForkBranchesQuery","BRANCH_PULL_REQUESTS_CHUNK_SIZE","getForkPullRequestsFragment","fetchForkBranchPullRequests","databaseId","fetchForkBranches","headOwner","renamed","FETCH_PULL_REQUEST_STATE_QUERY","nodeId","fetchBranchHead$1","deleteBranch$1","getPullRequestFields","getFetchPullRequestsQuery","toPullRequest","FETCH_BRANCH_BASE_QUERY","CREATE_REF_MUTATION","getFetchOpenPullRequestsQuery","fetchOpenPullRequests","isCrossRepository","resetBranch","createBranch","createPullRequest$1","MAX_COMPARE_FILES","dirs","trees","github_default","checkStatus$1","graphqlApiRoot","getTokenPageURL$1","signIn$3","fetchFiles$4","fetchBlob$3","fetchDirSHA$1","commitChanges$3","fetchFileCommits$1","triggerDeployment$1","fetchBranchHeadSHA$1","fetchDeployments$1","fetchPullRequests$2","savePullRequest$1","updateStatus$1","refs","REPO_PATH_REGEX","parseProjectPath","getProjectId","getBranchPath","FETCH_USER_PERMISSIONS_QUERY","fetchProjectPermissions","projectIds","fetchProjectDetails","project","forkingAccessLevel","FORK_READY_STATUSES","importStatus","isForkPathTaken","createForkError","actions","startProject","avatarURLCache","fetchAvatarURL","avatarURL","projectId","commitList","uniqueEmails","avatarMap","DEPLOYMENT_WINDOW","COMMIT_STATUS_MAP","DEPLOYMENT_STATUS_MAP","collectDeploymentCandidates","updatedAfter","collectStatusCandidates","targetURL","collectSafely","getFetchFileListQuery","endCursor","hasNextPage","FETCH_SUBTREES_QUERY","pageInfo","FETCH_BLOBS_QUERY","fetchBlobBatch","midPoint","firstHalf","secondHalf","fetchBlobNodes","isSelfHosted","batchPaths","fetchBlobs","textPaths","repository$1","DRAFT_TITLE_REGEX","DRAFT_TITLE_PREFIX","stripDraftPrefix","getCanMerge","toMergeRequest","username","parseMergeRequest","parseDiff","fetchMergeRequestFileList","mergeRequest","FETCH_MERGE_PERMISSIONS_QUERY","fetchMergePermissions","iidMap","mergeRequests","iid","userPermissions","fetchMergeRequestFileContents","blobMap","fetchOpenMergeRequests","sourceId","targetId","fetchMergeRequest","isFromForkToBranch","isForkMergeRequest","fetchForkBranchMergeRequests","branchSet","branchInfo","authorName","authorEmail","diffs","branchList","getStatusChange","applyStatusChange","MERGE_REQUEST_EXISTS_STATUS","fetchOpenForkMergeRequest","createForkMergeRequest","TRANSIENT_MERGE_STATUSES","MERGE_STATUS_POLL","AUTO_MERGE_WAIT_STATUSES","AUTO_MERGE_POLL","openMergeRequest","newLabel","fetchMergeStatus","cancelAutoMerge","waitForAutoMerge","autoMerge","getDiffStatus","targetBranch","changesCount","FETCH_BLOB_IDS_QUERY","gitlab_default","signIn$2","fetchFiles$3","fetchBlob$2","commitChanges$2","oid","gitBackendServices","github","gitlab","gitea","getRepositoryDatabase","remoteRepository","REPOSITORY_PROPS","ROOT_DIR_HANDLE_KEY","rootDirHandleDB","assetHashDB","getRootDirHandle","forceReload","showPicker","local_default","label$1","backendName$1","TEST_BACKEND_ROOT_DIR_NAME","TEST_BACKEND_NAME","test_default","allBackendServices","unsupportedBackends","validBackendNames","selectBackend","builtinReplacements","danishNorwegianReplacements","localeReplacements","escapeRegex","buildReplacementPattern","sortedKeys","replacements","defaultPattern","localeCache","localeMap","normalizeLocale","normalizedLocale","transliterate","customReplacements","UNSAFE_UNICODE_SLUG_CHARS_REGEX","UNSAFE_ASCII_SLUG_CHARS_REGEX","TRANSLITERATION_LOCALES","UNSAFE_CHARS_REGEXES","slugReplacementRegexCache","slugify","maxLengthParam","cleanAccents","sanitizeReplacement","maxLengthOption","trimReplacement","maxLength","trimPattern","escapedReplacement","cachedSlugRegexes","lowercase","getNewFolderName","validateNewFolderName","trimmedName","folderName","takenNames","findLibraryOptions","libraryName","legacyOptions","legacyName","mergeLibraryOptions","fieldOptions","siteOptions","resolveLibraryOptions","getMediaLibraryOptions","siteLibName","getFieldOptions","fieldLib","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","HEADER_LENGTH","HEIF_BRANDS","AVIF_BRANDS","startsWith","signature","readTag","getBrands","boxSize","brands","sniffRasterImageFormat","scriptURL","getUnpkgURL","libVersion","loadModule","library","getLeafletMarkerIconURL","getChunkURLs","devChunkLoaders","loadChunk","lastError","encodingSupportMap","checkIfEncodingIsSupported","canvas","exportCanvasAsBlob","imageData","encode","quality","IDLE_TIMEOUT","workerPromise","workerUnavailable","idleTimer","queue","getWorkerScript","moduleURL","WorkerUnavailableError","createWorker","worker","getWorker","terminateWorker","decodeInWorker","decodeOnMainThread","decode","decodeBuffer","decodeHEIC","job","calculateResize","originalWidth","originalHeight","targetWidth","targetHeight","isSmaller","scale","newWidth","newHeight","fit","resizeCanvas","THUMBNAIL_TRANSFORM_OPTIONS","createImageSource","image","createVideoSource","video","createSource","createFallbackImageBitmap","transformImage","naturalWidth","naturalHeight","optimizeSVG","optimize","normalizeFileNameTemplate","getDefaultMediaLibraryOptions","fileNameTemplate","transformations","toRasterImageFormat","getRasterImageFormats","declaredFormat","canConvertHEIC","getAcceptedImageTypes","getAcceptedFileTypes","transformFile","sourceFormat","formatTransformations","transformation","newFormat","newFileName","selectedSubfolderPath","focusedSubfolder","renamingSubfolder","deletingSubfolder","canBrowseSubfolders","getRelativePath","getSubfolderPath","resolveAssetFolderPath","knownFolder","folders","exactMatch","parentFolder","browsedDirPath","browsingCmsFolder","listSubfolders","getTakenNames","fileNames","getFolderBreadcrumbItems","subfolderNames","rootLabel","onBrowse","getOwnerFolderPath","getSubfolders","ownerFolderPath","getAssetsInDir","getUploadDirPath","subfolderPath","formatSubfolderName","slugificationEnabled","validateSubfolderName","normalizedName","taken","FULL_REGEX_PATTERN","STATEFUL_FLAGS_REGEX","getRegex","COMPARISON_OPERATORS","getViewConditions","conditions","operator","hasComparison","getConditionKey","operators","OTHER_GROUP_NAME","getGroupLabel","buildGroupMap","groupItems","matchesFilter","sortItemsByKey","keyedItems","aKey","bKey","isStringType","order","getCollapsibleGroupNames","getGroupingKey","isGroupCollapsed","view","setCollapsedGroups","_current","others","collapsedGroups","_previous","setGroupCollapsed","_name","collapsed","setAllGroupsCollapsed","initViewSettingsStorage","settingsDB","initial","defaults","storageKey","lastSaved","_settings","settingsState","filterAssets","groupAssets","partOptions","formatterCache","getFormatter","timeZone","getDateTimeParts","stripFieldTagPrefix","getFileNameParts","dotIndex","localeSuffixes","getFileNameLocaleSuffixes","characterEntitiesLegacy","characterReferenceInvalid","isDecimal","character","isHexadecimal","isAlphabetical","isAlphanumerical","decodeNamedCharacterReference","characterReference","parseEntities","settings","additional","point","following","begin","characterReferenceCharacters","characters","terminated","namedReference","reference","reason","referenceCode","prohibited","disallowed","flush","resolveNestedTemplateValues","innerTag","resolveTag","processNestedTemplates","newArgs","hasChanges","resolvedDefaultValue","truthyValue","resolvedTruthyValue","falsyValue","resolvedFalsyValue","exports","TIMEZONE_ENUM","configCacheMap","isCustomTimeZone","parseDateTimeConfig","dateFormat","timeFormat","pickerUTC","inputTimeZone","outputUTC","normalizedInputTimeZone","dateFormatStr","timeFormatStr","dateOnly","timeOnly","defaultMax","_inputTimeZone","normalizedConfig","dayjs","dayjsCustomParseFormat","dayjsLocalizedFormat","dayjsUTC","DATE_ONLY_REGEX","DATE_PART_REGEX","TRANSFORMATION_PARSERS","parseTransformation","splitTransformations","parsedTransformationsCache","parseTransformations","rawTransformations","applyUpperCaseTransformation","applyLowerCaseTransformation","applyDateTransformation","sValue","utc","applyDefaultTransformation","ternaryTransformation","applyTruncateTransformation","applyTransformation","applyTransformations","DATE_REGEX","TIME_SUFFIX_REGEX","DATE_FORMAT_OPTIONS","TIME_FORMAT_OPTIONS","DATE_TIME_FORMAT_OPTIONS","formatDate","dayjsTimeZone","isValidDate","getParser","parseWithFormatFallback","parseAsUTC","getDate","currentValue","displayFormatterCache","getDisplayFormatter","getDateTimeFieldDisplayValue","displayTimeZone","singleCustomTimeZone","getEntryFoldersCache","getEntryFolders","getAssociatedCollections","selectedEntries","selectedEntryIdSet","filterConditionCache","getFilterCondition","filter","matchesCollectionFilter","getPropertyValue","getListedCollections","entriesByCollectionCache","getCollectionBuckets","buckets","queryEntriesByCollection","getEntriesByCollection","entrySource","folderSource","countCollectionEntries","canCreateIndexFile","DEFAULT_ORDER_FIELD_KEY","isManuallyOrdered","getOrderFieldKey","reorder","getReorderGroupName","sortEntriesByOrderField","orderKey","keyed","optionLabelMapCache","getOptionLabelMap","labelMap","objectIdentityMap","nextObjectId","getObjectId","normalizeFieldName","isComplexListField","hasFields","hasTypes","getFieldReplacement","fallbackContext","getDisplayValue","getEntrySummaryFromContent","replaceTemplateFields","fieldNames","extractFieldNames","prepareFieldTemplates","valueField","displayFields","identifierField","searchFields","_valueField","_displayField","_searchField","allFieldNames","LIST_KEY_PATH_MATCH_REGEX","analyzeListFields","listFieldConfigs","baseFieldGroups","baseFieldName","fieldConfigForList","getFieldArgs","buildListItemOption","replaceWildcards","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","hasProcessedListFields","firstConfig","createSimpleOption","replacers","processEntry","refEntry","getFieldDisplayValue","hasListFields","FIELD_TEMPLATE_REGEX","listItemRegexCache","getFieldValue","resolveFilterValues","filters","currentSlug","currentLocaleValues","filterAndPrepareEntries","refEntries","hasContent","entryFilters","isEntrySlug","fieldKey","fieldValue","optionCacheMap","MAX_OPTION_CACHE_SIZE","optionsInProgress","mergedEntriesCache","withPendingEntries","pendingEntries","pendingCache","pendingEntry","buildOptions","getRefEntries","getOptions","resolvedFilters","resolvedKey","manuallyOrdered","getEntryOptions","getReferencedOptionLabel","optionLabelMap","getLabel","labelCacheMap","MAX_LABEL_CACHE_SIZE","optionsKeyCache","getOptionsKey","getOptionLabel","hasLabels","rawValues","getOptionValue","isOptionValue","getPreviewLabels","getOptionValueType","getEmptyOptionValue","firstValue","removeMarkdownSyntax","markdownParser","Marked","HTML_BLOCK_BOUNDARY_REGEX","stripMarkdown","numberFormatterCache","isRichTextField","stripItems","plainText","getVisibleFieldDisplayValue","visibleItemKeyPath","keyPathPrefix","_keyPath","commitDate","resolveRef","itemKey","subKeys","BODY_HEADER_REGEX","sanitizeEntrySummary","allowMarkdown","useBody","replaceSub","entryPath","commitAuthor","relationLabelResolved","replace","parsedTransformations","replaceSubContext","fallbackSummary","summaryCacheMap","lastAllEntries","entriesGeneration","getEntriesGeneration","formatEntrySummary","collectionSummaryTemplate","summaryTemplate","useTemplate","replaceContext","getEntrySummary","locale$5","optionCache","outerFlag","dependsOnEntries","handleDateTimeTag","dateTimeParts","handleUuidTag","handleSlugTag","handleFilePathTag","entryFilePath","pathAfterBase","lastSlashIndex","getRandomValue","randomValues","generate","replaceTemplateTag","dateTimeValue","_dateTimeParts","slugValue","assetFileName","filePathValue","replaceTemplatePlaceholder","hasDefaultTransformation","hasComplexNestedTemplateArgs","bailOnUnresolvableTag","getExistingSlugs","legacySlugLength","slugOptions","maxlength","trim","getAssetPathMap","_allAssets","getAssetByInternalPath","getAssetKey","unsaved","fillInternalPathTemplate","getAssetByRelativePathAndCollection","fieldFolder","folderOptions","mediaFolder","publicFolder","entryContent","normalizedMediaFolder","localPath","resolvedPath","normalizedPublicFolder","getAssetByRelativePath","collectionFiles","publicPathRegexCache","getPublicPathRegex","publicPath","getAssetByAbsolutePath","baseName","findInFolder","_collectionName","scanningFolders","foundAsset","matchingFolder","isRelativePath","getAssetByPath","isAssetInFolder","getAssetsByFolder","getAssetsByDirName","getDuplicateFiles","existingNames","SVG_NS","readAsDataURL","isFixedLength","parseViewBox","createInertSVG","isSVG","attributeNames","viewBox","PDFJS_DIST_URL","PDFJS_MODULE_URL","PDFJS_WORKER_URL","PDFJS_GET_DOC_OPTIONS","pdfjs","renderPDF","loadingTask","pdfPage","cachedBlobs","pendingAssetBlobs","XML_TYPE_REGEX","getDisplayBlob","createDisplayBlobURL","cacheAssetBlobURL","displayBlob","cacheAssetBlob","downloadOnce","download","downloadAssetBlob","fetchAssetBlob","readHandle","getAssetBlob","getThumbnailSourceBlob","getAssetBlobURL","thumbnailDB","pendingThumbnailBlobs","initThumbnailDB","resolveThumbnailBlob","thumbnailBlob","isPDF","hasCachedThumbnail","getAssetThumbnailURL","cacheOnly","cachedBlob","pendingRevocations","flushRevocations","revokeBlobURLIfNeeded","isFirst","revokeAssetBlobURLIfNeeded","replaceTemplatePath","groupNames","groupName","newGroupName","resolvePublicFolder","getEntryRelativePath","assetFolderPath","entryFolderPath","getAssetPublicURL","pathOnly","encodingEnabled","publicBasePath","allowSpecial","getFolderPublicPath","getFolderKey","getRelativeKey","encodeKey","encodeSegment","filterAssetsByQuery","lowerQuery","maxPages","pageResults","fetchPage","assertResponseOK","allowNotFound","errorText","fetchListing","credential","filterByKind","listObjects","browseObjects","searchObjects","uploadObjects","uploadedObjects","sanitizedName","deleteObjects","replaceObject","getRenamedPath","newName","createObjectStorageOperations","ObjectStorageService","libOptions","serviceId","serviceLabel","serviceURL","developerURL","apiKeyURL","apiKeyPattern","resolveConfig","isConfigured","isConfigURL","operations","newPath","parseXml","nodeToObject","toArray","DEFAULT_ENDPOINT_SUFFIX","MAX_RESULTS","trimSlashes","buildContainerUrl","accountName","container","buildRequestUrl","searchParams","buildBlobRequestUrl","requireToken","parseBlobResults","publicUrl","containerUrl","properties","displayKey","encodedKey","blobUrl","downloadURL","listBlobPage","putBlob","deleteBlob","azureBlobStorage","Name","isEnabled$2","isAssetURL$2","list$5","search$4","upload$1","deleteFiles","createEmptyFolder","removeFolder","activated","consoleLoaded","dialogOpen","CONSOLE_BASE_URL","FRAME_ORIGIN","FRAME_SRC_PARAMS","CONFIG_PROPS","getLibraryOptions","getMergedLibraryOptions","getCloudConfig","cloudName","apiKey","cloudinary_default","toHex","hmacSha256","encoder","cryptoKey","encodeRfc3986","generateAwsSignature","urlObj","amzDate","dateStamp","canonicalUri","canonicalQueryString","canonicalHeaders","signedHeaders","canonicalRequest","payloadHash","credentialScope","stringToSign","signatureHex","secretAccessKey","accessKeyId","signedRequest","extraHeaders","authorization","buildObjectUrl","bucket","forcePathStyle","isS3ObjectUrl","encodeKeyPath","buildObjectApiUrl","getAclHeader","acl","requireSecretAccessKey","parseS3Results","objects","baseUrl","listS3Page","putS3Object","fileContent","deleteS3Object","Key","s3Operations","S3CompatibleService","definition","objectAcl","requiredOption","awsS3","backblaze_b2_default","bunny_storage_default","JURISDICTION_INFIXES","getEndpoint","accountId","jurisdiction","cloudflare_r2_default","digitalocean_spaces_default","scaleway_default","getPublicUrl","supabase_default","formatFileName","originalName","assetNamesInSameFolder","getPublicKey","isEnabled","parseResults","cdnBase","isImage","isVideo","defaultOperations","autoFilename","getKeys","secretKey","publicKey","secretKeyRequired","getRESTHeaders","nextUrl","generateSignature","expire","allCloudStorageServices","backblazeB2","bunnyStorage","cloudflareR2","digitaloceanSpaces","scaleway","supabase","list$4","search$3","formData","CLOUD_MEDIA_LIBRARY_NAMES","URL_REGEX","getAssetBaseURL","getMediaFieldSource","assetBaseURL","getSourceURL","getMediaFieldURL","getRichTextMediaSource","customComponentNames","componentNames","getRichTextMediaURL","MARKDOWN_IMAGE_REGEX","getComparableAssetURL","createMatcher","matcher","getMatchingTargets","getNewURL","mayReferToTargets","matchField","replacing","replaced","findAssetReferences","exhaustive","every","isDone","matchArgs","onMatch","getEntriesByAssetURL","getEntriesByAssets","getAssetReferences","references","extractExifData","exif","DateTimeOriginal","latitude","longitude","probeSource","eventType","getInfo","getImageSourceInfo","getMediaSourceInfo","getSourceInfo","getMediaMetadata","cachedDetails","getExternalAssetDetails","getExternalAssetUsedEntries","CONCURRENCY","externalAssetAvailability","checkedIds","probeURL","isMixedContent","checkExternalAssetAvailability","checkExternalAssetsAvailability","unchecked","LINKED_FILES_SERVICE_ID","isLinkedURL","isAssetURL","createLinkedAsset","getFieldWidgets","collectLinkedAssets","widgets","linkedAssets","linkedFilesService","enabledCloudServices","getCloudService","getCloudServicePath","getExternalAssetPath","canPreviewExternalAsset","mergeUploadedExternalAssets","uploadedIds","uploaded","selectedCloudService","externalAssets","hasFolderSupport","externalFolders","selectedExternalDirPath","focusedExternalSubfolder","showNewExternalFolderDialog","renamingExternalSubfolder","deletingExternalSubfolder","externalAssetCounts","externalAssetsError","selectedExternalAssets","selectedExternalAssetIdSet","focusedExternalAsset","pruneExternalAssetSelection","kept","keep","selectedOrFocusedExternalAssets","overlaidExternalAssetId","renamingExternalAsset","externalAssetSearchTerms","getFetchOptions","password","hasAuthInfo","resetExternalAssets","browseExternalFolder","assetListSettings","defaultView","currentView","getSettingsKey","initSettings","savedView","sortAssets","_assets","showAssetOverlay","showUploadAssetsDialog","showNewSubfolderDialog","showUploadAssetsConfirmDialog","getFolderLabelByCollection","selectedFolderAssets","listedAssets","listedSubfolders","folderSummary","subfolder","getAdjacentAssets","isCurrent","previousAssetGroups","sortConditions","filterConditions","groupConditions","sortedAssets","filteredAssets","assetGroups","listedAssetIndexMap","_backend","initSettings$2","filterConditions$2","showContentOverlay","showDuplicateToast","activeInlineEditors","translatorApiKeyDialogState","copyFromLocaleToast","editorFirstPane","editorSecondPane","selectAssetsView","decodeSafely","decoder","sequence","decodeURISafely","uri","decodeURIComponentSafely","openNewTab","features","noopener","hasOverlay","selectedPageName","announcedPageStatus","mainAreaTitle","overlayTitle","encodeRoutePath","parseLocation","activeTransition","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","MIN_CHECK_GAP","lastCheckTime","commitCount","diffStores","entryIds","entriesBefore","assetsBefore","entriesAfter","assetsAfter","entryIdsAfter","assetPathsAfter","rootDirTree","isRootDirUnchanged","checkForRemoteChanges","maxAge","suspendChecksWhile","REMOTE_CHECK_INTERVAL","checkOnSchedule","checkOnReturn","startRemoteChangePolling","stopRemoteChangePolling","timer$1","POLL_INTERVAL","UNKNOWN_GRACE_DURATION","PING_TTL","pageLiveness","MAX_CACHED_PAGES","prune","cutoff","dropped","pingURL","sameOrigin","resetPageLiveness","getSkipCIOptions","skipCIConfigured","workflowEnabled","isWorkflowEnabled","unpublishedEntries","unpublishedEntriesLoading","unpublishedEntriesLoaded","publishingBranches","workflowDataReady","getUnpublishedEntriesByCollection","getUnpublishedEntry","getUnpublishedEntryBySlug","unpublishedEntry","getUnpublishedEntryByBranch","getUnpublishedEntryByDraft","originalEntry","isWorkflowDraft","isPendingDeletion","canMergePullRequest","isPublishAllowed","swapUnpublishedEntries","drafts","draftMap","mergeUnpublishedEntries","swapped","swappedIn","unpublished","getPublishedVersion","hasPublishedVersion","checkPublishedVersion","report","currentToken","runCount","cancelDeployResolution","getDeployTargets","prodSHA","prBranch","deployTargets","canResolveDeployments","showLinks","isFresh","markChecking","markLookupPending","pendingOnly","refreshProductionSHA","initDeployments","mergedEntries","isBuildDone","productionBuildDone","deployingEntries","lastDone","trackDeployingEntry","resetDeployingEntries","getEntryAssetVersion","mergeWorkflowAssets","assetMap","removeWorkflowAssets","publishWorkflowAssets","_workflow","publishedAsset","completeEntry","publishedEntry","vacatedPaths","targetFiles","removedPaths","convertPullRequests","isWorkflowReady","backendConfig","startLoadingPullRequests","loadUnpublishedEntries","MAGIC_LINK_REGEX","auth","clearUserCache","clearIntegrationCredentials","clearUserCacheIfNeeded","resetError","logError","parseMagicLink","encodedData","copiedPrefs","getUserCache","userCache","getBackend","confirmMagicLink","confirmed","copyMagicLinkPrefs","loadRepositoryData","signInAutomatically","magicLinkUser","verified","signInManually","_backendName","getSignInOptions","isTestRepo","authMethods","appId","backendLabel","Sign_in","showTokenDialog","configuredBackend","repositoryName","showLocalBackendOption","trimmedToken","showWorkflowNote","$$d","tokenOptionHidden","oauthOptionHidden","oauthOptionDisabled","magicLinkAccountName","text_3","consequent_8","text_4","consequent_9","$3","text_6","consequent_10","consequent_11","text_5","node_16","IMAGE_DATA_URL_REGEX","DEFAULT_APP_TITLE","DEFAULT_APP_LOGO_URL","SveltiaLogo","appTitle","appLogoURL","appLogoType","getDataURL","appIconURLs","superseded","logoURL","iconURLs","small","large","appManifestURL","manifest","parseMarkdown","Entrance_page","dataFetchError","text_2","div_8","div_9","div_10","div_11","root_7","text_7","Backend_status_indicator","startChecking","stopChecking","PACKAGE_JSON_URL","SCRIPT_URL","UPDATE_CHECK_INTERVAL","UPDATE_CACHE_TIMEOUT","getLatestVersion","isUpdateAvailable","latestVersion","userVersion","Update_notification","updateAvailable","checkForUpdates","reload","en_US_default","\"create\"","\"select\"","\"select_all\"","\"select_item\"","\"upload\"","\"copy\"","\"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\"","\"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\"","\"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_not_found\"","\"repository_empty\"","\"branch_not_found\"","\"root_dir_not_found\"","\"unexpected_error\"","\"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\"","\"sign_out\"","\"install_as_app\"","\"contents\"","\"assets\"","\"editorial_workflow\"","\"cms_config\"","\"menu\"","\"mobile_promo_title\"","\"mobile_promo_button\"","\"new_language_available\"","\"change_language\"","\"switching_language\"","\"locale_load_failed\"","\"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\"","\"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\"","\"singleton_selected_announcement\"","\"page_not_found\"","\"collection_not_found\"","\"asset_folder_not_found\"","\"file_not_found\"","\"x_of_x_selected\"","\"switch_view\"","\"list_view\"","\"grid_view\"","\"switch_to_list_view\"","\"switch_to_grid_view\"","\"sort\"","\"sorting_options\"","\"sort_keys\"","\"none\"","\"commit_author\"","\"commit_date\"","\"last_modified\"","\"size\"","\"_summary\"","\"_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_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\"","\"enter_new_name_for_external_folder\"","\"confirm_deleting_folder\"","\"renaming_folder\"","\"renaming_folder_failed\"","\"deleting_folder\"","\"deleting_folder_failed\"","\"edit_options\"","\"show_edit_options\"","\"copy_options\"","\"edit_asset\"","\"edit_x\"","\"wrap_long_lines\"","\"rename_asset\"","\"rename_x\"","\"enter_new_name_for_asset\"","\"enter_new_name_for_asset_error\"","\"character\"","\"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\"","\"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\"","\"processing_files\"","\"uploading_files\"","\"confirm_replacing_file\"","\"confirm_uploading_files\"","\"oversized_files\"","\"warning_oversized_files\"","\"invalid_files\"","\"warning_invalid_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\"","\"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\"","\"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\"","\"failed\"","\"checking\"","\"check_again\"","\"awaiting\"","\"short\"","\"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\"","\"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\"","\"invalid_value\"","\"entry_sidebar\"","\"sidebar_panels\"","\"title\"","\"placeholder\"","\"no_errors_found\"","\"validate\"","\"generated_on_save\"","\"unavailable\"","\"history\"","\"fetch_failed\"","\"no_history\"","\"backlinks\"","\"no_entries\"","\"saving_entry\"","\"description\"","\"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_item\"","\"list_item_value\"","\"add_x\"","\"list_item_options\"","\"add_item_above\"","\"add_item_below\"","\"select_list_type\"","\"unknown_variable_type\"","\"opacity\"","\"unselected_option\"","\"relation_field\"","\"save_together_hint\"","\"add_failed\"","\"assets_dialog\"","\"file\"","\"search_for_file\"","\"search_for_image\"","\"locations\"","\"selected_folder\"","\"selected_folders\"","\"no_subfolders\"","\"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\"","\"unsaved\"","\"character_counter\"","\"min_max\"","\"min\"","\"max\"","\"youtube_video_player\"","\"now\"","\"editor_components\"","\"src\"","\"alt\"","\"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\"","\"cloudinary\"","\"iframe_title\"","\"activate\"","\"button_label\"","\"auth_key_label\"","\"open_library\"","\"uploadcare\"","\"aws_s3\"","\"bunny_storage\"","\"cloudflare_r2\"","\"digitalocean_spaces\"","\"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\"","\"invalid_root_dir\"","\"invalid_root_dir_branch\"","\"path_outside_root_dir\"","\"oauth_implicit_flow\"","\"github_pkce_unsupported\"","\"oauth_no_app_id\"","\"open_authoring_no_workflow\"","\"no_auth_methods\"","\"missing_media_folder\"","\"public_folder_relative_path\"","\"public_folder_absolute_url\"","\"invalid_sanitize_replacement\"","\"invalid_url_option\"","\"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\"","\"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_regex\"","\"invalid_reorder_group\"","\"invalid_sortable_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\"","\"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\"","\"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\"","\"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\"","\"unsupported_ignored_option\"","\"conflicting_timezone_options\"","\"preview_path_no_date_field\"","\"preview_path_date_field_not_found\"","\"preview_path_field_not_found\"","\"missing_identifier_field\"","\"slug_i18n_ineffective\"","\"locale_not_omitted_from_file_path\"","\"i18n_not_configured\"","\"empty_public_folder\"","\"schema_unknown_option\"","\"compatibility_link\"","\"schema_tip\"","\"local_workflow\"","\"indicator\"","\"unsupported_browser\"","\"disabled\"","\"viewing_editorial_workflow\"","\"viewing_open_authoring_workflow\"","\"status\"","\"draft\"","\"drafts\"","\"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\"","\"status_change_blocked\"","\"publish_blocked\"","\"send_for_review\"","\"confirm_sending_for_review\"","\"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\"","\"branch_in_use\"","\"drag_entry\"","\"deploying_deletion\"","\"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\"","\"site_configuration_editor\"","\"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\"","\"accessibility\"","\"underline_links\"","\"advanced\"","\"beta\"","\"developer_mode\"","\"deploy_hook\"","\"saved\"","\"removed\"","\"clear_data\"","\"file_cache\"","\"confirmation\"","\"all_data\"","\"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$6","Locale_load_error_toast","showToast","Cascade_delete_note","blocker","bdi_1","Delete_assets_button","planDeletion","buttonDescription","dialogDescription","onDelete","useButton","showDialog","plan","MenuItem","blocked","Component_1","Back_button","useShortcut","onclick","rememberFocus","focusOverlay","getWrapper","keepFocusIn","ARROW_KEY_USER_SELECTOR","getArrowKeyDirection","canSwipeOn","Details_overlay","overflowItems","contentKey","onPrevious","onNext","touchStart","getHandler","onTouchStart","touches","onTouchEnd","changedTouches","$.window","h2","bdi","node_10","Download_assets_button","downloadFiles","saveFile$1","Copy_menu","menuItems","doCopyAction","toastKey","UPDATE_TOAST_DEFAULT_STATE","contentUpdatesToast","assetUpdatesToast","refreshFocusedAssets","getPath","createAssetNameTemplate","fillAssetNameTemplate","collectionFileName","getPendingFileName","nameTemplate","currentValues","defaultLocaleSlug","isValidImage","convertHEIC","isUsableImage","processFile","slugifyFilename","maxFileSize","preTransformFile","partitionProcessedFiles","oversized","getInitialProcessedAssets","processedAssets","originalFiles","originalFile","externalAssetsToast","uploadingExternalAssets","getSharedMediaLibraryOptions","reportError","reportSuccess","setAssets","forgetDeletedAssets","deletedIds","updateAsset","swap","oldAsset","newAsset","pruneSelection","ids","focusedPath","latestLoadId","fetchExternalAssetBlob","loadExternalAssets","loadId","fetchOptions","prepareExternalUploads","invalidFiles","uploadExternalAssets","originalAsset","validFiles","reportError$1","deleteExternalAssets","renameExternalAsset","renamedAsset","getExternalSubfolderAssets","getExternalFolderTree","createExternalFolder","renameExternalFolder","newDirPath","rebase","deleteExternalFolder","canCopyFileData","canCopyFileDataByName","copyFileData","Copy_assets_button","canCopyData","copyPublicURLs","copyFilePaths","copyFileIDs","hasId","Edit_options_menu","canEdit","canRename","canReplace","onEdit","onRename","onReplace","extraItems","moreItems","Edit_options_button","replaceFilePicker","replaceAsset","FilePicker","fileSizeFormatterCache","formatSize","kb","mb","gb","tb","getFileTypeLabel","formatDuration","File_info_sections","hasDimensions","dimensions","$.fallback","section","h4","section_1","h4_1","p_1","section_2","h4_2","section_3","h4_3","Info_panel_layout","preview","usedEntryLink","$$arg0","Used_entries","p_2","flushQueued","runQueuedFlush","requestFlushSync","Asset_preview","blurBackground","cover","checkerboard","dissolve","controls","mediaElement","hasError","loaded","blurImageURL","resolvedSrc","mediaSrc","isThumbnail","updatingSrc","ownedURLs","currentAsset","ownURL","releaseOwnedURL","updateSrc","previousSrc","nextSrc","checkLoaded","currentSrc","audio","img_1","Info_panel","previewURL","usedEntries","canPreview","unavailable","requestedAsset","updateProps","_asset","_details","_usedEntries","SANITIZE_OPTIONS","ALLOWED_STYLE_PROPERTIES","filterInlineStyle","ALLOWED_SANDBOX_TOKENS","ALLOWED_PERMISSIONS_POLICY_FEATURES","filterPermissionsPolicy","allow","iframe","directive","validateIframe","currentOrigin","currentSandbox","sandboxTokens","sanitizeRichTextHTML","Text_preview","rawHTML","pre_1","Not_found","backPath","anyPage","persistentCaches","getNormalizedValueCache","getNormalizedValue","normalizedValueCache","normalizedValue","hasMatch","tokenize","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","listedIds","showAsset","Copy_assets_button$1","editOptions","Edit_options_button$1","Text_preview$1","d_1","Info_panel$1","Details_overlay$2","Cloudinary_panel","onInsert","outputFilenameOnly","useTransformations","resources","Image","Remove_button","Upload_assets_preview","transformedFileMap","removable","showThumbnail","thumbnailURLs","getThumbnailURL","listedFiles","Image$1","fragment_3","Drop_zone","typeMismatchAlert","formatList","acceptedImageFormats","showUploadButton","showFilePreview","filterDroppedFiles","onDrop","dropTarget","typeMismatch","showTypeMismatchAlertDialog","showDefaultContent","openFilePicker","updateFileList","_files","filteredFileList","List_container","Listing_grid","Asset_list_container","onBlankClick","hasSubfolders","emptyAction","hasAssets","$$array","fragment_11","Asset_list_item","Unavailable_badge","isLinkedFile","showDetails","updateSelection","_selected","Asset_list_item$2","Subfolder_list_item","hasCheckboxColumn","onFocus","actionsDisabled","stopPropagation","canDelete","Subfolder_list_item$2","Upload_button","Upload_assets_button","Upload_button$1","getServiceDescription","setApiKey","saveApiKey","Cloud_service_auth","onAuth","serviceType","isStockAssets","authState","Asset_list","viewType","uploadDisabled","subfolderCount","rowIndexMap","getRowIndex","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","Subfolder_name_dialog","componentId","nameEdited","New_folder_dialog","folderLabel","New_folder_button","New_folder_button$2","Preview_asset_button","Breadcrumb","folded","ancestors","middle","canFold","getName","measure","em","leastWidths","natural","classList","least","nav","fragment_10","Primary_toolbar","fab","breadcrumbs","Primary_toolbar$3","New_folder_button$1","File_extension_change_dialog","oldExtension","newExtension","onOk","Rename_dialog","usedEntryCount","blockedMessage","confirmationOpen","keepName","finalName","extensionChanged","selectFileName","renameAsset","oldId","Rename_dialog$2","Rename_folder_dialog","currentName","Secondary_sidebar","Filter_menu","noneLabel","_label","updatedFilters","computed_const_1","Group_menu","collapsibleGroupNames","canExpandAll","canCollapseAll","Item_selector","selectedItems","totalCount","selectedCount","anySelected","allSelected","parseViewOptions","optionsKey","defaultName","defaultItem","isValidArray","parseCustomSortableFields","customSortableFields","DEFAULT_SORT_KEYS","SORT_ORDERS","DATE_FIELDS","SPECIAL_SORT_KEY_TYPES","SPECIAL_SORT_KEYS","getDefaultSortKeys","customIdField","getSortConfig","specialKeys","hasCommitAuthorKey","hasCommitDateKey","isCommitAuthorAvailable","isCommitDateAvailable","defaultKey","defaultOrder","getSortKeyType","getSortKeyLabel","_key","sortKeys","_allEntries","Sort_menu","getOrderLabel","sortKey","View_switcher","isGridView","Secondary_toolbar","hasListedAssets","hasMultipleAssets","Rejected_files_alert_dialog","oversizedFileNames","invalidFileNames","titleOwner","Page_container_main_area","primaryToolbar","secondaryToolbar","mainContent","secondarySidebar","main","Folder_info_panel$1","Main_area","rejectedFilesAlert","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","RejectedFilesAlertDialog","searchMode","ROUTE_REGEX","isSearchResultsPath","isSearchRoute","ASSETS_ROUTE_REGEX","isKnownFolderPath","navigationCount","getSelectedAssetFolderLabel","getAssetFolderHistoryState","showAssetDetails","discardAssetsNavigation","selectCloudService","assetId","resolveIndexRoute","announceAssetFolder","resolveAssetsRoute","fullPath","isConfigReadonly","isLockedByBranch","isReadonly","isDraftReadonly","getReadonlyMessage","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","areValuesModified","currentLocales","isDraftModified","originalLocales","originalSlugs","currentSlugs","parseField","keyPathList","createKeyPathList","DEFAULT_ALIASES_KEY","getAliasesKey","aliasesField","aliasesKey","getAliasKeyPaths","removeAliases","wildcardKeyPathRegexCache","getWildcardKeyPathRegex","copyProperty","unsortedMap","isTomlOutput","tomlDate","omitEmptyOptionalFields","childKeys","OPAQUE_FIELD_TYPES","isOpaqueField","finalizeContent","sortedMap","copyArgs","copyKeyValueField","pairKeyPaths","copyOpaqueField","resolvedField","concreteKeyPath","serializeContent","getFieldComments","getSingleFileComments","buildSingleFileContent","localeContents","nonDefaultContent","formatJSON","indentStyle","indentSize","formatTOML","stringifyTOML","addYAMLComments","comments","formatYAML","legacyQuote","toStringOptions","formatFrontMatter","formatEntryFile","customFormatter","isYAML","isFrontMatter","formatEntryData","resolveCacheDB","provided","getPreviousSha","isSingleFileEntry","buildEntryFileChanges","planChange","createLazyModule","loadPromise","notLoadedMessage","immutableLoaded","loadImmutable","preloadImmutable","getImmutable","assetURLUpdates","urlUpdates","waitForAssetURL","AssetProxy","#asset","ExternalAssetProxy","UnsavedAssetProxy","#file","createEntryMap","otherLocales","associatedAssets","convertEntryToMap","createGetAsset","unsavedFile","referencedEntryLookupCache","getReferencedEntryLookup","lookup","getMetaData","metaData","refEntriesCache","refCollection","refFile","buildEntry","getPreviewAssetCache","getAssociatedPreviewAssets","buildPreviewData","fieldsMetaData","fieldConfigMapCache","getFieldConfigMap","previewDataCache","previewDataCacheFlushScheduled","getPreviewData","draftCache","customFieldInstances","validationCache","pendingValidations","validationSequences","getCacheKey","registerCustomFieldInstance","unregisterCustomFieldInstance","resetCustomFieldValidation","parseValidationResult","triggerCustomFieldValidation","outcome","awaitCustomFieldValidations","validateCustomField","validity","TIMEZONE_OFFSET_REGEX","formatPart","getTimeZoneForStoredValue","offsetMatch","storedOffset","hours","minutes","getInitialTimeZone","storedTimeZone","browserTimeZone","getTimeZoneLabel","cityName","DATE_ONLY_MATCH_REGEX","TIME_SUFFIX_MATCH_REGEX","TIME_WITH_SECONDS_REGEX","formatDateTimeValue","dateStr","timeStr","includeSeconds","includeUTCSeconds","shouldUpdateValue","newDate","oldDate","getCurrentDateTime","configOutputUTC","_outputUTC","hasSeconds","inputFormat","effectiveTimeZone","timeSuffix","timeValue","getCurrentStorableValue","getInputValue","dateForParts","validateDateTimeField","hasMin","hasMax","rangeUnderflow","rangeOverflow","timeFormatter","formatTime","getFormattedDateTime","datePart","timePart","COMPONENT_NAME_PREFIX_REGEX","DEFAULT_MODES","NODE_NAME_MAP","DEFAULT_BUTTONS","BUTTON_NAME_MAP","BUILTIN_COMPONENTS","getValueFormat","getRangeErrorMessage","limitValue","limitKey","canAddMultiValue","getFieldValidationMessages","isDatetime","parsedDateTimeConf","minlength","getPathValidationMessages","getInvalidFields","extraValueMap","extraValues","validateNumberField","hasNumber","validateStringField","trimValue","tooShort","tooLong","VALIDATE_FIELD_FUNCTIONS","validatePattern","validation","validateScalarField","getCodeField","outputCodeOnly","outputKeys","resolveCodeField","validities","KEY_PATH_REGEX","validateKeyValueField","isKeyValueField","isKeyValue","formatSummary","hasSingleSubField","itemKeyPath","listFieldConfig","getUnknownTypeMessage","warnUnknownType","resolveVariableType","typeConfig","getListFieldInfo","hasMultiSubFields","hasVariableTypes","isSingleItemList","itemCount","formatObjectSummary","getListItemKey","tagListItems","assignIds","LEADING_INDEX_REGEX","INDEX_REGEX","validateListField","getListItems","resolveMediaValue","prepareListField","skip","PREPARE_FIELD_FUNCTIONS","relaxEmptyFieldValidity","enforceRequired","getWorkflowStatus","isRequiredEnforced","DEFAULT_VALIDITY","finalizeValidity","finalized","getAutoNowStages","autoNow","isAutoNowField","isAutoNowDue","stages","assignAutoNowValues","valueCache","isFieldTranslatable","i18n","isFieldLocalized","isFieldI18nDisabled","LIST_ITEM_SUBFIELD_REGEX","LIST_ITEM_INDEX_REGEX","recordValidationMessages","validateAnyField","prepareField","validateFieldFn","validateField","valid","revalidateSingleField","keyValueField","stateKeyPath","revalidateField","listKeyPath","validateList","validateArgs","getConfig","validateListItself","validationMessages","validateParentField","getParentField","fieldKeyPath","validateKeyPath","viaSubKey","validateValueEntry","ancestorKeyPath","ancestorConfig","pairValid","codeValid","listValid","validateItems","validateFields","valueStoreKey","valueEntries","extractDateTime","dateFieldName","fillEntryPathTemplate","pathTemplate","getPreviewPath","getEntryPreviewURL","_baseURL","previewPath","getEntryRepoBlobURL","thumbnailFieldRegexCache","isThumbnailPath","getEntryThumbnail","contentKeys","_thumbnailFieldNames","loadEntryThumbnail","released","onLoad","entryIdsByFolderCache","getEntryIdsByFolder","getAssetsBelowFolder","getAssociatedAssets","entryFolderPaths","existingPaths","entryIdsByFolder","isDescendantEntryFolder","getEntryRelativeAssets","SUPPORTED_EVENT_TYPES","UPDATABLE_EVENT_TYPES","callEventHooks","_login","updatedMap","normalizePath","addAlias","originalSlug","originalContent","getPreviewPathArgs","LEGACY_SLUG_EDITOR_TAG","LEGACY_LOCALIZED_SLUG_EDITOR_TAG","getConfiguredSlugTemplate","hasLegacySlugEditorTag","getEditableStages","getSlugOptions","configuredTemplate","legacyLocalized","localized","editorOnly","editorRequired","resolveBlobURLs","randomValueMaps","getRandomValues","getFillSlugOptions","getSlugTemplate","editorValue","templateOnly","slugEditor","getLocalizedSlug","_slug","localizingKeyPaths","NON_FIELD_TAGS","getLocalizingKeyPaths","hasLocalizedSlugs","getLocalizedSlugs","getCanonicalSlug","localizedSlugs","fillSlugOptions","getSlugs","getFolderName","getOwnFolderName","hasLocalizedFolders","getLocalizedFolderName","indexEntry","indexFileNames","localizedSubPath","getAllEntries","localizeDirPath","configuredIndexFileName","buildPathByStructure","buildCustomEntryPath","originalSubPath","keepsOriginalPath","createEntryPath","useCustomPath","FOLDER_PATH_REGEX","fillTemplateIfNeeded","pathString","isSharedIndexFile","getOwnedEntryFolderPath","lastSubPathSegment","getEntryAssetFolderPath","resolveInternalPath","resolvePublicPath","resolveAssetFolderPaths","getAssetFolderPaths","createPublicURL","getAssetSavingInfo","assetFolderPaths","resolvedInternalPath","resolvedPublicPath","replaceBlobURL","savingAssetsInSameFolder","savingAssets","dupFile","replacedName","assetPath","savingAssetProps","publicURL","getSubPath","getNestedCanonicalSlug","replaceBlobURLs","_globalAssetFolder","replaceBlobArgs","normalizeFieldValue","normalizeLocaleContent","createBaseSavingEntryData","slugs","normalizeArgs","getArrayItemTarget","planSingleFileChange","savingEntry","planMultiFileChange","createSavingEntryData","localizedEntryMap","createSyntheticDraft","buildEntryUpdateChanges","isEntryReadonly","getReadonlyEntryLabel","ITEM_INDEX_SUFFIX_REGEX","compactList","remainingValues","isStale","getFieldBlockers","dedupeBlockers","buildTargetChanges","getReferenceTargets","comparableURL","cutMarkup","nextBreak","blankBefore","blankAfter","removeMarkdownImages","removeAssetReferences","updatedContent","staleListItems","staleKeys","createAssetDeletionPlan","referenceTargets","entryReferences","referencesByLocale","updatedLocales","localeReferences","lastPlan","planAssetDeletion","allAssetList","getArrayFileCollection","groupArrayFileChanges","applyArrayFileChanges","slots","arrayOrder","positions","reordered","arrayItem","slot","getItemLabel","combineArrayFileChanges","arrayFileUpdates","fileChanges","createArrayFileEntries","savedEntries","isInFile","previousEntries","fileSavingEntries","savingEntries","newSavingEntries","newItemCount","previousEntry","getCommitAuthor","userData","savedEntryIds","arrayFileEntries","arrayFilePaths","excludingPaths","savedAssets","combinedChanges","savedArrayFileEntries","savedAsset","updateStores$5","notify","deleteAssets","extraChanges","cascadeChanges","updateStores$4","getDraftBaseProps","localeEntries","addSavingEntryData","draftProps","_changes","collectEntryChanges","draftBaseProps","addDataProps","getFallbackURL","getRenamedReference","oldName","collectEntryChangesFromAssets","movingAssets","replacingTargets","updatingEntries","readonlyEntries","updatingEntryMap","movedAssets","moveAssets","updateStores$3","GITKEEP_FILE_NAME","getSubfolderAssets","getSubfolderConfigFiles","createSubfolder","configFile","renameSubfolder","deleteSubfolder","deletionFailed","cachedMetadata","defaultAssetDetails","collectMediaMetadata","getMediaMetadataOnce","getAssetDetails","blobBaseURL","getAssetReferenceURL","getAssetUsedEntries","assetsDetailList","publicURLs","assetBlob","requestedAssets","detailList","repoBlobURL","Leaflet_map","mapElement","onReady","resizeObserver","shownCoordinates","showLocation","leaflet","iconUrl","showPreview","createdDate","coordinates","a_1","text_8","text_9","section_4","h4_4","text_10","text_11","section_5","h4_5","text_12","_blob","assetsInSameFolder","replacedAsset","originalAssets","replaceDuplicates","saveAssets","savingFileList","updateStores$2","Edit_asset_dialog","initState","resetState","saveAsset","footerExtra","Create_subfolder_dialog","creating","creationFailed","browseAncestor","back","renaming","renamingFailed","rename","Quick_search_bar","navigate","hadTerms","searching","Primary_sidebar","isSearchPage","getFolderLabel","isAssetCollection","shouldShowDivider","linkedCount","uiSettingsDB","getUISettingsDB","getSidebarWidth","saveSidebarWidth","Page_container","uiSettingsKey","primarySidebar","sidebarWidth","restoreSidebarWidth","onResize","clientWidth","Asset_result_item","searchAssets","assetSearchResults","Asset_results","Entry_thumbnail","Entry_result_item","resultRow","scanEntry","points","entryValueCache","searchEntries","entrySearchResults","Entry_results","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","uploading","uploadFailed","$$d_1","processing","$$d_2","mismatchedFiles","uploadableFiles","replaceFiles","dupFiles","dupFileCount","root_6","node_15","node_17","node_18","Upload_assets_dialog","Config_page","getLocalizedRelationValue","sourceLocale","targetLocale","PATH_MATCH_REGEX","VERSION_KEY","getValueMapVersion","getInheritedI18nOption","isDuplicatedField","copyDefaultLocaleValue","targetLanguage","localizedValue","createProxy","shouldAutoDuplicate","getFieldInfo","getValueMap","ownKeys","getDefaultValue","dynamicValue","getDefaultValueMap","jsonValue","populateMissingSubfields","funcArgs","subfieldKeyPath","subfield","populateDefault","hasRequiredSingleItem","itemFields","isString","parsedValue","_subField","firstOption","splitValue","GET_DEFAULT_VALUE_MAP_FUNCTIONS","getBooleanFieldDefaultValueMap","getCodeFieldDefaultValueMap","getDateTimeFieldDefaultValueMap","getFileFieldDefaultValueMap","getHiddenFieldDefaultValueMap","getKeyValueFieldDefaultValueMap","getListFieldDefaultValueMap","getRichTextFieldDefaultValueMap","getNumberFieldDefaultValueMap","getObjectFieldDefaultValueMap","getSelectFieldDefaultValueMap","populateDefaultValue","dynamicValues","getDefaultValues","alignPairs","defaultPairs","localePairs","displaced","syncDuplicateKeys","valueStore","alignedPairs","getDuplicateKeysFieldKeyPaths","pairKeyPath","syncAllDuplicateKeys","forEachTargetLocale","duplicated","_draft","copyDefaultLocaleValues","defaultLocaleContent","newContent","noI18nFieldKeys","toggleLocale","updateObject","newProps","getItemList","updateListField","valueListRemainder","expanderStateList","expanderStateListRemainder","manipulate","updateListFieldForLocales","localize","sourceList","getMultiValueList","moveMultiValueItem","addMultiValueItems","replaceIndex","removeMultiValueItem","currentKey","indexContent","childSegmentMap","siblings","hasChildKeys","getItemIndexes","indexListItems","nextDotIndex","getListItemIndexes","backupTimeout","backupDB","backupDBName","BACKUP_TOAST_DEFAULT_STATE","restoreDialogState","backupToastState","deleteBackup","getBackup","backup","getBackupSlug","isArrayItemDraft","saveBackup","createFileURLs","referencedFiles","restoreBackup","fileURLs","liveOrder","newValueMap","restoreBackupIfNeeded","doRestore","showBackupToastIfNeeded","resetBackupToastState","scheduleBackup","Backup_feedback","sameYear","sameMonth","sameDay","ROOT_ATTRIBUTE","rootElementMap","EntryDraftState","setEntryDraftContext","entryDraft","getEntryDraftContext","createEntryDraftMountContext","setEntryDraftRoot","getEntryDraftByElement","getBearerHeaders","postJSON","errorData","errorMessage","apiLabel","chatCompletions","systemPrompt","userMessage","maxTokens","reasoning","extraBody","responses","textItem","defaultHeaders","texts","endpoint$3","normalizeLanguage","createTranslationSystemPrompt","baseInstructions","lineBreakInstructions","responseInstructions","sourceLanguageName","targetLanguageName","createTranslationUserPrompt","parseAiTranslationResponse","translations","expectedCount","availability","resolveLanguageNames","sourceLangName","targetLangName","createAiTranslate","extraOptions","createAiTranslationService","availability$1","model","anthropic_default","anthropic_exports","endpoint$2","deepseek_default","deepseek_exports","SUPPORTED_LANGUAGES","LANGUAGE_ALIASES","scriptTag","regionTag","google_default","apiLabel$3","developerURL$3","apiKeyURL$3","apiKeyPattern$3","responseFormat","google_ai_default","google_exports","endpoint$1","mistral_default","mistral_exports","allTranslationServices","googleAi","openai_exports","translator","defaultTranslationService","google","turndownServicePromise","getTurndownService","TurndownService","HTML_ENTITY_MAP","decodeHTMLEntities","dec","getCopyingFieldMap","targetLocaleValue","translate","updateToast","translateFields","copingFieldMap","translatedValues","markdownSupported","turndownService","copyFields","copyFromLocale","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","isButtonDisabled","Validation_error","Boolean_editor","bind_get","bind_set","Boolean_preview","snapshotCache","getValueMapSnapshot","snapshot$2","pendingFieldUpdates","fieldUpdatePending","trackPendingFieldUpdate","awaitPendingFieldUpdates","afterPendingFieldUpdates","codeKeyPath","langKeyPath","setInputValue","setCurrentValue","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","Compute_preview","Asset_path","strong","Picker_breadcrumb","onNavigate","ancestorPath","Simple_image_grid_item","Simple_image_grid","gridId","onChange","noCheckIcon","Subfolder_strip","onOpen","selectedPaths","wasSelected","focusScope","hadFocus","getLanguageScript","getSupportedLocale","languageScript","supportedLocales","fetchJSON","fetchPagedResults","parsePage","hasMore","SUPPORTED_LOCALES","ENDPOINT","SEARCH_PARAMS","DESCRIPTION_REGEX","getLocale","medium","large2x","photographer","pexels_default","nextPage","photos","LIMIT","TOTAL_PAGES","FETCH_PAGES","landscape","pw","ph","picsum_default","pages","webformatURL","imageWidth","imageHeight","largeImageURL","pageURL","pixabay_default","CREDIT_LINK_PARAMS","thumb","regular","allStockAssetProviders","totalPages","getStockAssetMediaLibraryOptions","allProviderNames","providers","sortServicesByName","nameA","nameB","isFolderOffered","selectFolder","getFirstDefaultLibraryName","isDefaultLibraryEnabled","assetLibraryFolderMap","getStockAssetProviderEntries","hotlinking","getPickedFolderPublicPaths","browsingSubfolders","selectedSubfolderPaths","getUnsavedAssetSubfolderPath","targetFolderPath","getInsertedResources","resource","getSelectionWithResource","isSame","External_assets_panel","breadcrumb","searchQuery","panelAssets","_kind","onSelectionChange","selectedResources","browse","upload","createFolder","allMediaLibraryOptions","hasConfig","newFolderDialogOpen","folderCreationFailed","uploadingToast","listFetchOptions","latestRequestId","getAssets","requestId","emptyFolders","getResource","uploadFiles","prepared","canCreateFolder","showNewFolderDialog","createNewFolder","selectedURLs","requestedSelection","loadAuthInfo","Assets_panel","emptyMessage","onOpenSubfolder","onSelectSubfolder","listedItems","filteredItems","selectedAssetKeys","assetKind","Internal_assets_panel","dropZone","DropZone","DEFAULT_STATE","duplicates","checkDuplicates","EMPTY_PATH_SEGMENT_REGEX","getAssetLibraryFolderMap","fieldAssetFolder","fileAssetFolder","collectionAssetFolder","entryAssetFolder","globalFolder","getDefaultAssetFolder","folderMap","getTargetFolderPath","getUnsavedFileName","getUnsavedFileDisplayPath","getFileDisplayPath","unsavedFileName","decodedValue","isInTargetFolder","isAssetInSelectedFolder","resolveUnsavedAssetPaths","unsavedAssets","namesByDir","replacedPaths","resolvedUnsavedAssets","namesInDir","listAssets","isInSelectedFolder","hasSameAsset","getExistingBlobURL","foundURL","convertFileItemToAsset","getUnsavedAssets","getSavedAssetsForEntry","expectedPrefix","processResource","existingBlobURL","processedFile","libraryConfig","existingAsset","credit","newFolderButton","$.derived_safe_equal","$$arg1","Select_assets_dialog","elementIdPrefix","locationOption","headerItems","isDefaultLibrary","rawSearchTerms","isCloudLibrary","isStockLibrary","selectedFolder","externalAssetsPanel","canEnterURL","pendingFiles","enteredURL","droppedAssets","showURLInput","cloudServiceEntries","browsedPath","browsedDirAssets","selectedFolderLabel","enabledStockAssetProviderEntries","isEnabledMediaService","enabledExternalServiceEntries","Selector","pickedFolderPublicPaths","otherPaths","resetValues","firstDefaultLibraryName","headerExtra","Selector_1","consequent_12","$$array_1","cloudinaryActivated","consequent_13","consequent_14","$$array_2","consequent_15","node_21","consequent_16","node_22","consequent_17","fragment_33","consequent_18","serviceProps","$$array_3","ExternalAssetsPanel","consequent_19","consequent_20","consequent_21","Conflict_resolution_dialog","footer","getMediaFieldAssetOptions","processResources","getRejectedFileNames","oversizedFileName","invalidFileName","toFieldValue","inEditorComponent","getCustomFieldAssetOptions","addFileToDraft","namedFile","getPickedAssetKind","getPickedBlob","resolvePickedResources","Asset_picker","assetOptions","mediaFieldConfig","pick","pickOptions","rejected","fieldStateContext","createContext","reactDom","reactDomLoaded","loadReactDom","preloadReactDom","getReactDom","updateNonPrimitiveValue","WRAPPED_COMPONENT_TYPES","isReactComponent","resolveControl","customFieldType","buildControlProps","previewData","fieldId","fieldClassName","handleRef","cachedFieldClassName","getInputClassName","TextInput","Custom_editor","fieldContext","reactRoot","componentInstance","assetPicker","registration","resolvedControl","parentComponentNames","handleAddFile","handlePickFile","renderComponent","createElement","AssetPicker","buildPreviewProps","metadataKey","Custom_preview","Date_time_preview","displayValue","Date_time_editor","isInputFocused","_inputValue","handleFocus","handleBlur","Editable_text","initialText","editLabel","applyDisabled","ariaErrormessage","getSelectionEnd","onApply","editButton","valueElement","isComposing","moveListItem","getMoveTarget","getListItemAt","focusReorderControl","AUTO_SCROLL_THRESHOLD","AUTO_SCROLL_MAX_SPEED","autoScroll","getScrollContainer","overflowY","getAutoScrollSpeed","distanceFromTop","distanceFromBottom","stepAutoScroll","nextScrollTop","scrollTop","speed","scrollHeight","clientHeight","onAutoScrollDragOver","startAutoScroll","stopAutoScroll","Reorder_controls","onGrab","onRelease","onMove","getMediaFieldPreview","urlArgs","mediaKind","File_editor_item","showExtensionChangeDialog","grabbed","isImageField","isFolder","sortable","getURLArgs","fileDisplayPath","newFile","applyNewName","Reorder_controls$1","replaceMode","showSelectAssetsDialog","onPasteButtonClick","onFilePaste","clipboardItems","imageType","imageItem","createDragSorter","grabbedIndex","drag","displayOrder","getItemCount","getListElement","previewOrder","File_editor","uploadButton","onResourcesSelect","targetFolder","allowDrop","sorter","itemArgs","removeItem","itemList","$$args","showRemoveButton","resetSelection","showPhotoCreditDialog","photoCredit","acceptedTypes","enabledCloudServiceEntries","isDefaultLibraryAvailable","totalProviders","previousValue","hasValidResource","credits","fragment_12","File_preview_item","File_preview","Add_item_button","addItem","labelPlural","multiValueField","labelSingular","hasMaxItems","itemLabel","getPairs","validatePairs","savePairs","createKeyedRows","nextId","getNextId","initialValues","currentIds","keepIds","Key_value_editor","_keyLabel","_valueLabel","keyLabel","valueLabel","keysReadonly","rowElements","tableBody","validations","isOnlyBlankRow","ensureBlankRow","updatePairs","updatedPairs","savedPairs","addPair","removePair","updateStore","keyedPairs","root_5","thead","th","th_1","th_2","th_3","tbody","tr_1","td_1","td_2","td_3","d_2","Key_value_preview","Expand_icon","Object_body","summaryId","Field_editor","Object_header","expandable","centerContent","endContent","expanderRegexCache","pendingExpanderStates","flushExpanderStates","stateMap","getInitialExpanderState","currentState","isExpanded","syncExpanderStates","currentStates","pendingStates","getExpanderKeys","endingWithNumber","parentConfig","expandInvalidFields","validityMap","highlightEditorField","getLastRenderedParentField","pane","findEditorField","previousLastRenderedField","maxAttempts","lastRenderedField","revealEditorField","expanderKeys","targetField","isOutdated","widgetWrapper","highlightPreviewTemplateField","isKeyDown","getInitialListExpanderStates","minimizeCollapsed","createListItem","dupIndex","getObjectThumbnail","thumbnailFieldName","nestedFieldNames","fieldTypedKeyPath","List_editor_complex","addPositionItems","variableTypes","insertIndex","allowAdd","allowRemove","allowDuplicate","allowReorder","addToTop","singleSubFields","resolveType","isLocked","parentExpandedKeyPath","singleItem","canRemoveItem","parentExpanded","itemExpanderStates","allSubFields","typeFields","hasEditableSubFields","subI18n","isAddDisabled","updateExpanderStates","initializeExpanderState","updateComplexList","getItem","_formatSummary","getThumbnail","warnUnknownTypes","node_19","List_editor_simple","hasMultipleItems","getStoredValue","syncFromValue","List_editor","hasSubFields","Subsection","sectionId","headerId","getFieldLocaleAccess","inOtherLocale","canTranslate","isDuplicated","areKeysDuplicated","Field_preview","showLabel","isShown","previewProps","Preview","previews","Preview_1","List_preview_complex","itemTypes","List_preview_simple","List_preview","SEARCH_API_URL","searchLocations","parseGeoJSON","geometry","geometryType","isValidGeoJSON","roundCoordinates","coords","getGeometryBounds","lats","lngs","Map_editor","center","drawMode","draw","searchResults","showAlertDialog","mapInstance","constructors","TerraDrawPointMode","TerraDrawLineStringMode","TerraDrawPolygonMode","_draw","TerraDraw","TerraDrawLeafletAdapter","onDrawChange","feature","fitMapToGeometry","bounds","searchLocation","setLocation","onSearchResultSelect","lat","lon","useCurrentLocation","clearValue","Map_preview","isFloatType","isStringOutput","getNumberInputValue","getNumberFieldValue","Number_editor","Number_preview","numberFormatter","addObjectFields","removeObjectFields","Object_editor","hideHeader","hasValues","typeKeyPath","unknownType","addFields","removeFields","Object_preview","subFieldKeyPath","discardConflictingValue","reconcileScalarValue","firstItemIndex","firstItem","reconcileListValue","reconcileObjectValue","reconcileValue","copyFromDefaultLocale","getVariableTypeFields","normalizeField","inheritedI18n","fillDefaults","itemIndex","itemField","normalizeContent","normalizeContentMap","contentMap","getInitialValue","useEncoding","LIST_ITEM_KEY_PATH_REGEX","fillUuidValues","getUuidField","listItemKeyPath","getSlugEditorProp","slugEditorEnabled","getSlugTargetLocales","getInitialSlugs","initialSlug","getOriginalPath","initialPath","buildDraft","enabledLocales","expanderStates","createDraft","getOtherEntries","ownPaths","getTakenSlugs","otherEntries","ownSlugs","validateSlug","trimmedSlug","takenSlugs","getSlugValidationMessage","isSlugEditable","validateSlugs","isWholeSlug","editorValueIsSlug","hasEntrySlug","canUpdateSlug","needsSlugInput","getSlugPreviews","updateSlugs","getOwnFolderPaths","ownFolderPath","getTakenFolderNames","ownFolderPaths","otherSubPath","otherDirPath","renameEntryFolders","folderNames","Slug_editor","labelId","draftSlug","templateSlug","shownSlug","editError","updateSlug","applySlug","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","initSettings$1","Locale_switcher","thisPane","thatPane","listedLocales","hasAnyError","useDropDown","SelectComponent","SelectButtonGroup","OptionComponent","SelectButton","SelectComponent_1","OptionComponent_1","OptionComponent_2","UUID_TAG_LENGTHS","UUID_TAG_PATTERNS","TAG_PLACEHOLDER","generatedUuidMap","getListIndex","isUuidTag","parseUuidTags","literals","valueTemplate","firstOtherIndex","lastOtherIndex","hasUuidTag","getUuids","uuidTags","extractedUuids","generatedUuids","extractedIndex","extractable","getComputedValue","listFormatter","uuids","uuidIndex","getSubFields","computeFieldCacheMap","containsComputeField","collectFromField","getSubFields$1","listField","getIndex","collectComputeFields","collectComponentComputeFields","visitedPrefixes","isLocaleTarget","updateLocaleComputedValues","computeFields","updateComputedValues","trackComputedValues","initEntryDraftEditor","getEntryDraft","countQuotaEntries","getDraftValueSources","getPendingEntryValueSources","isReferencedIn","fieldArgs","getReferencedPendingEntries","referenced","grow","newlyReferenced","assignManualSortOrder","nextOrder","getPendingEntriesByCollection","getCreatableCollection","hasCreationRoom","getPendingRefEntries","refEntryIds","getRefEntriesWithPending","getPendingEntrySlugs","pendingSlugs","parentDraft","renamedSlug","renamedLocalizedSlugs","createPendingEntry","getNestedPendingEntries","parentIds","selectPendingEntry","Quick_add_dialog","adding","added","showValidationToast","errorCount","showErrorToast","hasMultipleLocales","startDraft","discardDraft","Entry_editor","Select_multiple","dropdownThreshold","updateList","addValue","removeValue","Select_single","hasEmptyOption","allOptions","Select_editor","SelectMultiple","SelectSingle","Select_1","Relation_editor","showQuickAddDialog","selectFieldConfig","creatableCollection","canCreate","creatableName","SLUG_VALUE_FIELDS","Relation_preview","refValues","formatComponentSummary","strippedTemplate","flatValues","getComponentDisplayValues","getComponentDisplayText","formatted","displayField","hasThumbnail","getComponentThumbnail","validateComponentValues","loc","deleteKeysByPrefix","flattenWithPrefix","getValuesByPrefix","reconcileComponentValues","normalizedValues","Editor_component","fieldEditors","typedPrefix","observe","fieldEditor","inline","valuesSnapshot","isNewComponent","typedKeyPathPrefix","getElement","previousValues","restoreValues","handleRemove","handleOk","handleCancel","brokenThumbnail","thumbnailSource","displayText","localeContainer","keyPathContainer","reconciledValues","fragment_7","node_13","getNoAsset","fieldListCache","getComponentFieldList","CONTAINER_QUERY_SELECTOR","COMPONENT_QUERY_SELECTOR","MEDIA_URL_ATTRIBUTES","MEDIA_QUERY_SELECTOR","parseSrcset","urlStart","srcset","descriptorEnd","resolveMediaURLs","updated","resolveURL","localName","hashString","VOID_ELEMENTS","FENCE_OPEN_REGEX","HTML_OPEN_TAG_REGEX","htmlTagRegexCache","splitHTMLBlocks","splitMarkdownBlocks","blocks","htmlBlock","stripped","openRe","closeRe","fenceMatch","htmlOpenMatch","encodeImageSrc","eSrc","globalPatternCache","MAX_SUBSTITUTION_PASSES","collectStringValues","getGlobalPattern","isMatchWithinPreviewValues","regions","findOutermostMatches","componentDefs","def","createPreviewContext","addComponentPreview","baseHash","seenHashes","previousPreviewMap","toPreview","fieldProps","getAsset","previewMap","substituteMatches","chunks","buildHTMLWithPreviews","defs","replaceInstances","previewTemplate","buildMarkdownWithPreviews","pass","TAG_NAME_REGEX","getTagName","callWithEmptyProps","createCustomNodeClass","componentDef","htmlSupported","htmlTagNames","toBlock","getPropsFromElement","CustomNode","DecoratorNode","serializedNode","EditorComponent","getNearestEditorFromDOMNode","activeEl","selectionRange","conversionMap","createTransformer","nonGlobalPattern","getProps","fromBlock","matchArray","isCustomNode","exportNode","fullString","startLineIndex","matchString","endLineIndex","rootNode","textNode","featureCacheMap","createLexicalNodeFeatures","DATA_URL_REGEX","GENERIC_PASTED_FILE_NAME","hasImageExtension","getTimestampFileName","findImageInHTML","getPastedImages","pastedItems","clipboardData","images","fileIndex","htmlIndex","getDroppedImages","droppedFiles","dataTransfer","Rich_text_editor","defaultConfig","cleanupTimeout","_modes","_buttons","_editorComponents","_allowNestedComponents","linkedImagesEnabled","minimal","allowNestedComponents","imageComponent","insertImages","outer","srcFieldConfig","externalSrc","_src","onPaste","scheduleExtraValueCleanup","Text_editor$1","src_default","marked","read_methods","set_like_methods","SvelteSet","#size","#init","#update_version","set_proto","#sources","SvelteMap","#read_all","callbackfn","this_arg","callbackFn","prev_res","v_reactions","Rich_text_preview","yt$6","markedBidi","reactRoots","previewNodes","newPreviewAssets","observerReady","highlighterVersion","assetURLVersion","requestedLanguages","doSanitize","isHTML","newMap","keyedBlocks","occurrences","occurrence","preloadHighlighter","isOwnElement","mountReactPreview","reportLoadError","unmountRemovedRoots","notifyRemovedPreviews","refreshOnAssetURLChange","replaceMediaURLs","mutationCallback","removedElements","removedNodes","addedNodes","Select_preview","Character_counter","setExtraHint","extraHint","getStringInputValue","getStringFieldValue","String_editor","CharacterCounter","isYouTubeVideoURL","getYouTubeEmbedURL","Youtube_embed","embeddable","embedURL","onViolation","blockedURI","violatedDirective","SAFE_PROTOCOL_REGEX","getPreviewType","String_preview","previewType","Uuid_editor","Uuid_preview","editors","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","PRESERVED_FIELD_TYPES","resetContent","ownI18n","objectDefault","subFieldConfig","resetFieldInStore","canResetField","resetField","getTargetLocales","resetAllFields","canResetEntry","copyValues","resetEntry","resolveOriginalKeyPath","itemPrefix","originalPrefix","getFieldValues","isFieldChanged","originalKeyPath","revertFields","isDefaultLocale","targetKeyPath","remapPrefix","revertLocale","revertChanges","revertsEverything","beforeInput","_sanitize","beforeInputLabel","afterInput","afterInputLabel","writeValue","hint","readonlyOption","allowPrefix","allowExtraLabels","hasExtraLabels","canCopy","canRevert","isRevertDisabled","fieldLabel","pendingDeletion","draftReadonly","locked","canReset","resetAvailability","updateResetAvailability","editorProps","Editor","Editor_1","ExtraHint","root_8","node_20","ExtraHint_1","Parent_folder_tree_item","childItems","countSegments","getIndexEntryRank","collectFolders","ranks","getNodeLabel","buildTree","childPaths","buildNodes","pruneLeaves","excludePath","getNestedTree","getMaxParentFolderDepth","baseDepth","getParentFolderTree","addFolderToTree","addSegment","nodePath","existingNode","findNestedTreeNode","Path_editor","canMove","ownFolderName","selectedPath","hasRoomForFolder","newFolderName","newFolderNameEdited","newFolderPaths","localizedSelectedPath","selectedNode","selectedLabel","popupOpen","takenFolderNames","newFolderError","showNewFolderError","hasFolderChoice","selectPath","showPathEditor","Entry_preview_iframe","generateHTML","mountPlaceholder","renderReactComponent","contentDocument","contentWindow","componentProps","mountReactComponent","createRoot","reportMountError","initializeIframe","mountComponent","iframe_1","createFieldPreviewMounter","FieldPreview","createWidgetFor","createWidgetsMap","widgetFor","createWidgetsFor","ImmutableMap","fromJS","getCollectionByName","convertArgs","convertEntry","preparePreviewTemplateProps","Entry_preview","styleURLs","reactComponent","reactProps","getProportionalScrollTop","scrollRange","targetScrollHeight","targetClientHeight","getFieldAlignedScrollTop","ratio","targetOffsetTop","scrollSource","Pane_body","thisPaneContentArea","thatPaneContentArea","syncScrolling","labelOptions","MainContent","EntryPreview","EntryEditor","contentArea","syncScrollPosition","thisElement","ownerDocument","thatElement","thatScrollTop","markScrollSource","scrollEventTarget","eventOptions","scrollEventOptions","initCount","findPreviewIframe","initializeScrollSync","MainContent_1","Reset_dialog","Preview_button","refineState","liveness","getEntryPreviewLink","deployMap","compose","deploy","pollTimedOut","Preview_link_button","as","isDeployPreview","pingable","awaitingPreview","canPing","LOCALE_CONTENT_KEYS","getLocaleContentLabel","getPaneStateKey","getPaneSizes","firstPane","secondPane","getRestoredPanes","editorLocale","savedPanes","showSecondPane","getDefaultPanes","currentLocale","singlePane","getPanesEditingLocale","editPane","savePaneState","panes","attempts","unwatch","lastKey","isSettled","holdBack","keepWaiting","prior","reopenRecentConclusions","getTargetKey","supersede","schedule","restart","retain","retainDeployPolling","recheckDeployments","Pane_header","isLocaleEnabled","isOnlyLocale","resetAction","showResetDialog","menuButton","previewLink","hasLinkItems","h3","paneLocale","MenuButton","compareWithStore","canOverwrite","detectEntryConflict","describeConflict","reloadDraft","isDraftUntouched","refreshOpenedDraft","conflict","Remote_change_infobar","dismissedFor","showReloadDialog","Panel_container","isNullish","getContentTypedKeyPath","contentSegments","resolveRelationKeyPath","getRelationKeyPaths","valuePattern","getRelationValues","getEntryRelationValues","getReferencingRelationFields","collected","sourceCollectionName","sourceCollection","sourceFileName","getBacklinks","seenEntryIds","backlinks","sourceCollectionFile","targetValues","sourceEntry","backlink","collectionNames","Backlinks_panel","groupedEntries","Panel_container$1","historyCache","fetchEntryHistory","clearEntryHistoryCache","entryId","History_panel","commitURL","Panel_section","Slug_update_form","getEditError","Slug_panel","canUpdate","editorLocales","readonlySlugs","getSectionLabel","sidebarSheetPanel","getSidebarPanels","showSidebarPanel","Validation_panel","onSelectField","hasResults","validating","listErrors","slugValidity","pathValidity","fragment_6","fragment_9","fragment_13","Sidebar_panel","Sidebar_sheet","closingKey","fieldToHighlight","Sidebar","panels","savedKey","draftPanelKey","lastDraftId","activeKey","sidebarPanel","View_menu_items","canShowSecondPane","previewShown","hasSingleLocale","getCandidateEntries","relation","excludeIds","collectCascadeTargets","getLocaleValues","getContentUpdater","getDeletedValues","removeReferences","staleKeyPaths","listKeyPaths","getBlockers","fieldKeyPaths","collectDeleteTargets","getDeletedVersions","EMPTY_CASCADE_DELETE_PLAN","planCascadeDelete","versions","planCascadeDeleteOrThrow","buildCascadeDeleteChanges","Delete_entry_dialog","cascadePlan","withUpdatedOrder","newOrder","buildReorderChanges","orderedEntries","buildArrayFileReorderChanges","reorderEntries","computeRenumberedEntries","updatedEntries","buildRenumberChanges","idSet","assetPathSet","deleteEntries","renumberChanges","renumberSavingEntries","renumberedIds","cascadeSavingEntries","updateStores$1","createRenamedEntry","getReplacementMap","getValuesArgs","oldValues","renamedEntry","oldValue","replaceReferences","outdatedKeyPaths","collectRenameTargets","relations","buildCascadeChanges","noChanges","readonlyTargets","PUBLISH_REFUSED","REGULAR_FILE_MODES","getPathChanges","classifyPath","getUpdatedEntry","getDepth","getDescendantPaths","getDescendantFolders","getReferencingPaths","deletion","updatedEntry","findUnexpectedChanges","updatedPaths","descendantPaths","descendantFolders","referencingPaths","isExpected","sameCollection","pathChange","createRefusal","refusal","verifyMergeState","unexpected","getWorkflowErrorMessage","getWorkflowService","getEventHookArgs","resolveWorkflowBranch","currentBranch","getPreviousPaths","upsertUnpublishedEntry","removeUnpublishedEntry","storeUnpublishedEntry","clearUnpublishedEntry","settleAssets","settlePublishedEntry","cascadedEntries","saveWorkflowChanges","updateWorkflowStatus","newPullRequest","pendingPublishes","mergeWorkflowEntry","hookArgs","preType","postType","publishWorkflowEntry","discardWorkflowEntry","deleteWorkflowEntry","discardWorkflowEntries","deleteWorkflowEntries","targetMap","deleteOrDiscardEntries","useWorkflow","getDiscardDialogStrings","publishedVersionExists","getPublishDialogStrings","Entry_removal","deleting","showDeleteDialog","showDiscardDialog","showDeleteErrorToast","deleteErrorMessage","progressMessage","discardDialogStrings","confirmDelete","confirmDiscard","runDeletion","toastState","progressKey","deleteEntry","discardChanges","Save_conflict_dialog","conflictDescription","closeWorkflowEntryEditor","handleEntryAlreadyPublished","validateWorkflowEntry","canMoveToStatus","canPublish","Entry_status_menu","updating","statusName","qualifiedStatusName","changeStatus","newStatus","_status","Publish_entry_button","modified","showPublishDialog","dialogStrings","publishing","publish","hasTemplateTag","usesCurrentTime","resolveComparisonValue","today","isLocalDateTime","dateFieldConfig","toDate","isNumberLike","compareValues","targetDate","targetStr","prepareConditions","comparisons","matchesConditions","rawValue","refValue","parseFilterConfig","filterEntries","configuredFilters","optionKeys","preparedFilters","viewFilters","entryListSettings","viewBeforeReorder","_view","parseGroupConfig","getReorderGroupingConditions","groupEntriesByComparison","viewGroups","sortCondition","sortedGroups","_entries","MARKDOWN_SORT_KEY_LENGTH","MARKDOWN_FIELD_KEYS","getSortKeyGetter","isMarkdownField","moveIndexFileToTop","reordering","reorderedEntries","reorderDirty","VIEW_TIME_INTERVAL","viewTime","viewUsesTime","listedEntries","_nestedFilterPath","filterNested","listedUnpublishedEntries","sort","listedEntryIndexMap","QUOTA_WARNING_THRESHOLD","collectionState","_selectedCollection","canReorder","quota","entryCount","sortedEntries","filteredEntries","entryGroups","restoreView","defaultSort","defaultFilter","groupOptions","defaultGroup","setReorderMode","reorderGroup","overrides","ASSET_FIELD_TYPES","copyEntryRelativeAssets","ownsFolder","copies","copyAsset","copyFieldAssets","blobURLs","findHiddenField","duplicateDraft","orderFieldKey","duplicatedHiddenFieldMap","clearedUuidFieldMap","hiddenFields","getInitialUuidValue","defaultValueMap","duplicatePath","newDraft","moveSubPath","restPath","oldDir","newDir","moveEntry","newSubPath","dirMove","localeDirMove","localeDirMoves","newLocaleSubPath","updateCanonicalSlug","buildMoveChanges","movedEntry","originalLocalizedEntry","buildNestedMoveChanges","oldDirPath","descendants","movedEntries","getMovedFolders","movedFolders","oldFolderPath","newFolderPath","buildEntryAssetMoveChanges","takenPaths","moveChanges","detectWorkflowConflict","buildChanges","cascadeEntries","assetMoveChanges","saveEntry","savingPendingEntries","pendingCollectionName","canDuplicateEntry","creationDisabled","getRemovalMenuItems","canDeleteEntry","isCollectionFile","getSaveFailure","Toolbar_1","overflowButtons","showReviewDialog","resolveReviewPrompt","showConflictDialog","saveConflict","showErrorDialog","saving","duplicating","entryRemoval","collectionLabelSingular","entrySummary","busy","controlsDisabled","discardsDraft","canDuplicate","removalMenuItems","discardItemStrings","_goBack","isReadyForReview","askForReview","save","savedEntry","savedDraft","statusChangeFailed","failure","fragment_8","panelDisabled","node_23","node_24","node_26","node_27","node_28","node_29","node_30","EntryRemoval","node_31","node_32","node_33","Content_details_overlay","secondPaneContentArea","firstPaneContentArea","restoring","switching","highlightRequestCount","firstPaneWidth","paneStateKey","$$d_3","collectionReadonly","$$d_4","firstPaneSize","secondPaneSize","minPaneSize","restorePanes","switchPanes","savePanes","swapPanes","markInteracted","ensureEditPaneVisible","revealRequestedField","revealRequestedFieldIfNeeded","onmessage","targetCollection","fragment_16","firstWidth","secondWidth","alternate_3","alternate_4","Status_badge","Entry_list_item_cells","showCheckbox","Entry_list_item","rowIndex","Entry_reorder_list_item","canMoveUp","canMoveDown","onMoveUp","onMoveDown","Entry_reorder_list","reorderGroups","dragOrigin","draggedEntry","publishOrder","getLocalEntries","finishDrag","localEntries","accepted","Create_entry_button","optionMenu","openEditor","indexFileLabel","hasOptions","ButtonComponent","SplitButton","ButtonComponent_1","Entry_list","fragment_17","File_list","statuses","Nested_tree_item","isCurrentCollection","hasCurrentDescendant","Collection_tree_item","folderItems","treeNodes","internalCollection","Singleton_tree_item","isLastCommitPublished","canTriggerDeployment","deployHookURL","deployHookAuthHeader","Publish_button","toastStatus","hide","hasNestedCollections","errorToast","Delete_entries_dialog","draftEntries","publishedEntries","publishedEntryAssets","deleteSelectedEntries","nearingQuota","deleteDisabled","hasEntries","thumbnailFieldNames","listedEntryCount","hasListedEntries","hasMultipleEntries","CONTENTS_ROUTE_REGEX","showNotFound","notFoundKey","clearEditor","messageKey","resolveCollectionIndexRoute","selectRouteCollection","resolveListingRoute","routeType","resolveFileRoute","resolveEntryRoute","resolveContentsRoute","_fileMap","Contents_page","awaitingDrafts","FileList","EntryList","Translator_selector","Translator_api_key_dialog","saveKey","Content_updates_toast","Entry_parse_errors_toast","showParseErrorToast","canShowMobileSignInDialog","showMobileSignInDialog","getState","setState","onboardingState","createOneOffNotice","Mobile_promo_infobar","notice","New_language_infobar","newLocale","showInfobar","showInfobarIfNeeded","longLang","shortLang","availableLocales","hideInfobar","Not_found_page","Page_switcher","assetsLink","_pages","sMode","Bottom_navigation$1","App_install_menu_item","canInstall","installPrompt","beforeInstallPromptHandler","appInstalledHandler","Shortcuts_dialog","kbd","Shortcuts_menu_item","Pref_switch","Accessibility_panel","CACHE_STORE_NAMES","LOCAL_STORAGE_KEY_PREFIX","DATABASE_NAME_REGEX","clearTestBackendFiles","clearFileCache","getDatabaseNames","deleteDatabase","clearLocalStorage","eraseAllData","Advanced_panel","showClearCacheDialog","showEraseDataDialog","clearCache","eraseData","h3_1","h3_2","h3_3","p_3","p_4","Appearance_panel","Contents_panel","Api_key_input","I18n_panel","Language_panel","localizedLabel","nativeLabel","selectedLocale","switchingLocale","switchingLocaleLabel","Media_panel","AppearancePanel","LanguagePanel","ContentsPanel","I18nPanel","MediaPanel","AccessibilityPanel","AdvancedPanel","toastMessage","Panel_1","Settings_dialog","selectedPanel","Account_menu","showPrefsDialog","isLocalRepo","Account_button","hasAvatar","Create_button","entryCollections","collectionItems","assetsDisabled","allDisabled","Release_notes_menu_item","labelKey","Help_menu","Help_button","Notifications_button","Site_logo","showInHeader","Global_toolbar","Menu_page","toSJISFunction","CODEWORDS_COUNT","kanji","fromString","BitBuffer","bufIndex","bit","BitMatrix","reserved","getSymbolSize","require_utils$1","posCount","intervals","posLength","FINDER_PATTERN_SIZE","PenaltyScores","mask","sameCountCol","sameCountRow","lastCol","bitsCol","bitsRow","darkCount","modulesCount","getMaskAt","maskPattern","numPatterns","bestPattern","lowerPenalty","setupFormatFunc","penalty","ECLevel","require_error_correction_level","EC_BLOCKS_TABLE","EC_CODEWORDS_TABLE","errorCorrectionLevel","EXP_TABLE","LOG_TABLE","GF","require_galois_field","coeff","divident","divisor","poly","degree","Polynomial","require_polynomial","ReedSolomonEncoder","paddedData","remainder","buff","numeric","alphanumeric","TEST_KANJI","TEST_NUMERIC","TEST_ALPHANUMERIC","VersionCheck","require_version_check","Regex","require_regex","dataStr","Utils","ECCode","require_error_correction_code","Mode","require_mode","G18","G18_BCH","getBestVersionForDataLength","currentVersion","getReservedBitsCount","getTotalBitsFromDataArray","totalBits","reservedBits","getBestVersionForMixedData","dataTotalCodewordsBits","usableBits","seg","ecl","G15","G15_MASK","G15_BCH","NumericData","bitBuffer","remainingNum","ALPHA_NUM_CHARS","AlphanumericData","ByteData","KanjiData","dijkstra","predecessors","costs","closest","cost_of_s_to_u","adjacent_nodes","cost_of_e","cost_of_s_to_u_plus_cost_of_e","cost_of_s_to_v","first_visit","graph","require_numeric_data","require_alphanumeric_data","require_byte_data","require_kanji_data","require_dijkstra","getStringByteLength","getSegments","getSegmentsFromString","numSegs","alphaNumSegs","byteSegs","kanjiSegs","s1","s2","getSegmentBitsLength","mergeSegments","segs","prevSeg","curr","buildGraph","prevNodeIds","nodeGroup","currentNodeIds","prevNodeId","buildSingleSegment","bestMode","modesHint","optimizedSegs","require_bit_buffer","require_bit_matrix","AlignmentPattern","require_alignment_pattern","FinderPattern","require_finder_pattern","MaskPattern","require_mask_pattern","require_reed_solomon_encoder","Version","require_version","FormatInfo","require_format_info","Segments","require_segments","setupFinderPattern","matrix","setupTimingPattern","setupAlignmentPattern","setupVersionInfo","mod","setupFormatInfo","setupData","inc","bitIndex","byteIndex","dark","createData","remainingByte","createCodewords","totalCodewords","dataTotalCodewords","ecTotalBlocks","blocksInGroup1","totalCodewordsInGroup1","dataCodewordsInGroup1","dataCodewordsInGroup2","ecCount","dcData","ecData","maxDataSize","dataSize","createSymbol","estimatedVersion","rawSegments","bestVersion","dataBits","modules","hex2rgba","hexCode","hexValue","margin","qrSize","symbolSize","scaledMargin","palette","posDst","pxColor","iSrc","jSrc","require_utils","clearCanvas","getCanvasElement","canvasEl","qrData","rendererOpts","getColorAttrib","attrib","svgCmd","cmd","qrToPath","moveBy","newRow","lineLength","qrcodesize","bg","svgTag","canPromise","require_can_promise","QRCode","require_qrcode","CanvasRenderer","require_canvas","SvgRenderer","require_svg_tag","renderCanvas","argsNum","isLastArgCb","renderFunc","Mobile_sign_in_dialog","import_browser","Search_page","Settings_page","panelKey","Deploy_status_badge","LABELS","Workflow_entry_card","deploying","onDragStart","onDragEnd","onPublish","deploySHA","deployState","gone","deleteIcon","span_4","span_5","Workflow_page","COLUMN_LABELS","STATUS_UPDATE_MESSAGES","DELETION_MESSAGES","CANCELLATION_MESSAGES","PUBLISHING_MESSAGES","targetEntry","busyBranches","isBusy","targetIsDeletion","publishDialogStrings","columns","pendingDeletions","announced","runAction","reportValidationErrors","confirmPublish","review","ready","header_1","header_2","Main_router","NOT_FOUND_PAGE_NAME","ContentsPage","AssetsPage","SearchPage","WorkflowPage","ConfigPage","MenuPage","SettingsPage","SelectedPage","NotFoundPage","selectPage","route","SelectedPage_1","Fork_permission_dialog","Open_authoring_indicator","forkURL","isMergeableObject","isNonNullObject","isSpecial","stringValue","isReactElement","emptyTarget","cloneUnlessOtherwiseSpecified","deepmerge","defaultArrayMerge","getMergeFunction","customMerge","getEnumerableOwnPropertySymbols","propertyIsOnObject","propertyIsUnsafe","mergeObject","destination","sourceIsArray","deepmerge_1","hasTags","replaceTags","globalMediaFolder","globalPublicFolder","getCollectionBaseFolder","normalizeAssetFolder","globalFolders","baseFolder","addFolderIfNeeded","iterateFiles","fileMediaFolder","filePublicFolder","inherits","handleFieldMediaFolders","fieldMediaFolders","validCollections","addAssetCollections","assetCollections","_mediaFolder","_publicFolder","assetCollection","isAssetFolderReadonly","getAllAssetFolders","assetFolders","_globalMediaFolder","_globalPublicFolder","isGlobalFolderConfigured","allAssetsFolder","isRelativeFileCollectionFolder","allFolders","localeFolderNameMap","hasLocaleFolder","getFilePathMap","getCollectionFileFolder","compareFilePath","getEntryCollectionFolders","getFolderPath","getFileCollectionFolders","getSingletonCollectionFolders","singletonCollection","getAllEntryFolders","LOAD_CONFIG_DOC_URL","SCHEMA_TIP_URL","prefetchedResponses","requestFile","requestURL","fetchFile","manualInit","prefetched","schemaMissing","showSchemaTip","getConfigPath","verifyLinksAreSecure","links","getConfigLinks","prefetchCmsConfig","fetchCmsConfig","INVALID_FIELD_NAME_DOC_URL","COMPATIBILITY_DOC_URL","addMessage","locators","collector","warnings","locatorStr","extraMessage","extraStrKey","checkUnsupportedOptions","UNSUPPORTED_OPTIONS","VALID_NAME_REGEX","isValidName","checkName","strKeyBase","nameCounts","checkRegex","UNSUPPORTED_BACKEND_DOC_URL","UNSUPPORTED_BACKEND_SUGGESTION_URL","AUTH_DOC_URL","BACKEND_DOC_SLUGS","OPEN_AUTHORING_DOC_URL","INVALID_BRANCH_SEGMENT_REGEX","isValidBranchPath","parseBackendConfig","suggestion","allowTokenAuth","authDocURL","UNSUPPORTED_OPTIONS$8","BODY_FIELD_TYPES","KNOWN_FORMATS","isFormatMismatch","isFrontMatterFormat","normalizedExtension","normalizedFormat","fmFormatType","METADATA_KEYS","getCanonicalSlugKey","EXPLICIT_TYPE_REGEX","findFields","isFirstSegment","hasField","getRootFields","checkFieldReferences","prefixedOnly","specialTags","checkThumbnailField","checkFieldReferences$1","fieldTypes","checkDateTimeTags","checkPreviewPath","parseCodeFieldConfig","parseComputeFieldConfig","validateTimeZone","validateTimeZoneOptions","parseDateTimeFieldConfig","UNSUPPORTED_OPTIONS$7","TRANSFORMATION_KEYS","parseRasterImageTransformation","parseMediaLibraries","configs","checkMultipleDefault","checkObjectDefaultKeys","checkObjectDefault","keysArgs","parseFileFieldConfig","media_folder","UNSUPPORTED_OPTIONS$6","hasLocaleTag","parseHiddenFieldConfig","RANGE_OPTIONS","checkCommonFieldOptions","minOption","maxOption","parseCustomFieldConfig","fieldParsers","parseFieldConfig","isBuiltIn","parseFields","checkNameArgs","checkFieldType","OBJECT_FIELD_TYPES","checkDefaultValue","subfields","subfieldType","holdsObjects","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","checkArrayFileValueField","checkArrayFileWorkflowRelation","parentCollection","parseRelationFieldConfig","hasFiles","targetFields","UNSUPPORTED_OPTIONS$3","parseRichTextFieldConfig","UNSUPPORTED_OPTIONS$2","LOCALE_OPTIONS","checkLocales","hasLocalizedField","isNonEmptyArray","parseI18nConfig","checkI18nTargets","checkI18nOverrides","parseCollectionFile","previewPathDateField","parseCollectionFiles","checkCollectionFilter","DEFAULT_IDENTIFIER_FIELD","checkIdentifierField","SINGLE_FILE_STRUCTURES","checkSlugOptions","i18nConfig","SLUG_SPECIAL_TAGS","SUMMARY_SPECIAL_TAGS","checkCollectionTemplates","INTERNAL_SORT_KEYS","checkNamedViewOptions","isNameRequired","optionType","checkViewOptions","sortableFields","UNSUPPORTED_OPTIONS$1","index_file","reorderGroupName","view_groups","preview_path","preview_path_date_field","parseCollection","hasDivider","hasFolder","hasFile","optionCount","parseCollections","hasCloudMediaLibrary","media_library","media_libraries","parseMediaConfig","public_folder","asset_collections","parseSlugConfig","URL_OPTIONS","parseCmsConfig","countLevelsUp","lowest","getEntryDepth","checkRootDirPaths","entryFolders","entryDepth","decodeSegment","TAG_PROPERTIES","MAX_UNION_DEPTH","visited","getLeaves","getConstValues","leaf","describeTag","leaves","optional","leafValues","getRequired","getPropertyNames","matchProperty","buildChain","discriminateByTag","tagged","rewritten","discriminateByRequired","signatures","propertyNames","markers","otherIndex","fallbackIndex","prepareSchema","rewrite","allowUnknownProperties","deepCompareStrict","typeofa","aKeys","bKeys","encodePointer","escapePointer","schemaArrayKeyword","schemaMapKeyword","ignoredKeyword","initialBaseURI","dereference","baseURI","basePointer","schemaURI","keyBase","subSchema","DATE","DAYS","TIME","HOSTNAME","URIREF","URITEMPLATE","URL_","UUID","JSON_POINTER","JSON_POINTER_URI_FRAGMENT","RELATIVE_JSON_POINTER","EMAIL","IPV4","IPV6","DURATION","bind","date_time","isLeapYear","full","DATE_TIME_SEPARATOR","dateTime","NOT_URI_FRAGMENT","URI_PATTERN","Z_ANCHOR","ucs2length","charCode","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","thenResult","elseResult","subInstancePointer","dependantKey","propsOrSchema","thisEvaluated","length2","contained","Validator","SCHEMA_DRAFT","CONTAINER_KEYWORDS","FALSE_SCHEMA_KEYWORD","CONSTRAINT_PARAMS","resolveKeyword","location","resolveInstance","normalizeUnit","instancePath","keyword","param","findUnknownProperties","failedLocations","compileSchema","validator","getCustomFieldSchemas","validateSchema","metaSchema","applyCustomFieldSchemas","customField","VALUE_TYPES","formatValue","formatType","formatOption","appendFieldName","locateError","structural","describeError","reportSchemaErrors","relevant","other","hasAlternatives","missing","preparedSchemas","getConfigSchemas","configSchema","replaceRegExps","validateConfigSchema","violations","updateFolders","initCmsConfig","rawConfig","manualConfig","App","ncRoot","transitioned","documentTitle","link_1","link_2","link_3","link_4","COMPATIBILITY_URL","UNSUPPORTED_FUNC_NAMES","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","control","renderRichText","BundledReact","getFieldType","registerCustomFormat","fromFile","toFile","registerEditorComponent","htmlOptions","registerEventListener","eventListener","registerPreviewStyle","registerPreviewTemplate","registerFieldType","CMS","htm_module_default","parseStyle","addDeclaration","cssText","htm","main_default","Fragment","scriptElement"],"ignoreList":[0,1,2,3,4,5,6,7,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,266,270,271,272,273,274,279,280,281,282,290,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,489,490,491,509,511,512,513,514,515,516,517,518,520,521,522,523,526,955,956,957,1098,1099,1100,1101,1102,1103,1104,1105,1106,1107,1108,1109,1110,1111,1112,1113,1114,1115,1116,1117,1118,1119,1120,1121,1122,1123,1124,1125,1135,1177,1178,1179,1180,1181,1182,1183,1196],"sources":["../../node_modules/.pnpm/react@19.3.0/node_modules/react/cjs/react.production.js","../../node_modules/.pnpm/react@19.3.0/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.16/node_modules/dompurify/dist/purify.es.mjs","../../node_modules/.pnpm/isomorphic-dompurify@4.5.0/node_modules/isomorphic-dompurify/dist/browser.mjs","../../node_modules/.pnpm/marked@18.1.0/node_modules/marked/lib/marked.esm.js","../../src/lib/chunks/constants.js","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/object.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/shared/utils.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/constants.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/constants.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/warnings.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/hydration.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/equality.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/shared/errors.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/errors.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/shared/clone.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/shared/context.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/context.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/task.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/status.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/utils.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/misc.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/bindings/shared.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/async.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/deriveds.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/batch.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/sources.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/proxy.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/operations.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/error-handling.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/effects.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/legacy.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/runtime.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/utils.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dev/css.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/events.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/reconciler.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/template.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/reactivity/create-subscriber.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/boundary.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/render.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/branches.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/await.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/if.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/key.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/css-props.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/each.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/html.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/snippet.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/svelte-component.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/timing.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/loop.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/transitions.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/svelte-element.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/blocks/svelte-head.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/css.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/attachments.js","../../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/shared/attributes.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/class.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/style.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/bindings/select.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/attributes.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/bindings/input.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/bindings/size.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/dom/elements/bindings/this.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/store.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/client/reactivity/props.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/index-client.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/internal/disclose-version.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/cst/names.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/data-model/from-cst.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/errors.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/data-model/parse.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/data-model/visit.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/data-model/validate.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/dir-utils.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/utils.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/number.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/currency.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/datetime.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/offset.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/percent.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/string.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/unit.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/index.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/message-value.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/fallback.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/functions/unknown.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/resolve/function-context.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-function-ref.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-expression.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-variable.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/resolve/resolve-value.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/resolve/format-markup.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/select-pattern.js","../../node_modules/.pnpm/@sveltia+i18n@1.4.1_svelte@5.57.2_@typescript-eslint+types@8.71.1_/node_modules/@sveltia/i18n/dist/index.svelte.js","../../node_modules/.pnpm/messageformat@4.0.0/node_modules/messageformat/lib/messageformat.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/icon/icon.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/alert/alert-content.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/alert/alert.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/alert/alert.svelte","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/events.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/value.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/typography/truncated-text.svelte","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/misc.js","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/crypto.js","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/element.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/popup-position.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/popup.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/modal.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/placeholder.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/modal.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/popup.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/alert/infobar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/bottom-navigation/bottom-navigation.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/button-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/floating-action-button-wrapper.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/scroll.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/select.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/text.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/navigation.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/type-ahead.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/widget.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/group.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/select-button-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/select-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/button/split-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/divider/divider.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/divider/spacer.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/checkbox/checkbox-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/checkbox/checkbox.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/modal-close-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/dialog.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/alert-dialog.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/confirmation-dialog.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/emoji/caret.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/emoji/generated.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/emoji/emoji.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/emoji/position.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/emoji/emoji-suggestions.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/emoji-autocomplete.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/text-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/dialog/prompt-dialog.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/drawer/drawer.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/drawer/drawer.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/file/file-picker.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid-body.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/table/table-part.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid-cell.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid-row.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/grid/grid.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/listbox/listbox.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/listbox/option-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/listbox/option.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-item.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-item-checkable.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-item-checkbox.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/menu/menu-item-radio.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/progressbar/progressbar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/radio/radio-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/radio/radio.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/resizable-pane/sizing.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/resizable-pane/resizable-handle.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/resizable-pane/resizable-pane-group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/resizable-pane/resizable-pane.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/scroll/infinite-scroll.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/search-bar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/select/combobox.svelte","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/easing/index.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/animate/index.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/select/select.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/select/select-tags.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/select/select-tags.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/slider/slider.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/slider/slider.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/switch/switch.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/table/table-cell.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/table/table-row.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/table/table.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tabs/tab-list.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tabs/tab-list.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tabs/tab-panel.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tabs/tab.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/toast/toast.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/code-editor.js","../../node_modules/.pnpm/lexical@0.52.0_typescript@6.0.3/node_modules/lexical/dist/Lexical.prod.js","../../node_modules/.pnpm/@lexical+selection@0.52.0_typescript@6.0.3/node_modules/@lexical/selection/dist/LexicalSelection.prod.js","../../node_modules/.pnpm/@lexical+utils@0.52.0_typescript@6.0.3/node_modules/@lexical/utils/dist/LexicalUtils.prod.js","../../node_modules/.pnpm/@lexical+extension@0.52.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionConfig.prod.js","../../node_modules/.pnpm/@lexical+extension@0.52.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionInitialStateExtension.prod.js","../../node_modules/.pnpm/@lexical+extension@0.52.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionLexicalBuilder.prod.js","../../node_modules/.pnpm/@lexical+extension@0.52.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionGetPeerDependencyFromEditor.prod.js","../../node_modules/.pnpm/@preact+signals-core@1.14.4/node_modules/@preact/signals-core/dist/signals-core.module.js","../../node_modules/.pnpm/@lexical+extension@0.52.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionWatchedSignal.prod.js","../../node_modules/.pnpm/@lexical+extension@0.52.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionHorizontalRuleExtension.prod.js","../../node_modules/.pnpm/@lexical+extension@0.52.0_typescript@6.0.3/node_modules/@lexical/extension/dist/LexicalExtensionGetExtensionDependency.prod.js","../../node_modules/.pnpm/@lexical+html@0.52.0_typescript@6.0.3/node_modules/@lexical/html/dist/LexicalHtml.prod.js","../../node_modules/.pnpm/@lexical+code-core@0.52.0_typescript@6.0.3/node_modules/@lexical/code-core/dist/LexicalCodeCore.prod.js","../../node_modules/.pnpm/@lexical+link@0.52.0_typescript@6.0.3/node_modules/@lexical/link/dist/LexicalLink.prod.js","../../node_modules/.pnpm/@lexical+list@0.52.0_typescript@6.0.3/node_modules/@lexical/list/dist/LexicalList.prod.js","../../node_modules/.pnpm/@lexical+clipboard@0.52.0_typescript@6.0.3/node_modules/@lexical/clipboard/dist/LexicalClipboard.prod.js","../../node_modules/.pnpm/@lexical+dragon@0.52.0_typescript@6.0.3/node_modules/@lexical/dragon/dist/LexicalDragon.prod.js","../../node_modules/.pnpm/@lexical+rich-text@0.52.0_typescript@6.0.3/node_modules/@lexical/rich-text/dist/LexicalRichText.prod.js","../../node_modules/.pnpm/@lexical+markdown@0.52.0_typescript@6.0.3/node_modules/@lexical/markdown/dist/LexicalMarkdown.prod.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/constants.js","../../node_modules/.pnpm/@lexical+history@0.52.0_typescript@6.0.3/node_modules/@lexical/history/dist/LexicalHistory.prod.js","../../node_modules/.pnpm/@lexical+table@0.52.0_typescript@6.0.3/node_modules/@lexical/table/dist/LexicalTable.prod.js","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/string.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/background-update.js","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/storage/indexed-db.js","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/storage/local-storage.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/generated.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/cache.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/version.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/loader.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/theme.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/facade.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/html.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/markdown.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/shiki/highlighter.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/transformers/block-escape.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/transformers/hr.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/transformers/table.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/core.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/lexical-root.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/store.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/code-language-switcher.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/toolbar/toolbar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/toolbar-wrapper.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/code-editor-toolbar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/code-editor.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/text-area.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/emoji-autocomplete.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/floating-link-editor.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/raw-markdown.js","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/array.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/format-text-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/insert-component.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/insert-item-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/insert-link-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/insert-menu-button.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/toggle-block-menu-item.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/toolbar/text-editor-toolbar.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-editor/text-editor.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/number-input.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/number-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/masked-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/text-field/secret-input.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tree/tree-item.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/services/tree.svelte.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/tree/tree.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/app-shell.js","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/app-shell.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/empty-state.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/group.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/components/util/visibility-observer.svelte","../../node_modules/.pnpm/@sveltia+ui@0.80.2_svelte@5.57.2_@typescript-eslint+types@8.71.1__typescript@6.0.3/node_modules/@sveltia/ui/dist/locales/en-US.yaml","../../src/lib/services/app/index.js","../../src/lib/services/config/constants.js","../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js","../../src/lib/services/utils/state.svelte.js","../../src/lib/services/config/state.js","../../src/lib/services/config/index.js","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/file.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.4/node_modules/sanitize-filename/index.js","../../src/lib/services/utils/cache.js","../../src/lib/services/utils/file.js","../../src/lib/services/backends/root-dir.js","../../src/lib/services/backends/fs/shared/handles.js","../../node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/types/other.js","../../node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/types/standard.js","../../node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/src/Mime.js","../../node_modules/.pnpm/mime@4.1.0/node_modules/mime/dist/src/index.js","../../src/lib/services/assets/kinds.js","../../src/lib/services/assets/state.js","../../src/lib/services/assets/reserved.js","../../src/lib/services/backends/branch-access.js","../../src/lib/services/common/template/constants.js","../../src/lib/services/common/template/tags.js","../../src/lib/services/api/registries.js","../../node_modules/.pnpm/flat@6.0.1/node_modules/flat/index.js","../../src/lib/services/contents/fields/rich-text/components/utils.js","../../src/lib/services/contents/fields/rich-text/constants.js","../../src/lib/services/utils/string.js","../../src/lib/services/contents/fields/rich-text/components/definitions.js","../../src/lib/services/contents/i18n/placeholder.js","../../src/lib/services/workflow/constants.js","../../src/lib/services/workflow/open-authoring.js","../../src/lib/services/assets/folders.js","../../src/lib/services/backends/fs/shared/constants.js","../../src/lib/services/backends/git/shared/config.js","../../src/lib/services/contents/index.js","../../src/lib/services/backends/fs/shared/scan.js","../../src/lib/services/backends/git/shared/concurrency.js","../../src/lib/services/contents/collection/predicates.js","../../src/lib/services/contents/collection/entries/index-file.js","../../src/lib/services/contents/fields/index.js","../../src/lib/services/config/deprecations.js","../../src/lib/services/contents/file/constants.js","../../src/lib/services/contents/collection/nested/index.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/contents/collection/index.js","../../src/lib/services/contents/collection/files/index.js","../../src/lib/services/contents/entry/key-paths.js","../../src/lib/services/utils/object.js","../../src/lib/services/contents/entry/subtree.js","../../src/lib/services/integrations/media-libraries/multiple.js","../../src/lib/services/utils/number.js","../../src/lib/services/contents/entry/fields.js","../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js","../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/primitive.js","../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/date.js","../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/extract.js","../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/util.js","../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/struct.js","../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/parse.js","../../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/stringify.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/detected-formats.js","../../src/lib/services/contents/file/parse.js","../../src/lib/services/utils/scheduling.js","../../src/lib/services/contents/file/process.js","../../src/lib/services/contents/folders.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/gitea/constants.js","../../src/lib/services/user/constants.js","../../src/lib/services/user/account.svelte.js","../../src/lib/services/backends/git/shared/api.js","../../src/lib/services/backends/git/shared/user.js","../../src/lib/services/backends/git/gitea/user.js","../../src/lib/services/backends/git/shared/auth.js","../../src/lib/services/backends/git/gitea/auth.js","../../src/lib/services/backends/git/shared/errors.js","../../src/lib/services/backends/git/shared/url.js","../../src/lib/services/user/prefs.svelte.js","../../src/lib/services/backends/git/shared/repository.js","../../src/lib/services/backends/git/gitea/repository.js","../../src/lib/services/backends/git/gitea/instance.js","../../src/lib/services/backends/git/shared/fork.js","../../src/lib/services/backends/git/gitea/fork.js","../../src/lib/services/backends/git/shared/commits.js","../../src/lib/services/backends/git/shared/head.js","../../src/lib/services/backends/git/gitea/commits.js","../../src/lib/services/backends/git/shared/api-optional.js","../../src/lib/services/backends/git/shared/defer.js","../../src/lib/services/backends/git/shared/reconcile.js","../../src/lib/services/contents/entry/paths.js","../../src/lib/services/backends/git/shared/reparse.js","../../src/lib/services/backends/git/shared/parse-files.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/tree.js","../../src/lib/services/backends/git/gitea/files.js","../../src/lib/services/backends/git/shared/pull-requests.js","../../src/lib/services/backends/git/shared/workflow.js","../../src/lib/services/workflow/labels.js","../../src/lib/services/backends/git/gitea/pull-requests.js","../../src/lib/services/workflow/branch.js","../../src/lib/services/backends/git/gitea/workflow-fork.js","../../src/lib/services/backends/git/gitea/workflow.js","../../src/lib/services/backends/git/shared/init.js","../../src/lib/services/workflow/config.js","../../src/lib/services/backends/git/gitea/index.js","../../src/lib/services/backends/git/github/constants.js","../../src/lib/services/backends/git/github/api.js","../../src/lib/services/backends/git/github/user.js","../../src/lib/services/backends/git/github/auth.js","../../src/lib/services/backends/git/github/repository.js","../../src/lib/services/backends/git/github/fork.js","../../src/lib/services/utils/array.js","../../src/lib/services/backends/git/github/graphql.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/progress.js","../../src/lib/services/backends/git/github/files.js","../../src/lib/services/backends/git/github/status.js","../../src/lib/services/backends/git/github/pull-requests.js","../../src/lib/services/backends/git/github/workflow-fork.js","../../src/lib/services/backends/git/github/workflow.js","../../src/lib/services/backends/git/github/index.js","../../src/lib/services/backends/git/gitlab/constants.js","../../src/lib/services/backends/git/gitlab/user.js","../../src/lib/services/backends/git/gitlab/auth.js","../../src/lib/services/backends/git/gitlab/repository.js","../../src/lib/services/backends/git/gitlab/fork.js","../../src/lib/services/backends/git/gitlab/commits.js","../../src/lib/services/backends/git/gitlab/deployment.js","../../src/lib/services/backends/git/gitlab/files.js","../../src/lib/services/backends/git/gitlab/status.js","../../src/lib/services/backends/git/gitlab/merge-requests.js","../../src/lib/services/backends/git/gitlab/workflow-fork.js","../../src/lib/services/backends/git/gitlab/workflow.js","../../src/lib/services/backends/git/gitlab/index.js","../../src/lib/services/backends/git/services.js","../../src/lib/services/utils/database.js","../../src/lib/services/backends/fs/local.js","../../src/lib/services/backends/fs/test.js","../../src/lib/services/backends/index.js","../../node_modules/.pnpm/@sindresorhus+transliterate@2.3.1/node_modules/@sindresorhus/transliterate/replacements.js","../../node_modules/.pnpm/@sindresorhus+transliterate@2.3.1/node_modules/@sindresorhus/transliterate/locale-replacements.js","../../node_modules/.pnpm/@sindresorhus+transliterate@2.3.1/node_modules/@sindresorhus/transliterate/index.js","../../src/lib/services/common/slug/constants.js","../../src/lib/services/common/slug/index.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/sniff.js","../../src/lib/services/app/dependencies.js","../../src/lib/services/utils/media/image/encode.js","../../src/lib/services/utils/media/image/heic.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/utils/regex.js","../../src/lib/services/common/view.js","../../src/lib/services/assets/view/filter.js","../../src/lib/services/assets/view/group.js","../../node_modules/.pnpm/@sveltia+utils@0.12.3/node_modules/@sveltia/utils/dist/datetime.js","../../src/lib/services/common/template/utils.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/common/transformations.js","../../node_modules/.pnpm/dayjs@1.11.23/node_modules/dayjs/plugin/timezone.js","../../src/lib/services/utils/date.js","../../src/lib/services/contents/fields/date-time/parse.js","../../src/lib/services/contents/fields/date-time/display.js","../../src/lib/services/contents/entry/collections.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/fields/relation/helpers/filters.js","../../src/lib/services/contents/fields/relation/helpers/index.js","../../src/lib/services/contents/fields/select/helpers.js","../../src/lib/services/utils/markdown.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/common/template/index.js","../../src/lib/services/assets/index.js","../../src/lib/services/utils/media/image/svg.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/integrations/media-libraries/cloud/search.js","../../src/lib/services/integrations/media-libraries/paging.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/utils/crypto.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/scaleway.js","../../src/lib/services/integrations/media-libraries/cloud/s3/supabase.js","../../src/lib/services/assets/file-name.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/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/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/utils/url.js","../../src/lib/services/utils/window.js","../../src/lib/services/app/navigation.js","../../src/lib/services/backends/refresh.js","../../src/lib/services/backends/poll.js","../../src/lib/services/deployments/constants.js","../../src/lib/services/deployments/ping.js","../../src/lib/services/backends/git/shared/integration.js","../../src/lib/services/workflow/index.js","../../src/lib/services/deployments/resolve.js","../../src/lib/services/workflow/deploy.js","../../src/lib/services/workflow/assets.js","../../src/lib/services/workflow/entries.js","../../src/lib/services/workflow/load.js","../../src/lib/services/user/auth.svelte.js","../../src/lib/services/user/sign-in-options.js","../../src/lib/components/entrance/sign-in.svelte","../../src/lib/services/app/branding.js","../../src/lib/components/entrance/entrance-page.svelte","../../src/lib/components/global/infobars/backend-status-indicator.svelte","../../src/lib/services/app/update.js","../../src/lib/components/global/infobars/update-notification.svelte","../../src/lib/locales/en-US.yaml","../../src/lib/services/app/i18n.js","../../src/lib/components/global/locale-load-error-toast.svelte","../../src/lib/components/common/cascade-delete-note.svelte","../../src/lib/components/assets/list/delete-assets-button.svelte","../../src/lib/components/common/page-toolbar/back-button.svelte","../../src/lib/services/app/focus.js","../../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/contents/collection/data/index.js","../../src/lib/services/assets/data/index.js","../../src/lib/services/assets/name.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/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/assets/file-size.js","../../src/lib/services/assets/file-type.js","../../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/services/utils/render.js","../../src/lib/components/assets/shared/asset-preview.svelte","../../src/lib/components/assets/list/external/info-panel.svelte","../../src/lib/services/contents/fields/rich-text/sanitize.js","../../src/lib/components/assets/list/text-preview.svelte","../../src/lib/components/global/not-found.svelte","../../src/lib/services/search/util.js","../../src/lib/services/assets/external/view.js","../../src/lib/components/assets/list/external/details-overlay.svelte","../../src/lib/components/assets/browser/cloudinary-panel.svelte","../../src/lib/components/assets/shared/image.svelte","../../src/lib/components/common/remove-button.svelte","../../src/lib/components/assets/shared/upload-assets-preview.svelte","../../src/lib/components/assets/shared/drop-zone.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/services/integrations/service-description.js","../../src/lib/services/user/api-keys.js","../../src/lib/components/assets/shared/cloud-service-auth.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/subfolder-name-dialog.svelte","../../src/lib/components/assets/list/external/new-folder-dialog.svelte","../../src/lib/components/assets/list/new-folder-button.svelte","../../src/lib/components/assets/list/external/new-folder-button.svelte","../../src/lib/components/assets/list/preview-asset-button.svelte","../../src/lib/components/common/breadcrumb.svelte","../../src/lib/components/assets/list/primary-toolbar.svelte","../../src/lib/components/assets/list/external/primary-toolbar.svelte","../../src/lib/components/assets/shared/file-extension-change-dialog.svelte","../../src/lib/components/assets/list/rename-dialog.svelte","../../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/filter-menu.svelte","../../src/lib/components/common/page-toolbar/group-menu.svelte","../../src/lib/components/common/page-toolbar/item-selector.svelte","../../src/lib/services/contents/collection/view/options.js","../../src/lib/services/contents/collection/view/sort-keys.js","../../src/lib/components/common/page-toolbar/sort-menu.svelte","../../src/lib/components/common/page-toolbar/view-switcher.svelte","../../src/lib/components/assets/list/secondary-toolbar.svelte","../../src/lib/components/assets/shared/rejected-files-alert-dialog.svelte","../../src/lib/components/common/page-container-main-area.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/services/config/readonly.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/save/key-path.js","../../src/lib/services/contents/entry/aliases.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/draft/save/file-changes.js","../../src/lib/services/api/lazy-module.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/api/preview-data.js","../../src/lib/services/contents/fields/custom/helpers.js","../../src/lib/services/contents/draft/validate/custom-fields.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/validate.js","../../src/lib/services/contents/fields/rich-text/index.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/fields/key-value/validate.js","../../src/lib/services/contents/fields/object/helpers.js","../../src/lib/services/contents/fields/list/helpers.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/validity.js","../../src/lib/services/contents/fields/date-time/auto-now.js","../../src/lib/services/contents/i18n/fields.js","../../src/lib/services/contents/draft/validate/fields.js","../../src/lib/services/contents/entry/index.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/collection/slug.js","../../src/lib/services/contents/draft/slugs.js","../../src/lib/services/contents/collection/nested/i18n.js","../../src/lib/services/contents/draft/save/entry-path.js","../../src/lib/services/contents/draft/save/assets.js","../../src/lib/services/contents/draft/save/changes.js","../../src/lib/services/contents/entry/changes.js","../../src/lib/services/contents/entry/readonly.js","../../src/lib/services/contents/entry/cascade.js","../../src/lib/services/assets/data/cascade.js","../../src/lib/services/contents/file/array.js","../../src/lib/services/backends/save.js","../../src/lib/services/assets/data/delete.js","../../src/lib/services/assets/data/move.js","../../src/lib/services/assets/data/subfolder.js","../../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/edit-options-button.svelte","../../src/lib/components/common/leaflet-map.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/components/assets/list/create-subfolder-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/components/global/toolbar/items/quick-search-bar.svelte","../../src/lib/components/assets/list/primary-sidebar.svelte","../../src/lib/services/app/ui-settings.js","../../src/lib/components/common/page-container.svelte","../../src/lib/components/search/asset-result-item.svelte","../../src/lib/services/search/assets.js","../../src/lib/components/search/asset-results.svelte","../../src/lib/components/contents/shared/entry-thumbnail.svelte","../../src/lib/components/search/entry-result-item.svelte","../../src/lib/services/search/entries.js","../../src/lib/components/search/entry-results.svelte","../../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/config/config-page.svelte","../../src/lib/services/contents/fields/relation/helpers/locale.js","../../src/lib/services/contents/draft/create/proxy.svelte.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/hidden/defaults.js","../../src/lib/services/contents/fields/key-value/defaults.js","../../src/lib/services/contents/fields/list/defaults.js","../../src/lib/services/contents/fields/number/defaults.js","../../src/lib/services/contents/fields/object/defaults.js","../../src/lib/services/contents/fields/rich-text/defaults.js","../../src/lib/services/contents/fields/select/defaults.js","../../src/lib/services/contents/fields/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/list.js","../../src/lib/services/contents/entry/content-index.js","../../src/lib/services/contents/draft/backup.js","../../src/lib/components/contents/details/backup-feedback.svelte","../../src/lib/services/contents/draft/state.svelte.js","../../src/lib/services/integrations/ai/api.js","../../src/lib/services/integrations/ai/anthropic.js","../../src/lib/services/integrations/translators/ai-translation.js","../../src/lib/services/integrations/translators/anthropic.js","../../src/lib/services/integrations/ai/deepseek.js","../../src/lib/services/integrations/translators/deepseek.js","../../src/lib/services/integrations/translators/google.js","../../src/lib/services/integrations/ai/google.js","../../src/lib/services/integrations/translators/google-ai.js","../../src/lib/services/integrations/ai/mistral.js","../../src/lib/services/integrations/translators/mistral.js","../../src/lib/services/integrations/ai/openai.js","../../src/lib/services/integrations/translators/index.js","../../src/lib/services/integrations/translators/openai.js","../../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/components/contents/details/editor/validation-error.svelte","../../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/value-map.svelte.js","../../src/lib/services/contents/editor/pending.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/components/contents/details/fields/compute/compute-preview.svelte","../../src/lib/components/assets/browser/asset-path.svelte","../../src/lib/components/assets/browser/picker-breadcrumb.svelte","../../src/lib/components/assets/browser/simple-image-grid-item.svelte","../../src/lib/components/assets/browser/simple-image-grid.svelte","../../src/lib/components/assets/browser/subfolder-strip.svelte","../../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/assets/browser/select-assets-dialog.svelte.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/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/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/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/common/editable-text.svelte","../../src/lib/services/utils/drag-sorting.js","../../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/components/contents/details/fields/file/upload-button.svelte","../../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/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/common/expand-icon.svelte","../../src/lib/components/contents/details/fields/object/object-body.svelte","../../src/lib/components/contents/details/fields/object/object-header.svelte","../../src/lib/services/contents/editor/fields.js","../../src/lib/services/contents/fields/list/items.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/fields/object/subsection.svelte","../../src/lib/services/contents/editor/locale.js","../../src/lib/components/contents/details/preview/field-preview.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/services/contents/fields/map/geocoding.js","../../src/lib/services/contents/fields/map/helpers.js","../../src/lib/components/contents/details/fields/map/map-editor.svelte","../../src/lib/components/contents/details/fields/map/map-preview.svelte","../../src/lib/services/contents/fields/number/helpers.js","../../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/services/contents/draft/create/normalize.js","../../src/lib/services/contents/fields/uuid/helpers.js","../../src/lib/services/contents/draft/create/uuid.js","../../src/lib/services/contents/draft/create/index.js","../../src/lib/services/contents/draft/validate/slugs.js","../../src/lib/services/contents/editor/slug.js","../../src/lib/components/contents/details/editor/slug-editor.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/fields/compute/helpers.js","../../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/pending-entries.js","../../src/lib/services/contents/draft/save/sort-order.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/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/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.js","../../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/images.js","../../src/lib/components/contents/details/fields/rich-text/rich-text-editor.svelte","../../node_modules/.pnpm/marked-bidi@1.0.15_marked@18.1.0/node_modules/marked-bidi/src/index.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/reactivity/set.js","../../node_modules/.pnpm/svelte@5.57.2_@typescript-eslint+types@8.71.1/node_modules/svelte/src/reactivity/map.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/contents/draft/update/reset.js","../../src/lib/services/contents/draft/update/revert.js","../../src/lib/components/contents/details/editor/field-editor.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/components/contents/details/preview/entry-preview-iframe.svelte","../../src/lib/services/contents/editor/preview-templates.js","../../src/lib/components/contents/details/preview/entry-preview.svelte","../../src/lib/services/contents/editor/scroll.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/services/contents/draft/save/conflict.js","../../src/lib/services/contents/draft/reload.js","../../src/lib/components/contents/details/remote-change-infobar.svelte","../../src/lib/components/contents/details/sidebar/panels/panel-container.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/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/reorder/index.js","../../src/lib/services/contents/collection/data/delete.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/services/workflow/editor.js","../../src/lib/services/workflow/validate.js","../../src/lib/components/workflow/entry-status-menu.svelte","../../src/lib/components/workflow/publish-entry-button.svelte","../../src/lib/services/contents/collection/view/conditions.js","../../src/lib/services/contents/collection/view/filter.js","../../src/lib/services/contents/collection/view/settings.js","../../src/lib/services/contents/collection/view/group.js","../../src/lib/services/contents/collection/view/sort.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/contents/collection/nested/move.js","../../src/lib/services/contents/draft/save/asset-move.js","../../src/lib/services/workflow/conflict.js","../../src/lib/services/contents/draft/save/index.js","../../src/lib/services/contents/editor/toolbar.js","../../src/lib/components/contents/details/toolbar.svelte","../../src/lib/components/contents/details/content-details-overlay.svelte","../../src/lib/components/workflow/status-badge.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/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/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/onboarding.js","../../src/lib/components/global/infobars/mobile-promo-infobar.svelte","../../src/lib/components/global/infobars/new-language-infobar.svelte","../../src/lib/components/global/not-found-page.svelte","../../src/lib/components/global/toolbar/items/page-switcher.svelte","../../src/lib/components/global/toolbar/bottom-navigation.svelte","../../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/services/app/cache.js","../../src/lib/components/settings/panels/advanced-panel.svelte","../../src/lib/components/settings/panels/appearance-panel.svelte","../../src/lib/components/settings/panels/contents-panel.svelte","../../src/lib/components/settings/controls/api-key-input.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","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/can-promise.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/utils.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/error-correction-level.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/bit-buffer.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/bit-matrix.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/alignment-pattern.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/finder-pattern.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/mask-pattern.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/error-correction-code.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/galois-field.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/polynomial.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/reed-solomon-encoder.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/version-check.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/regex.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/mode.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/version.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/format-info.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/numeric-data.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/alphanumeric-data.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/byte-data.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/kanji-data.js","../../node_modules/.pnpm/dijkstrajs@1.0.3/node_modules/dijkstrajs/dijkstra.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/segments.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/qrcode.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/renderer/utils.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/renderer/canvas.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/renderer/svg-tag.js","../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/browser.js","../../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/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js","../../src/lib/services/config/folders/assets.js","../../src/lib/services/config/folders/entries.js","../../src/lib/services/config/loader.js","../../src/lib/services/config/parser/utils/validator.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/fields/code.js","../../src/lib/services/config/parser/fields/compute.js","../../src/lib/services/config/parser/fields/datetime.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/filter.js","../../src/lib/services/config/parser/collections/identifier.js","../../src/lib/services/config/parser/collections/slug.js","../../src/lib/services/config/parser/collections/templates.js","../../src/lib/services/config/parser/collections/views.js","../../src/lib/services/config/parser/collections/index.js","../../src/lib/services/config/parser/media.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.1/node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/pointer.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/dereference.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/format.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/node_modules/@cfworker/json-schema/dist/esm/validate.js","../../node_modules/.pnpm/@cfworker+json-schema@4.1.1/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/compatibility.js","../../src/lib/services/api/field-types.svelte.js","../../src/lib/services/api/field-types.js","../../src/lib/services/api/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.0\";\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.16 | (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.16/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 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);\nArray.prototype.indexOf;\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nArray.prototype.slice;\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\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 regExpTest = unapply(RegExp.prototype.test);\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\tif (thisArg instanceof RegExp) thisArg.lastIndex = 0;\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* 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}\nfunction isRegex(value) {\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\"enterkeyhint\",\n\t\"exportparts\",\n\t\"filter\",\n\t\"font\",\n\t\"g\",\n\t\"glyph\",\n\t\"glyphref\",\n\t\"hkern\",\n\t\"image\",\n\t\"inputmode\",\n\t\"line\",\n\t\"lineargradient\",\n\t\"marker\",\n\t\"mask\",\n\t\"metadata\",\n\t\"mpath\",\n\t\"part\",\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 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 NODE_TYPE = {\n\telement: 1,\n\tattribute: 2,\n\ttext: 3,\n\tcdataSection: 4,\n\tentityReference: 5,\n\tentityNode: 6,\n\tprocessingInstruction: 7,\n\tcomment: 8,\n\tdocument: 9,\n\tdocumentType: 10,\n\tdocumentFragment: 11,\n\tnotation: 12\n};\nconst LITERAL_TEXT_ELEMENT_NAMES = [\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 LITERAL_TEXT_ELEMENTS = freeze(addToSet({}, LITERAL_TEXT_ELEMENT_NAMES));\nconst LITERAL_TEXT_CLOSE = function() {\n\tconst map = {};\n\tarrayForEach(LITERAL_TEXT_ELEMENT_NAMES, (name) => {\n\t\tmap[name] = seal(new RegExp(\"</\" + name + \"(?=[\\\\t\\\\n\\\\f\\\\r />])\", \"i\"));\n\t});\n\treturn freeze(map);\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: a fresh set built from\n* cfg[key] when it is an own array property (seeded with a clone of\n* options.base when given, case-normalized via options.transform),\n* the fallback set otherwise.\n*\n* @param cfg the cloned, prototype-free configuration object\n* @param key the configuration property to read\n* @param fallback the set to use when the option is absent or not an array\n* @param options transform and optional base set to merge into\n* @returns the resolved set\n*/\nconst _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {\n\treturn objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;\n};\n/**\n* Resolve an object-valued configuration option: a prototype-free clone\n* of cfg[key] when it is an own, truthy object property, else a fresh\n* fallback built by makeFallback (fresh on every parse, so a previous\n* parse can never leak state into the next one).\n*\n* @param cfg the cloned, prototype-free configuration object\n* @param key the configuration property to read\n* @param makeFallback builds the fallback value when the option is absent\n* @returns the resolved object\n*/\nconst _resolveObjectOption = function _resolveObjectOption(cfg, key, makeFallback) {\n\tconst value = objectHasOwnProperty(cfg, key) ? cfg[key] : void 0;\n\treturn value && typeof value === \"object\" ? clone(value) : makeFallback();\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.16\";\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\twindow.DocumentFragment;\n\tconst HTMLTemplateElement = window.HTMLTemplateElement, Node = window.Node, Element = window.Element, NodeFilter = window.NodeFilter;\n\twindow.NamedNodeMap === void 0 && (window.NamedNodeMap || window.MozNamedAttrMap);\n\twindow.HTMLFormElement;\n\tconst 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\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 _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 = Object.seal(create(null, {\n\t\ttagNameCheck: {\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\tattributeNameCheck: {\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\tallowCustomizedBuiltInElements: {\n\t\t\twritable: true,\n\t\t\tconfigurable: false,\n\t\t\tenumerable: true,\n\t\t\tvalue: false\n\t\t}\n\t}));\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 USE_PROFILES = {};\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([\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 = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);\n\tconst DEFAULT_HTML_INTEGRATION_POINTS = freeze([\"annotation-xml\"]);\n\tlet HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);\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 (CONFIG && CONFIG === cfg) return;\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\", clone({}), { transform: transformCaseFunc });\n\t\tFORBID_ATTR = _resolveSetOption(cfg, \"FORBID_ATTR\", clone({}), { 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\", () => addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS));\n\t\tHTML_INTEGRATION_POINTS = _resolveObjectOption(cfg, \"HTML_INTEGRATION_POINTS\", () => addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS));\n\t\tconst customElementHandling = _resolveObjectOption(cfg, \"CUSTOM_ELEMENT_HANDLING\", () => create(null));\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\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 = clone(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 = clone(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 = clone(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\taddToSet(ALLOWED_TAGS, [\"tbody\"]);\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\tif (freeze) freeze(cfg);\n\t\tCONFIG = 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 parent the (possibly simulated) parent node\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, parent, parentTagName) {\n\t\tif (parent.namespaceURI === HTML_NAMESPACE) return tagName === \"svg\";\n\t\tif (parent.namespaceURI === 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 parent the (possibly simulated) parent node\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, parent, parentTagName) {\n\t\tif (parent.namespaceURI === HTML_NAMESPACE) return tagName === \"math\";\n\t\tif (parent.namespaceURI === 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 parent the (possibly simulated) parent node\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, parent, parentTagName) {\n\t\tif (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) return false;\n\t\tif (parent.namespaceURI === 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\tlet parent = getParentNode(element);\n\t\tif (!parent || !parent.tagName) parent = {\n\t\t\tnamespaceURI: NAMESPACE,\n\t\t\ttagName: \"template\"\n\t\t};\n\t\tconst tagName = stringToLowerCase(element.tagName);\n\t\tconst parentTagName = stringToLowerCase(parent.tagName);\n\t\tif (!ALLOWED_NAMESPACES[element.namespaceURI]) return false;\n\t\tif (element.namespaceURI === SVG_NAMESPACE) return _checkSvgNamespace(tagName, parent, parentTagName);\n\t\tif (element.namespaceURI === MATHML_NAMESPACE) return _checkMathMlNamespace(tagName, parent, parentTagName);\n\t\tif (element.namespaceURI === HTML_NAMESPACE) return _checkHtmlNamespace(tagName, parent, parentTagName);\n\t\tif (PARSER_MEDIA_TYPE === \"application/xhtml+xml\" && ALLOWED_NAMESPACES[element.namespaceURI]) return true;\n\t\treturn false;\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* _stripAttributeNode\n\t*\n\t* Remove a single Attr node case/namespace-exactly on an attribute-teardown\n\t* path. Name-based removeAttribute() ASCII-lowercases its lookup key for an\n\t* HTML element in an HTML document and so silently misses a case-preserved\n\t* handler (e.g. `ONERROR` off an XML/XHTML import) - the same defect\n\t* _removeAttribute() was fixed for, which a name-based call would reintroduce\n\t* on these IN_PLACE teardown paths. Unlike _removeAttribute this does not\n\t* record into DOMPurify.removed: the neutralize passes intentionally do not\n\t* book-keep. A clobbered/detached node falls back to best-effort name-based\n\t* removal.\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* _neutralizeRoot\n\t*\n\t* Fail-closed teardown of an in-place root after the sanitize walk aborts\n\t* (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered\n\t* custom element's reaction detaches a node so `_forceRemove`'s deliberate\n\t* parentless guard throws, or any other re-entrant engine mutation — would\n\t* otherwise leave the caller's *live* tree half-sanitized, with everything\n\t* after the abort point still carrying its handlers. There is no safe way\n\t* to resume the walk (the tree mutated under us), so we strip the root bare:\n\t* remove every child and every attribute, then let the caller's catch see\n\t* the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`\n\t* getters; the root was already clobber-pre-flighted at the IN_PLACE entry).\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) {\n\t\t\tconst snapshot = [];\n\t\t\tarrayForEach(childNodes, (child) => {\n\t\t\t\tarrayPush(snapshot, child);\n\t\t\t});\n\t\t\tarrayForEach(snapshot, (child) => {\n\t\t\t\ttry {\n\t\t\t\t\tremove(child);\n\t\t\t\t} catch (_) {}\n\t\t\t});\n\t\t}\n\t\tconst attributes = getAttributes(root);\n\t\tif (attributes) for (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\") _stripAttributeNode(root, attribute, name);\n\t\t}\n\t};\n\t/**\n\t* _removeAttribute\n\t*\n\t* Name-based getAttributeNode()/removeAttribute() ASCII-lowercase their\n\t* lookup key for HTML elements in an HTML document, so they silently miss an\n\t* attribute whose stored qualified name still contains uppercase ASCII\n\t* letters. That happens when the node came from a case-preserving source\n\t* (an XML/XHTML document imported via importNode(), or createAttributeNS()),\n\t* where e.g. `ONERROR` survives the walk: the policy check lowercases to\n\t* `onerror` and rejects it, but `removeAttribute('ONERROR')` looks up\n\t* `onerror` and finds nothing. Remove the exact Attr node instead, which is\n\t* case- and namespace-exact, and fall back to name-based removal only when\n\t* the caller could not supply the node.\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\ttry {\n\t\t\tif (attr) removeAttributeNode(element, attr);\n\t\t\telse element.removeAttribute(name);\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\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* _stripDisallowedAttributes\n\t*\n\t* Removes every attribute the active configuration does not allow from a\n\t* single element, using the same allowlist as the main attribute pass (so\n\t* `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to\n\t* neutralise nodes that are being discarded from an in-place tree.\n\t*\n\t* @param element the element to strip\n\t*/\n\tconst _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {\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\" || ALLOWED_ATTR[transformCaseFunc(name)]) continue;\n\t\t\t_stripAttributeNode(element, attribute, name);\n\t\t}\n\t};\n\t/**\n\t* _neutralizeSubtree\n\t*\n\t* Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT\n\t* move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,\n\t* namespace, comment, processing-instruction and KEEP_CONTENT:false removals\n\t* all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path\n\t* those dropped nodes are detached from the caller's LIVE tree but a\n\t* handler-bearing original among them (an `<img onerror>`/`<video>` that was\n\t* loading) keeps its queued resource event, which fires in page scope after\n\t* sanitize returns. This walks a removed subtree and strips every attribute\n\t* the active configuration does not allow — so `on*` handlers are cancelled\n\t* through the SAME allowlist that governs kept nodes, not a separate `/^on/`\n\t* blocklist. Run synchronously before sanitize returns, i.e. before any\n\t* queued event can fire. Hook-free by design: these nodes leave the output,\n\t* so firing attribute hooks for them would be surprising. Clobber-safe reads;\n\t* a doomed clobbered node may shadow `removeAttribute` (its own attributes are\n\t* irrelevant — it is discarded — while its non-clobbered descendants, e.g.\n\t* the `<img>`, are reached and scrubbed).\n\t*\n\t* @param root the root of a removed subtree to neutralise\n\t*/\n\tconst _neutralizeSubtree = function _neutralizeSubtree(root) {\n\t\tconst stack = [root];\n\t\twhile (stack.length > 0) {\n\t\t\tconst node = stack.pop();\n\t\t\tif (_readNodeType(node) === NODE_TYPE.element) _stripDisallowedAttributes(node);\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* _neutralizePatchLinkage\n\t*\n\t* IN_PLACE entry pre-pass (declarative-partial-updates / streaming\n\t* hardening, https://github.com/WICG/declarative-partial-updates).\n\t*\n\t* The main walk strips patch linkage (`for`/`patchsrc`) and removes range\n\t* markers (PIs / markup comments) node-by-node, in document order, AS it\n\t* reaches each node. On a live in-place root that leaves a window: from the\n\t* moment the root is connected until the walk arrives at a given node, that\n\t* node's linkage is live. A patch applied on connection/stream can fire as\n\t* a microtask during the walk and inject or teleport an unsanitized DOM\n\t* range into a region the iterator has already passed and will not revisit,\n\t* so the post-return \"tree is sanitized\" contract is violated. Sweep the\n\t* whole tree once up front and sever every linkage before the walk begins,\n\t* closing that window.\n\t*\n\t* This CANNOT undo a patch that already fired before sanitize ran — that is\n\t* the irreducible \"do not IN_PLACE a live-connected attacker tree\" caveat —\n\t* but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML\n\t* to group with the rest of the declarative-partial-updates handling and\n\t* stay overridable, consistent with the codebase.\n\t*\n\t* Clobber-safe traversal (cached childNodes getter); per-node try/catch so a\n\t* clobbered root cannot defeat the sweep of its non-clobbered descendants.\n\t*\n\t* NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe\n\t* .html Q1): this mirrors the existing policy of keeping `for` on\n\t* <label>/<output>. If the shipping feature can drive a patch through a\n\t* surviving `for`-on-label/output + `id` pair, this pre-pass and the\n\t* attribute check at _isBasicCustomElement's caller must additionally drop\n\t* that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.\n\t*\n\t* @param root the in-place root to sweep\n\t*/\n\t/**\n\t* Central policy for declarative-partial-updates patch-linkage attributes,\n\t* shared by the _neutralizePatchLinkage pre-pass and _isValidAttribute so\n\t* the two sites cannot drift: `patchsrc` always links, `for` links\n\t* everywhere except on <label>/<output>, and the whole policy is gated on\n\t* SAFE_FOR_XML (see the rationale block in _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\tconst _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {\n\t\tif (!SAFE_FOR_XML) return;\n\t\tconst stack = [root];\n\t\twhile (stack.length > 0) {\n\t\t\tconst node = stack.pop();\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\tcontinue;\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\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* _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, /^[\\r\\n\\t ]+/);\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 object that you can use to traverse filtered lists of nodes or elements in a document.\n\t*\n\t* @param root The root element or node to start traversing on.\n\t* @return The created NodeIterator\n\t*/\n\tconst _createNodeIterator = function _createNodeIterator(root) {\n\t\tconst doc = getOwnerDocument ? getOwnerDocument(root) : root.ownerDocument;\n\t\treturn createNodeIterator.call(doc || root, root, 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* Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the\n\t* character data of an element subtree. Used as the final safety net for\n\t* SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions\n\t* which only form after text-node normalization (e.g. fragments split across\n\t* stripped elements) cannot survive into a template-evaluating framework.\n\t*\n\t* Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`\n\t* in place rather than round-tripping through innerHTML. This preserves\n\t* descendant node references (important for IN_PLACE callers), avoids a\n\t* serialize/reparse cycle, and reads literal character data — which means\n\t* `<%...%>` in text content matches the ERB regex against its real bytes\n\t* instead of the HTML-entity-escaped form innerHTML would produce.\n\t*\n\t* Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for\n\t* attributes is performed during the per-node `_sanitizeAttributes` pass.\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\tnode.normalize();\n\t\tconst doc = getOwnerDocument ? getOwnerDocument(node) : node.ownerDocument;\n\t\tconst walker = createNodeIterator.call(doc || node, node, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);\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\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* _isClobbered\n\t*\n\t* Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML\n\t* interface with [LegacyOverrideBuiltIns]; a descendant element with a\n\t* `name` attribute matching a prototype property shadows that property\n\t* on direct reads. We use this check at the IN_PLACE entry-point and\n\t* during attribute sanitization to refuse clobbered forms.\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* Checks whether the given value is a DocumentFragment from any realm.\n\t*\n\t* The realm-independent replacement reads `nodeType` through the cached\n\t* Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE\n\t* constant (11). nodeType is a numeric value resolved from the node's\n\t* internal slot, identical across realms for the same kind of node.\n\t*\n\t* @param value object to check\n\t* @return true if value is a DocumentFragment-shaped node from any realm\n\t*/\n\tconst _isDocumentFragment = function _isDocumentFragment(value) {\n\t\tif (!getNodeType || typeof value !== \"object\" || value === null) return false;\n\t\ttry {\n\t\t\treturn getNodeType(value) === NODE_TYPE.documentFragment;\n\t\t} catch (_) {\n\t\t\treturn false;\n\t\t}\n\t};\n\t/**\n\t* Checks whether the given object is a DOM node, including nodes that\n\t* originate from a different window/realm (e.g. an iframe's\n\t* contentDocument). The previous `value instanceof Node` check was\n\t* realm-bound: nodes from a different window failed it, causing\n\t* sanitize() to silently stringify them and reset IN_PLACE to false,\n\t* returning the original node unsanitized. See GHSA-4w3q-35jp-p934.\n\t*\n\t* @param value object to check whether it's a DOM node\n\t* @return true if value is a DOM node from any realm\n\t*/\n\tconst _isNode = function _isNode(value) {\n\t\tif (!getNodeType || typeof value !== \"object\" || value === null) return false;\n\t\ttry {\n\t\t\treturn typeof getNodeType(value) === \"number\";\n\t\t} catch (_) {\n\t\t\treturn false;\n\t\t}\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* @return true if the node must be removed\n\t*/\n\tconst _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {\n\t\tif (SAFE_FOR_XML && 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 && currentNode.namespaceURI === HTML_NAMESPACE && LITERAL_TEXT_ELEMENTS[tagName] && (_isNode(currentNode.firstElementChild) || typeof currentNode.textContent === \"string\" && regExpTest(LITERAL_TEXT_CLOSE[tagName], currentNode.textContent))) return true;\n\t\tif (currentNode.nodeType === NODE_TYPE.processingInstruction) return true;\n\t\tif (SAFE_FOR_XML && currentNode.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* Handle a node whose tag is forbidden or not allowlisted: keep\n\t* allowed custom elements (false return exits _sanitizeElements\n\t* early - the namespace and fallback-tag removal checks are\n\t* intentionally skipped for kept custom elements), else hoist\n\t* content per KEEP_CONTENT and remove.\n\t*\n\t* A kept custom element is the ONLY case in which this function\n\t* returns false, so the caller uses that return value to run the\n\t* afterSanitizeElements hook on the kept element and keep the\n\t* element-hook lifecycle consistent with normal allowlisted\n\t* elements (GHSA-c2j3-45gr-mqc4).\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]) {\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* Fork a hook-mutable allowlist off its shared binding the first time a\n\t* (possibly lazily-installed) uponSanitize* hook is about to see it, so the\n\t* hook cannot widen the per-instance default or the setConfig binding by\n\t* reference and leak past the call. Returns the set unchanged once it is\n\t* already call-local, so repeated calls across elements are idempotent.\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 ? clone(set) : set;\n\t};\n\t/**\n\t* Shared guard for a node that a hook has detached from the walk tree,\n\t* used after each element-hook site in _sanitizeElements. Detaching is a\n\t* long-standing user pattern (issue #469; draw.io-style foreignObject\n\t* filtering). Per the cached, unclobberable parentNode getter the node is\n\t* genuinely out of the tree, so it can reach neither the serialized\n\t* output nor an IN_PLACE live tree; treat it as removed and stop\n\t* processing it. Without this guard, the unsafe-node / namespace checks\n\t* would call _forceRemove on a parentless node and hit the REPORT-3\n\t* fail-closed throw — which exists for nodes DOMPurify wants gone but\n\t* *cannot* detach (clobbered / parentless roots), the opposite of a node\n\t* that is already safely gone. The walk root is exempt: a detached\n\t* IN_PLACE root is legitimate input and must still be fully sanitized,\n\t* and a kill-decision on it must keep hitting the REPORT-3 throw.\n\t*\n\t* Nodes detached by hooks stay the hook's responsibility for placement:\n\t* they are not recorded in DOMPurify.removed, so the post-walk IN_PLACE\n\t* pass (which iterates DOMPurify.removed) does not reach them. But a\n\t* hook-detached subtree can still hold a queued resource-event handler -\n\t* e.g. an <img onload> that began loading when the caller built the live\n\t* tree - which fires in page scope after sanitize returns even though the\n\t* handler never reached the returned tree. That is the audit-5 F1 hazard,\n\t* and the documented node.remove() hook pattern walks straight into it.\n\t* So on the IN_PLACE path we neutralize the detached subtree inline,\n\t* stripping its non-allow-listed attributes before returning, exactly as\n\t* the post-walk pass does for _forceRemove'd subtrees.\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 is detached and now handled, false otherwise\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_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\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)) {\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 (_readNodeType(currentNode) === 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 && currentNode.nodeType === NODE_TYPE.text) {\n\t\t\tconst content = _stripTemplateExpressions(currentNode.textContent);\n\t\t\tif (currentNode.textContent !== 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\tif (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, \"\"))) 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, stringReplace(value, ATTR_WHITESPACE$1, \"\"))) 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* Write a modified attribute value back onto the element. On\n\t* success, re-probe for clobbering introduced by the new value and\n\t* remove the element when found; otherwise, when this writeback is the\n\t* recreate half of the SANITIZE_NAMED_PROPS remove-and-recreate, pop the\n\t* removal entry that path recorded so it does not show as removed. On\n\t* failure, remove the attribute instead.\n\t*\n\t* Returns true only on a clean write (the value was set and the new value\n\t* introduced no clobbering). The caller uses that, together with its own\n\t* knowledge of whether this attribute pushed a DOMPurify.removed record, to\n\t* decide whether to pop that record. The pop must happen ONLY for the\n\t* named-prop remove-and-recreate; popping on any other value change (trim,\n\t* template scrubbing, Trusted Types) would consume an unrelated _forceRemove\n\t* subtree-cleanup record and let that detached subtree keep a live event\n\t* handler through the IN_PLACE neutralization pass (SO-001).\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* _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(currentNode.nodeName);\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 (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {\n\t\t\t\t_removeAttribute(name, currentNode, attr);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (lcName === \"attributename\" && stringMatch(value, \"href\")) {\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* _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_sanitizeElements(shadowNode, fragment);\n\t\t\t_sanitizeAttributes(shadowNode, fragment);\n\t\t\tif (_isDocumentFragment(shadowNode.content)) _sanitizeShadowDOM2(shadowNode.content);\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\t_executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n\t};\n\t/**\n\t* _sanitizeAttachedShadowRoots\n\t*\n\t* Walks `root` and feeds every attached shadow root we encounter into\n\t* the existing _sanitizeShadowDOM pipeline. The default node iterator\n\t* does not descend into shadow trees, so nodes inside an attached\n\t* shadow root would otherwise be skipped entirely.\n\t*\n\t* Two real input paths put attached shadow roots in front of us:\n\t*   1. IN_PLACE on a DOM node that already has shadow roots attached.\n\t*   2. DOM-node input where importNode(dirty, true) deep-clones the\n\t*      shadow root because it was created with `clonable: true`.\n\t*\n\t* This pass runs once, up front, so the main iteration loop (and the\n\t* existing _sanitizeShadowDOM template-content recursion) stay\n\t* untouched — string-input paths are not affected.\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\tif (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) ALLOWED_TAGS = clone(ALLOWED_TAGS);\n\t\tif (hooks.uponSanitizeAttribute.length > 0) ALLOWED_ATTR = clone(ALLOWED_ATTR);\n\t\tDOMPurify.removed = [];\n\t\tconst inPlace = IN_PLACE && typeof dirty !== \"string\" && _isNode(dirty);\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\ttry {\n\t\t\t\t_sanitizeAttachedShadowRoots(dirty);\n\t\t\t} catch (error) {\n\t\t\t\t_neutralizeRoot(dirty);\n\t\t\t\tthrow error;\n\t\t\t}\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 trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : 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\tconst nodeIterator = _createNodeIterator(walkRoot);\n\t\t\twhile (currentNode = nodeIterator.nextNode()) {\n\t\t\t\t_sanitizeElements(currentNode, walkRoot);\n\t\t\t\t_sanitizeAttributes(currentNode, walkRoot);\n\t\t\t\tif (_isDocumentFragment(currentNode.content)) _sanitizeShadowDOM2(currentNode.content);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (inPlace) {\n\t\t\t\t_neutralizeRoot(dirty);\n\t\t\t\tarrayForEach(DOMPurify.removed, (entry) => {\n\t\t\t\t\tif (entry.element) _neutralizeSubtree(entry.element);\n\t\t\t\t});\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (inPlace) {\n\t\t\tlet rootWasRemoved = false;\n\t\t\tarrayForEach(DOMPurify.removed, (entry) => {\n\t\t\t\tif (entry.element) {\n\t\t\t\t\tif (entry.element === dirty) rootWasRemoved = true;\n\t\t\t\t\t_neutralizeSubtree(entry.element);\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (rootWasRemoved) 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\tlet serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\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\tif (SAFE_FOR_TEMPLATES) serializedHTML = _stripTemplateExpressions(serializedHTML);\n\t\treturn trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : 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\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.1.0 - 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 I(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var P=I();function W(l){P=l}var A={exec:()=>null};function C(l){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l(n),e[n]=s),s}}function h(l,e=\"\"){let t=typeof l==\"string\"?l:l.source,n={replace:(s,r)=>{let o=typeof r==\"string\"?r:r.source;return o=o.replace(x.caret,\"$1\"),t=t.replace(s,o),n},getRegex:()=>new RegExp(t,e)};return n}var _e=((l=\"\")=>{try{return!!new RegExp(\"(?<=1)(?<!1)\"+l)}catch{return!1}})(),x={codeRemoveIndent:/^(?: {0,3}\\t| {1,4})/gm,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}((?:=+|-+) *)(?=\\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \\t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\\[[ xX]\\] +\\S/,listReplaceTask:/^\\[[ xX]\\] +/,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}));/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:C(l=>new RegExp(`^ {0,${l}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \t][^\\\\n]*)?(?:\\\\n|$))`)),hrRegex:C(l=>new RegExp(`^ {0,${l}}((?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\\\\*[ \t]*){3,})(?:\\\\n+|$)`)),fencesBeginRegex:C(l=>new RegExp(`^ {0,${l}}(?:\\`\\`\\`|~~~)`)),headingBeginRegex:C(l=>new RegExp(`^ {0,${l}}#`)),htmlBeginRegex:C(l=>new RegExp(`^ {0,${l}}(?:</?(?:${N})(?: +|$|/?>)|<(?:script|pre|style|textarea|!--))`,\"i\")),blockquoteBeginRegex:C(l=>new RegExp(`^ {0,${l}}>`))},$e=/^(?:[ \\t]*(?:\\n|$))+/,Le=/^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/,ze=/^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/,G=/^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/,Ae=/^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,J=/ {0,3}(?:[*+-]|\\d{1,9}[.)])/,he=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |fences|blockquote|heading|hr|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,de=h(he).replace(/bull/g,J).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(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/\\|table/g,\"\").getRegex(),Ee=h(he).replace(/bull/g,J).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(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/table/g,/ {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/).getRegex(),V=/^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \\t]+\\n)[^\\n]+)*)/,Me=/^[^\\n]+/,Y=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/,Ie=h(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace(\"label\",Y).replace(\"title\",/(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/).getRegex(),Ce=h(/^(bull)([ \\t][^\\n]*?)?(?:\\n|$)/).replace(/bull/g,J).getRegex(),N=\"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\",ee=/<!--(?:-?>|[\\s\\S]*?(?:-->|$))/,Be=h(\"^ {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)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|<(?!script|pre|style|textarea)([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|</(?!script|pre|style|textarea)[a-z][a-z0-9-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$))\",\"i\").replace(\"comment\",ee).replace(\"tag\",N).replace(\"attribute\",/ +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/).getRegex(),ke=l=>h(V).replace(\"hr\",G).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\",\"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",N).getRegex(),De=ke(/ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/),qe=ke(/ {0,3}(?:[*+-]|\\d{1,9}[.)])(?:[ \\t]|\\n|$)/),ve=h(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/).replace(\"paragraph\",qe).getRegex(),te={blockquote:ve,code:Le,def:Ie,fences:ze,heading:Ae,hr:G,html:Be,lheading:de,list:Ce,newline:$e,paragraph:De,table:A,text:Me},ue=h(\"^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)\").replace(\"hr\",G).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\",\"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",N).getRegex(),Ze={...te,lheading:Ee,table:ue,paragraph:h(V).replace(\"hr\",G).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\",\"\").replace(\"table\",ue).replace(\"blockquote\",\" {0,3}>\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*(?:\\\\n|$))|~~~)[^\\\\n]*(?:\\\\n|$)\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)])[ \\\\t]+[^ \\\\t\\\\n]\").replace(\"html\",\"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",N).getRegex()},He={...te,html:h(`^ *(?:comment *(?:\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\\\s[^'\"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))`).replace(\"comment\",ee).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:A,lheading:/^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,paragraph:h(V).replace(\"hr\",G).replace(\"heading\",` *#{1,6} *[^\n]`).replace(\"lheading\",de).replace(\"|table\",\"\").replace(\"blockquote\",\" {0,3}>\").replace(\"|fences\",\"\").replace(\"|list\",\"\").replace(\"|html\",\"\").replace(\"|tag\",\"\").getRegex()},Ge=/^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,Ne=/^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,ge=/^( {2,}|\\\\)\\n(?!\\s*$)[ \\t]*/,Qe=/^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/,$=/[\\p{P}\\p{S}]/u,B=/[\\s\\p{P}\\p{S}]/u,Q=/[^\\s\\p{P}\\p{S}]/u,je=h(/^((?![*_])punctSpace)/,\"u\").replace(/punctSpace/g,B).getRegex(),Fe=/[\\p{Pi}\\p{Ps}\"']/u,fe=/(?!~)[\\p{P}\\p{S}]/u,Ue=/(?!~)[\\s\\p{P}\\p{S}]/u,Ke=/(?:[^\\s\\p{P}\\p{S}]|~)/u,We=h(/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(),me=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/,Xe=h(me,\"u\").replace(/punct/g,$).getRegex(),Je=h(me,\"u\").replace(/punct/g,fe).getRegex(),Ve=/^(?:\\*+(?:((?!\\*)(?!openQuote)punct)|([^\\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\\s_]))?/,Ye=h(Ve,\"u\").replace(/openQuote/g,Fe).replace(/punct/g,$).getRegex(),xe=\"^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)\",et=h(xe,\"gu\").replace(/notPunctSpace/g,Q).replace(/punctSpace/g,B).replace(/punct/g,$).getRegex(),tt=h(xe,\"gu\").replace(/notPunctSpace/g,Ke).replace(/punctSpace/g,Ue).replace(/punct/g,fe).getRegex(),nt=\"^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)[\\\\s](\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|(?:(?!\\\\*)punct|notPunctSpace)(\\\\*+)(?!\\\\*)(?=notPunctSpace)\",rt=h(nt,\"gu\").replace(/notPunctSpace/g,Q).replace(/punctSpace/g,B).replace(/punct/g,$).getRegex(),st=h(\"^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)\",\"gu\").replace(/notPunctSpace/g,Q).replace(/punctSpace/g,B).replace(/punct/g,$).getRegex(),it=\"^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\\\s](_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)\",ot=h(it,\"gu\").replace(/notPunctSpace/g,Q).replace(/punctSpace/g,B).replace(/punct/g,$).getRegex(),at=h(/^~~?(?:((?!~)punct)|[^\\s~])/,\"u\").replace(/punct/g,$).getRegex(),lt=\"^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)\",ut=h(lt,\"gu\").replace(/notPunctSpace/g,Q).replace(/punctSpace/g,B).replace(/punct/g,$).getRegex(),pt=h(/\\\\(punct)/,\"gu\").replace(/punct/g,$).getRegex(),ct=h(/^<(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(),ht=h(ee).replace(\"(?:-->|$)\",\"-->\").getRegex(),dt=h(\"^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\",ht).replace(\"attribute\",/\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/).getRegex(),be=/\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]/,U=h(/(?:\\[(?:brackets|\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/).replace(\"brackets\",be).getRegex(),kt=h(/^!?\\[(label)\\]\\([ \\t\\n]*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?[ \\t\\n]*\\)/).replace(\"label\",U).replace(\"href\",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]+|(?=\\))/).replace(\"title\",/\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex(),gt=h(/^!?\\[(label)\\]\\[(ref)\\]/).replace(\"label\",U).replace(\"ref\",Y).getRegex(),ft=h(/^!?\\[(ref)\\](?:\\[\\])?/).replace(\"ref\",Y).getRegex(),pe=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\]){1,999}/,mt=h(/(?:[^\\[\\]\\\\`]*(?:\\[(?:brackets|\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\]))){0,999}?[^\\[\\]\\\\`]*?/).replace(\"brackets\",be).getRegex(),xt=h(\"reflink|nolink(?!\\\\()\",\"g\").replace(\"reflink\",h(/^!?\\[(label)\\]\\[(ref)\\]/).replace(\"label\",mt).replace(\"ref\",pe).getRegex()).replace(\"nolink\",h(/^!?\\[(ref)\\](?:\\[\\])?/).replace(\"ref\",pe).getRegex()).getRegex(),ce=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,bt=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\\w-])/,Rt=h(/(?:mailto:email|xmpp:email(?:\\/[A-Za-z0-9@.]+)?)/).replace(/email/g,bt).getRegex(),ne={_backpedal:A,anyPunctuation:pt,autolink:ct,blockSkip:We,br:ge,code:Ne,del:A,delLDelim:A,delRDelim:A,emStrongLDelim:Xe,emStrongRDelimAst:et,emStrongRDelimUnd:st,escape:Ge,link:kt,nolink:ft,punctuation:je,reflink:gt,reflinkSearch:xt,tag:dt,text:Qe,url:A},Tt={...ne,emStrongLDelim:Ye,emStrongRDelimAst:rt,emStrongRDelimUnd:ot,link:h(/^!?\\[(label)\\]\\((.*?)\\)/).replace(\"label\",U).getRegex(),reflink:h(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace(\"label\",U).getRegex()},X={...ne,emStrongRDelimAst:tt,emStrongLDelim:Je,delLDelim:at,delRDelim:ut,url:h(/^emailProtocol|^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace(\"emailProtocol\",Rt).replace(\"protocol\",ce).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:h(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@))))/).replace(\"protocol\",ce).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},Ot={...X,br:h(ge).replace(\"{2,}\",\"*\").getRegex(),text:h(X.text).replace(\"\\\\b_\",\"\\\\b_| {2,}\\\\n\").replace(/\\{2,\\}/g,\"*\").getRegex()},j={normal:te,gfm:Ze,pedantic:He},D={normal:ne,gfm:X,breaks:Ot,pedantic:Tt};var wt={\"&\":\"&amp;\",\"<\":\"&lt;\",\">\":\"&gt;\",'\"':\"&quot;\",\"'\":\"&#39;\"},Re=l=>wt[l];function O(l,e){if(e){if(x.escapeTest.test(l))return l.replace(x.escapeReplace,Re)}else if(x.escapeTestNoEncode.test(l))return l.replace(x.escapeReplaceNoEncode,Re);return l}function Te(l){return l.replace(x.numericCharacterReference,(e,t,n)=>{let s=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return s===0||s>1114111||s>=55296&&s<=57343?\"\\uFFFD\":String.fromCodePoint(s)})}function re(l){try{l=encodeURI(l).replace(x.percentDecode,\"%\")}catch{return null}return l}function se(l,e){let t=l.replace(x.findPipe,(r,o,i)=>{let u=!1,a=o;for(;--a>=0&&i[a]===\"\\\\\";)u=!u;return u?\"|\":\" |\"}),n=t.split(x.splitPipe),s=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(;s<n.length;s++)n[s]=n[s].trim().replace(x.slashPipe,\"|\");return n}function L(l,e,t){let n=l.length;if(n===0)return\"\";let s=0;for(;s<n;){let r=l.charAt(n-s-1);if(r===e&&!t)s++;else if(r!==e&&t)s++;else break}return l.slice(0,n-s)}function ie(l){let e=l.split(`\n`),t=e.length-1;for(;t>=0&&x.blankLine.test(e[t]);)t--;return e.length-t<=2?l:e.slice(0,t+1).join(`\n`)}function q(l){return l.trim().toLowerCase().toUpperCase().toLowerCase()}function oe(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}function ae(l,e=0){let t=e,n=\"\";for(let s of l)if(s===\"\t\"){let r=4-t%4;n+=\" \".repeat(r),t+=r}else n+=s,t++;return n}function Oe(l,e,t,n,s){let r=e.href,o=e.title||null,i=l[1].replace(s.other.outputLinkReplace,\"$1\"),u=l[0].charAt(0)===\"!\";n.state.inLink=!0;let a=n.state.linkEmitted,p=n.state.inRawBlock;n.state.linkEmitted=!1;let c=n.inlineTokens(i),d=n.state.linkEmitted;if(n.state.linkEmitted=a,n.state.inLink=!1,!u){if(d){n.state.inRawBlock=p;return}n.state.linkEmitted=!0}return{type:u?\"image\":\"link\",raw:t,href:r,title:o,text:i,tokens:c}}function Pt(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(`\n`).map(r=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[i]=o;return r.slice(Math.min(i.length,s.length))}).join(`\n`)}function we(l,e,t,n){if(!e.includes(\"<\"))return!1;for(let s=0;s<e.length;s++){if(e[s]===\"\\\\\"){s++;continue}if(e[s]===\"`\"){let i=n.inline.code.exec(e.slice(s));if(i){s+=i[0].length-1;continue}}if(e[s]!==\"<\")continue;let r=l.slice(t+s),o=n.inline.tag.exec(r)||n.inline.autolink.exec(r);if(o){if(o[0].length>e.length-s)return!0;s+=o[0].length-1}}return!1}var y=class{options;rules;lexer;constructor(e){this.options=e||P}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]:ie(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,\"\");return{type:\"code\",raw:n,codeBlockStyle:\"indented\",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=Pt(n,t[3]||\"\",this.rules);return{type:\"code\",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,\"$1\"):t[2],text:s}}}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 s=L(n,\"#\");(this.options.pedantic||!s||this.rules.other.endingSpaceTabChar.test(s))&&(n=s.trim())}return{type:\"heading\",raw:L(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:L(t[0],`\n`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=L(t[0],`\n`).split(`\n`),s=\"\",r=\"\",o=[];for(;n.length>0;){let i=!1,u=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))u.push(n[a]),i=!0;else if(!i)u.push(n[a]);else break;n=n.slice(a);let p=u.join(`\n`),c=p.replace(this.rules.other.blockquoteSetextReplace,`\n    $1`).replace(this.rules.other.blockquoteSetextReplace2,\"\");s=s?`${s}\n${p}`:p,r=r?`${r}\n${c}`:c;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,o,!0),this.lexer.state.top=d,n.length===0)break;let m=o.at(-1);if(m?.type===\"code\")break;if(m?.type===\"blockquote\"){let b=m,g=n.join(`\n`),w=b.raw+`\n`+g.replace(this.rules.other.blockquoteSetextReplace2,\"\"),f=this.blockquote(w);o[o.length-1]=f;let M=w.substring(f.raw.length).replace(/^\\n/,\"\"),v=M?M.split(`\n`).length:0,Z=v?n.slice(0,-v):n;Z.length>0&&(s=`${s}\n${Z.join(`\n`)}`),r=r.substring(0,r.length-b.text.length)+f.text;break}else if(m?.type===\"list\"){let b=m,g=b.raw+`\n`+n.join(`\n`),w=this.list(g);o[o.length-1]=w,s=s.substring(0,s.length-m.raw.length)+w.raw,r=r.substring(0,r.length-b.raw.length)+w.raw,n=g.substring(o.at(-1).raw.length).split(`\n`);continue}}return{type:\"blockquote\",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,r={type:\"list\",raw:\"\",ordered:s,start:s?+n.slice(0,-1):\"\",loose:!1,items:[]};n=s?`\\\\d{1,9}\\\\${n.slice(-1)}`:`\\\\${n}`,this.options.pedantic&&(n=s?n:\"[*+-]\");let o=this.rules.other.listItemRegex(n),i=!1;for(;e;){let a=!1,p=\"\",c=\"\";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let d=t[2].split(`\n`,1)[0],m=t[1].length,b=this.options.pedantic?ae(d,m):d.replace(this.rules.other.leadingSpaceTab,M=>ae(M,m)),g=e.split(`\n`,1)[0],w=!b.trim(),f=0;if(this.options.pedantic?(f=2,c=b.trimStart()):w?f=m+1:(f=b.search(this.rules.other.nonSpaceChar),f=f>4?1:f,c=b.slice(f),f+=m),w&&this.rules.other.blankLine.test(g)&&(p+=g+`\n`,e=e.substring(g.length+1),a=!0),!a){let M=this.rules.other.nextBulletRegex(f),v=this.rules.other.hrRegex(f),Z=this.rules.other.fencesBeginRegex(f),le=this.rules.other.headingBeginRegex(f),Pe=this.rules.other.htmlBeginRegex(f),ye=this.rules.other.blockquoteBeginRegex(f);for(;e;){let K=e.split(`\n`,1)[0],H;if(g=K,this.options.pedantic?(g=g.replace(this.rules.other.listReplaceNesting,\"  \"),H=g):H=g.replace(this.rules.other.leadingSpaceTab,Se=>Se.replace(this.rules.other.tabCharGlobal,\"    \")),Z.test(g)||le.test(g)||Pe.test(g)||ye.test(g)||M.test(g)||v.test(g))break;if(H.search(this.rules.other.nonSpaceChar)>=f||!g.trim())c+=`\n`+H.slice(f);else{if(w||b.replace(this.rules.other.tabCharGlobal,\"    \").search(this.rules.other.nonSpaceChar)>=4||Z.test(b)||le.test(b)||v.test(b))break;c+=`\n`+g}w=!g.trim(),p+=K+`\n`,e=e.substring(K.length+1),b=H.slice(f)}}r.loose||(i?r.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(i=!0)),r.items.push({type:\"list_item\",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(c),loose:!1,text:c,tokens:[]}),r.raw+=p}let u=r.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items)if(this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]),!r.loose){let p=a.tokens.filter(d=>d.type===\"space\"),c=p.length>0&&p.some(d=>this.rules.other.anyLine.test(d.raw));r.loose=c}for(let a of r.items){let p=a.tokens[0];if(a.task&&(p?.type===\"text\"||p?.type===\"paragraph\")){a.text=a.text.replace(this.rules.other.listReplaceTask,\"\"),p.raw=p.raw.replace(this.rules.other.listReplaceTask,\"\"),p.text=p.text.replace(this.rules.other.listReplaceTask,\"\");for(let d=this.lexer.inlineQueue.length-1;d>=0;d--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[d].src)){this.lexer.inlineQueue[d].src=this.lexer.inlineQueue[d].src.replace(this.rules.other.listReplaceTask,\"\");break}let c=this.rules.other.listTaskCheckbox.exec(a.raw);if(c){let d={type:\"checkbox\",raw:c[0]+\" \",checked:c[0]!==\"[ ]\"};a.checked=d.checked,r.loose?a.tokens[0]&&[\"paragraph\",\"text\"].includes(a.tokens[0].type)&&\"tokens\"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=d.raw+a.tokens[0].raw,a.tokens[0].text=d.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(d)):a.tokens.unshift({type:\"paragraph\",raw:d.raw,text:d.raw,tokens:[d]}):a.tokens.unshift(d)}}else a.task&&(a.task=!1)}if(r.loose)for(let a of r.items){a.loose=!0;for(let p of a.tokens)p.type===\"text\"&&(p.type=\"paragraph\")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ie(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])&&oe(t[2],\"()\")!==-1)return;let n=q(t[1]).replace(this.rules.other.multipleSpaceGlobal,\" \"),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,\"$1\").replace(this.rules.inline.anyPunctuation,\"$1\"):\"\",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,\"$1\"):t[3];return{type:\"def\",tag:n,raw:L(t[0],`\n`),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=se(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,\"\").split(\"|\"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,\"\").split(`\n`):[],o={type:\"table\",raw:L(t[0],`\n`),header:[],align:[],rows:[]};if(n.length===s.length){for(let i of s)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 r)o.rows.push(se(i,o.header.length).map((u,a)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:o.align[a]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:\"heading\",raw:L(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){let t=this.rules.inline.escape.exec(e);if(t)return{type:\"escape\",raw:t[0],text:t[1]}}tag(e){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=this.rules.inline.link.exec(e);if(t){let n=t[0].charAt(0)===\"!\"?2:1;if(!this.options.pedantic&&we(e,t[1],n,this.rules))return;let s=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let i=L(s.slice(0,-1),\"\\\\\");if((s.length-i.length)%2===0)return}else{let i=oe(t[2],\"()\");if(i===-2)return;if(i>-1){let a=(t[0].indexOf(\"!\")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,a).trim(),t[3]=\"\"}}let r=t[2],o=\"\";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],o=i[3])}else o=t[3]?t[3].slice(1,-1):\"\";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?r=r.slice(1):r=r.slice(1,-1)),Oe(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,\"$1\"),title:o&&o.replace(this.rules.inline.anyPunctuation,\"$1\")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=n[0].charAt(0)===\"!\"?2:1;if(!this.options.pedantic&&we(e,n[1],s,this.rules))return;let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,\" \"),o=t[q(r)];if(!o){let i=n[0].charAt(0);return{type:\"text\",raw:i,text:i}}return Oe(n,o,n[0],this.lexer,this.rules)}}emStrong(e,t,n=\"\"){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[3]||\"\")||!n||this.rules.inline.punctuation.exec(n)){let o=[...s[0]].length-1,i,u,a=o,p=0,c=s[0][0],d=n===c,m=c===\"*\"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,t=t.slice(-1*e.length+o);(s=m.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i)continue;if(u=[...i].length,s[3]||s[4]){a+=u;continue}else if(s[5]||s[6]){if(o%3&&!((o+u)%3)){p+=u;continue}if(d)break}if(a-=u,a>0)continue;u=Math.min(u,u+a+p);let b=[...s[0]][0].length,g=e.slice(0,o+s.index+b+u);if(Math.min(o,u)%2){let f=g.slice(1,-1);return{type:\"em\",raw:g,text:f,tokens:this.lexer.inlineTokens(f)}}let w=g.slice(2,-2);return{type:\"strong\",raw:g,text:w,tokens:this.lexer.inlineTokens(w)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal,\" \"),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:\"codespan\",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:\"br\",raw:t[0]}}del(e,t,n=\"\"){let s=this.rules.inline.delLDelim.exec(e);if(!s)return;if(!(s[1]||\"\")||!n||this.rules.inline.punctuation.exec(n)){let o=[...s[0]].length-1,i,u,a=o,p=this.rules.inline.delRDelim;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(u=[...i].length,u!==o))continue;if(s[3]||s[4]){a+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a);let c=[...s[0]][0].length,d=e.slice(0,o+s.index+c+u),m=d.slice(o,-o);return{type:\"del\",raw:d,text:m,tokens:this.lexer.inlineTokens(m)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]===\"@\"?(n=t[1],s=\"mailto:\"+n):(n=t[1],s=n),{type:\"link\",raw:t[0],text:n,href:s,autolink:!0,tokens:[{type:\"text\",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]===\"@\")n=t[0],s=\"mailto:\"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??\"\";while(r!==t[0]);n=t[0],t[1]===\"www.\"?s=\"http://\"+t[0]:s=t[0]}return{type:\"link\",raw:t[0],text:n,href:s,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]:Te(t[0]),escaped:n}}}};var R=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||P,this.options.tokenizer=this.options.tokenizer||new y,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:x,block:j.normal,inline:D.normal};this.options.pedantic?(t.block=j.pedantic,t.inline=D.pedantic):this.options.gfm&&(t.block=j.gfm,this.options.breaks?t.inline=D.breaks:t.inline=D.gfm),this.tokenizer.rules=t}static get rules(){return{block:j,inline:D}}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(x.carriageReturn,`\n`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(x.tabCharGlobal,\"    \").replace(x.spaceLine,\"\"));let s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(i=>(r=i.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let i=t.at(-1);r.raw.length===1&&i!==void 0?i.raw+=`\n`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type===\"paragraph\"||i?.type===\"text\"?(i.raw+=(i.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,i.text+=`\n`+r.text,this.inlineQueue.at(-1).src=i.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type===\"paragraph\"||i?.type===\"text\"?(i.raw+=(i.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,i.text+=`\n`+r.raw,this.inlineQueue.at(-1).src=i.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let o=e;if(this.options.extensions?.startBlock){let i=1/0,u=e.slice(1),a;this.options.extensions.startBlock.forEach(p=>{a=p.call({lexer:this},u),typeof a==\"number\"&&a>=0&&(i=Math.min(i,a))}),i<1/0&&i>=0&&(o=e.substring(0,i+1))}if(this.state.top&&(r=this.tokenizer.paragraph(o))){let i=t.at(-1);n&&i?.type===\"paragraph\"?(i.raw+=(i.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,i.text+=`\n`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(r),n=o.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type===\"text\"?(i.raw+=(i.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,i.text+=`\n`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,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 s=n[0],r=s.lastIndexOf(\"[\");if(!(s.charAt(0)===\"!\"||!Object.hasOwn(this.tokens.links,q(s.slice(r+1,-1))))&&!(r>1&&this.linkInText(s.slice(1,r-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=n&&e.includes(\")\");try{return this.#e(e,t)}finally{this.state.linkParenPossible=n}}#e(e,t){let n=e;if(this.tokens.links&&e.includes(\"[\")){let i=this.tokenizer.rules.inline.reflinkSearch,u=a=>{let p=a.lastIndexOf(\"[\");if(!Object.hasOwn(this.tokens.links,q(a.slice(p+1,-1))))return a;if(p>1&&a.charAt(0)!==\"!\"){let c=a.slice(1,p-1);if(this.linkInText(c))return\"[\"+c.replace(i,u)+\"][\"+\"a\".repeat(a.length-p-2)+\"]\"}return\"[\"+\"a\".repeat(a.length-2)+\"]\"};n=n.replace(i,u)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,i=>\"+\".repeat(i.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(i,u,a)=>{let p=a?a.length:0;return i.slice(0,p)+\"[\"+\"a\".repeat(i.length-p-2)+\"]\"}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let s=!1,r=\"\",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}s||(r=\"\"),s=!1;let i;if(this.options.extensions?.inline?.some(a=>(i=a.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length);let a=t.at(-1);i.type===\"text\"&&a?.type===\"text\"?(a.raw+=i.raw,a.text+=i.text):t.push(i);continue}if(i=this.tokenizer.emStrong(e,n,r)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.del(e,n,r)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.autolink(e)){e=e.substring(i.raw.length),t.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e))){e=e.substring(i.raw.length),t.push(i);continue}let u=e;if(this.options.extensions?.startInline){let a=1/0,p=e.slice(1),c;this.options.extensions.startInline.forEach(d=>{c=d.call({lexer:this},p),typeof c==\"number\"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(u=e.substring(0,a+1))}if(i=this.tokenizer.inlineText(u)){e=e.substring(i.raw.length),i.raw.slice(-1)!==\"_\"&&(r=i.raw.slice(-1)),s=!0;let a=t.at(-1);a?.type===\"text\"?(a.raw+=i.raw,a.text+=i.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=\"Infinite loop on byte: \"+e;if(this.options.silent)console.error(t);else throw new Error(t)}};var S=class{options;parser;constructor(e){this.options=e||P}space(e){return\"\"}code({text:e,lang:t,escaped:n}){let s=(t||\"\").match(x.notSpaceStart)?.[0],r=e?e.replace(x.endingNewline,\"\")+`\n`:\"\";return s?'<pre><code class=\"language-'+O(s)+'\">'+(n?r:O(r,!0))+`</code></pre>\n`:\"<pre><code>\"+(n?r:O(r,!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,s=\"\";for(let i=0;i<e.items.length;i++){let u=e.items[i];s+=this.listitem(u)}let r=t?\"ol\":\"ul\",o=t&&n!==1?' start=\"'+n+'\"':\"\";return\"<\"+r+o+`>\n`+s+\"</\"+r+`>\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 r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let s=\"\";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];n=\"\";for(let i=0;i<o.length;i++)n+=this.tablecell(o[i]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>\n<thead>\n`+t+`</thead>\n`+s+`</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>${O(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:s,autolink:r}){let o=r?O(n,!0):this.parser.parseInline(s),i=re(e);if(i===null)return o;e=O(i,r);let u='<a href=\"'+e+'\"';return t&&(u+=' title=\"'+O(t)+'\"'),u+=\">\"+o+\"</a>\",u}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=re(e);if(r===null)return O(n);e=r;let o=`<img src=\"${O(e)}\" alt=\"${O(n)}\"`;return t&&(o+=` title=\"${O(t)}\"`),o+=\">\",o}text(e){return\"tokens\"in e&&e.tokens?this.parser.parseInline(e.tokens):\"escaped\"in e&&e.escaped?e.text:O(e.text)}};var z=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return\"\"+e}image({text:e}){return\"\"+e}br(){return\"\"}checkbox({raw:e}){return e}};var T=class l{options;renderer;textRenderer;constructor(e){this.options=e||P,this.options.renderer=this.options.renderer||new S,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new z}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 s=e[n];if(this.options.extensions?.renderers?.[s.type]){let o=s,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||\"\";continue}}let r=s;switch(r.type){case\"space\":{t+=this.renderer.space(r);break}case\"hr\":{t+=this.renderer.hr(r);break}case\"heading\":{t+=this.renderer.heading(r);break}case\"code\":{t+=this.renderer.code(r);break}case\"table\":{t+=this.renderer.table(r);break}case\"blockquote\":{t+=this.renderer.blockquote(r);break}case\"list\":{t+=this.renderer.list(r);break}case\"checkbox\":{t+=this.renderer.checkbox(r);break}case\"html\":{t+=this.renderer.html(r);break}case\"def\":{t+=this.renderer.def(r);break}case\"paragraph\":{t+=this.renderer.paragraph(r);break}case\"text\":{t+=this.renderer.text(r);break}default:{let o='Token with \"'+r.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 s=0;s<e.length;s++){let r=e[s];if(this.options.extensions?.renderers?.[r.type]){let i=this.options.extensions.renderers[r.type].call({parser:this},r);if(i!==!1||![\"escape\",\"html\",\"link\",\"image\",\"checkbox\",\"strong\",\"em\",\"codespan\",\"br\",\"del\",\"text\"].includes(r.type)){n+=i||\"\";continue}}let o=r;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 _=class{options;block;constructor(e){this.options=e||P}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?R.lex:R.lexInline}provideParser(e=this.block){return e?T.parse:T.parseInline}};var F=class{defaults=I();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=T;Renderer=S;TextRenderer=z;Lexer=R;Tokenizer=y;Hooks=_;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case\"table\":{let r=s;for(let o of r.header)n=n.concat(this.walkTokens(o.tokens,t));for(let o of r.rows)for(let i of o)n=n.concat(this.walkTokens(i.tokens,t));break}case\"list\":{let r=s;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let i=r[o].flat(1/0);n=n.concat(this.walkTokens(i,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error(\"extension name required\");if(\"renderer\"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...i){let u=r.renderer.apply(this,i);return u===!1&&(u=o.apply(this,i)),u}:t.renderers[r.name]=r.renderer}if(\"tokenizer\"in r){if(!r.level||r.level!==\"block\"&&r.level!==\"inline\")throw new Error(\"extension level must be 'block' or 'inline'\");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level===\"block\"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level===\"inline\"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}\"childTokens\"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new S(this.defaults);for(let o in n.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if([\"options\",\"parser\"].includes(o))continue;let i=o,u=n.renderer[i],a=r[i];r[i]=(...p)=>{let c=u.apply(r,p);return c===!1&&(c=a.apply(r,p)),c||\"\"}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new y(this.defaults);for(let o in n.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if([\"options\",\"rules\",\"lexer\"].includes(o))continue;let i=o,u=n.tokenizer[i],a=r[i];r[i]=(...p)=>{let c=u.apply(r,p);return c===!1&&(c=a.apply(r,p)),c}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new _;for(let o in n.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if([\"options\",\"block\"].includes(o))continue;let i=o,u=n.hooks[i],a=r[i];_.passThroughHooks.has(o)?r[i]=p=>{if(this.defaults.async&&_.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await u.call(r,p);return a.call(r,d)})();let c=u.call(r,p);return a.call(r,c)}:r[i]=(...p)=>{if(this.defaults.async)return(async()=>{let d=await u.apply(r,p);return d===!1&&(d=await a.apply(r,p)),d})();let c=u.apply(r,p);return c===!1&&(c=a.apply(r,p)),c}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,o=n.walkTokens;s.walkTokens=function(i){let u=[];return u.push(o.call(this,i)),r&&(u=u.concat(r.call(this,i))),u}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return R.lex(e,t??this.defaults)}parser(e,t){return T.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let r={...s},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.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 u=o.hooks?await o.hooks.preprocess(n):n,p=await(o.hooks?await o.hooks.provideLexer(e):e?R.lex:R.lexInline)(u,o),c=o.hooks?await o.hooks.processAllTokens(p):p;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let m=await(o.hooks?await o.hooks.provideParser(e):e?T.parse:T.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(m):m})().catch(i);try{o.hooks&&(n=o.hooks.preprocess(n));let a=(o.hooks?o.hooks.provideLexer(e):e?R.lex:R.lexInline)(n,o);o.hooks&&(a=o.hooks.processAllTokens(a)),o.walkTokens&&this.walkTokens(a,o.walkTokens);let c=(o.hooks?o.hooks.provideParser(e):e?T.parse:T.parseInline)(a,o);return o.hooks&&(c=o.hooks.postprocess(c)),c}catch(u){return i(u)}}}onError(e,t){return n=>{if(n.message+=`\nPlease report this to https://github.com/markedjs/marked.`,e){let s=\"<p>An error occurred:</p><pre>\"+O(n.message+\"\",!0)+\"</pre>\";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var E=new F;function k(l,e){return E.parse(l,e)}k.options=k.setOptions=function(l){return E.setOptions(l),k.defaults=E.defaults,W(k.defaults),k};k.getDefaults=I;k.defaults=P;function yt(...l){return E.use(...l),k.defaults=E.defaults,W(k.defaults),k}k.use=yt;k.walkTokens=function(l,e){return E.walkTokens(l,e)};k.parseInline=E.parseInline;k.Parser=T;k.parser=T.parse;k.Renderer=S;k.TextRenderer=z;k.Lexer=R;k.lexer=R.lex;k.Tokenizer=y;k.Hooks=_;k.parse=k;var gn=k.options,fn=k.setOptions,mn=k.walkTokens,xn=k.parseInline,bn=k,Rn=T.parse,Tn=R.lex;export{_ as Hooks,R as Lexer,F as Marked,T as Parser,S as Renderer,z as TextRenderer,y as Tokenizer,P as defaults,I as getDefaults,Tn as lexer,k as marked,gn as options,bn as parse,xn as parseInline,Rn as parser,fn as setOptions,yt as use,mn as walkTokens};\n//# sourceMappingURL=marked.esm.js.map\n","/**\n * Global property the main bundle shares its React instance on, for the `react-dom` chunk. Kept in\n * a module without dependencies, as it’s imported by the build configuration as well as the app, so\n * the two sides can’t drift apart.\n */\nexport const SHARED_REACT_KEY = '__SVELTIA_CMS_REACT__';\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","// Store the references to globals in case someone tries to monkey patch these, causing the below\n// to de-opt (this occurs often when using popular extensions).\nexport var is_array = Array.isArray;\nexport var index_of = Array.prototype.indexOf;\nexport var includes = Array.prototype.includes;\nexport var array_from = Array.from;\nexport var object_keys = Object.keys;\nexport var define_property = Object.defineProperty;\nexport var get_descriptor = Object.getOwnPropertyDescriptor;\nexport var get_descriptors = Object.getOwnPropertyDescriptors;\nexport var object_prototype = Object.prototype;\nexport var array_prototype = Array.prototype;\nexport var get_prototype_of = Object.getPrototypeOf;\nexport var is_extensible = Object.isExtensible;\nexport var has_own_property = Object.prototype.hasOwnProperty;\n\n/**\n * @param {any} thing\n * @returns {thing is Function}\n */\nexport function is_function(thing) {\n\treturn typeof thing === 'function';\n}\n\nexport const noop = () => {};\n\n// Adapted from https://github.com/then/is-promise/blob/master/index.js\n// Distributed under MIT License https://github.com/then/is-promise/blob/master/LICENSE\n\n/**\n * @template [T=any]\n * @param {any} value\n * @returns {value is PromiseLike<T>}\n */\nexport function is_promise(value) {\n\treturn typeof value?.then === 'function';\n}\n\n/** @param {Function} fn */\nexport function run(fn) {\n\treturn fn();\n}\n\n/** @param {Array<() => void>} arr */\nexport function run_all(arr) {\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tarr[i]();\n\t}\n}\n\n/**\n * TODO replace with Promise.withResolvers once supported widely enough\n * @template [T=void]\n */\nexport function deferred() {\n\t/** @type {(value: T) => void} */\n\tvar resolve;\n\n\t/** @type {(reason: any) => void} */\n\tvar reject;\n\n\t/** @type {Promise<T>} */\n\tvar promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\t// @ts-expect-error\n\treturn { promise, resolve, reject };\n}\n\n/**\n * @template V\n * @param {V} value\n * @param {V | (() => V)} fallback\n * @param {boolean} [lazy]\n * @returns {V}\n */\nexport function fallback(value, fallback, lazy = false) {\n\treturn value === undefined\n\t\t? lazy\n\t\t\t? /** @type {() => V} */ (fallback)()\n\t\t\t: /** @type {V} */ (fallback)\n\t\t: value;\n}\n\n/**\n * When encountering a situation like `let [a, b, c] = $derived(blah())`,\n * we need to stash an intermediate value that `a`, `b`, and `c` derive\n * from, in case it's an iterable\n * @template T\n * @param {ArrayLike<T> | Iterable<T>} value\n * @param {number} [n]\n * @returns {Array<T>}\n */\nexport function to_array(value, n) {\n\t// return arrays unchanged\n\tif (Array.isArray(value)) {\n\t\treturn value;\n\t}\n\n\t// if value is not iterable, or `n` is unspecified (indicates a rest\n\t// element, which means we're not concerned about unbounded iterables)\n\t// convert to an array with `Array.from`\n\tif (n === undefined || !(Symbol.iterator in value)) {\n\t\treturn Array.from(value);\n\t}\n\n\t// otherwise, populate an array with `n` values\n\n\t/** @type {T[]} */\n\tconst array = [];\n\n\tfor (const element of value) {\n\t\tarray.push(element);\n\t\tif (array.length === n) break;\n\t}\n\n\treturn array;\n}\n\n/**\n * @param {Record<string | symbol, unknown>} obj\n * @param {Array<string | symbol>} keys\n * @returns {Record<string | symbol, unknown>}\n */\nexport function exclude_from_object(obj, keys) {\n\t/** @type {Record<string | symbol, unknown>} */\n\tvar result = {};\n\n\tfor (var key in obj) {\n\t\tif (!keys.includes(key)) {\n\t\t\tresult[key] = obj[key];\n\t\t}\n\t}\n\n\tfor (var symbol of Object.getOwnPropertySymbols(obj)) {\n\t\tif (Object.propertyIsEnumerable.call(obj, symbol) && !keys.includes(symbol)) {\n\t\t\tresult[symbol] = obj[symbol];\n\t\t}\n\t}\n\n\treturn result;\n}\n","// General flags\nexport const DERIVED = 1 << 1;\nexport const EFFECT = 1 << 2;\nexport const RENDER_EFFECT = 1 << 3;\n/**\n * An effect that does not destroy its child effects when it reruns.\n * Runs as part of render effects, i.e. not eagerly as part of tree traversal or effect flushing.\n */\nexport const MANAGED_EFFECT = 1 << 24;\n/**\n * An effect that does not destroy its child effects when it reruns (like MANAGED_EFFECT).\n * Runs eagerly as part of tree traversal or effect flushing.\n */\nexport const BLOCK_EFFECT = 1 << 4;\nexport const BRANCH_EFFECT = 1 << 5;\nexport const ROOT_EFFECT = 1 << 6;\nexport const BOUNDARY_EFFECT = 1 << 7;\n/**\n * 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\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","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\n/**\n * Whitespace inside one of these elements will not result in\n * a whitespace node being created in any circumstances. (This\n * list is almost certainly very incomplete)\n * TODO this is currently unused\n */\nexport const ELEMENTS_WITHOUT_TEXT = ['audio', 'datalist', 'dl', 'optgroup', 'select', 'video'];\n\nexport const ATTACHMENT_KEY = '@attach';\n","/* 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} from '../../../constants.js';\nimport * as w from '../warnings.js';\nimport { get_next_sibling } from './operations.js';\n\n/**\n * Use this variable to guard everything related to hydration code so it can be treeshaken out\n * if the user doesn't use the `hydrate` method and these code paths are therefore not needed.\n */\nexport let hydrating = false;\n\n/** @param {boolean} value */\nexport function set_hydrating(value) {\n\thydrating = value;\n}\n\n/**\n * The node that is currently being hydrated. This starts out as the first node inside the opening\n * <!--[--> comment, and updates each time a component calls `$.child(...)` or `$.sibling(...)`.\n * When entering a block (e.g. `{#if ...}`), `hydrate_node` is the block opening comment; by the\n * time we leave the block it is the closing comment, which serves as the block's anchor.\n * @type {TemplateNode}\n */\nexport let hydrate_node;\n\n/** @param {TemplateNode | null} node */\nexport function set_hydrate_node(node) {\n\tif (node === null) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\treturn (hydrate_node = node);\n}\n\nexport function hydrate_next() {\n\treturn set_hydrate_node(get_next_sibling(hydrate_node));\n}\n\n/** @param {TemplateNode} node */\nexport function reset(node) {\n\tif (!hydrating) return;\n\n\t// If the node has remaining siblings, something has gone wrong\n\tif (get_next_sibling(hydrate_node) !== null) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\thydrate_node = node;\n}\n\n/**\n * @param {HTMLTemplateElement} template\n */\nexport function hydrate_template(template) {\n\tif (hydrating) {\n\t\t// @ts-expect-error TemplateNode doesn't include DocumentFragment, but it's actually fine\n\t\thydrate_node = template.content;\n\t}\n}\n\nexport function next(count = 1) {\n\tif (hydrating) {\n\t\tvar i = count;\n\t\tvar node = hydrate_node;\n\n\t\twhile (i--) {\n\t\t\tnode = /** @type {TemplateNode} */ (get_next_sibling(node));\n\t\t}\n\n\t\thydrate_node = node;\n\t}\n}\n\n/**\n * Skips or removes (depending on {@link remove}) all nodes starting at `hydrate_node` up until the next hydration end comment\n * @param {boolean} remove\n */\nexport function skip_nodes(remove = true) {\n\tvar depth = 0;\n\tvar node = hydrate_node;\n\n\twhile (true) {\n\t\tif (node.nodeType === COMMENT_NODE) {\n\t\t\tvar data = /** @type {Comment} */ (node).data;\n\n\t\t\tif (data === HYDRATION_END) {\n\t\t\t\tif (depth === 0) return node;\n\t\t\t\tdepth -= 1;\n\t\t\t} else if (\n\t\t\t\tdata === HYDRATION_START ||\n\t\t\t\tdata === HYDRATION_START_ELSE ||\n\t\t\t\t// \"[1\", \"[2\", etc. for if blocks\n\t\t\t\t(data[0] === '[' && !isNaN(Number(data.slice(1))))\n\t\t\t) {\n\t\t\t\tdepth += 1;\n\t\t\t}\n\t\t}\n\n\t\tvar next = /** @type {TemplateNode} */ (get_next_sibling(node));\n\t\tif (remove) node.remove();\n\t\tnode = next;\n\t}\n}\n\n/**\n *\n * @param {TemplateNode} node\n */\nexport function read_hydration_instruction(node) {\n\tif (!node || node.nodeType !== COMMENT_NODE) {\n\t\tw.hydration_mismatch();\n\t\tthrow HYDRATION_ERROR;\n\t}\n\n\treturn /** @type {Comment} */ (node).data;\n}\n","/** @import { Equals } from '#client' */\n\n/** @type {Equals} */\nexport function equals(value) {\n\treturn value === this.v;\n}\n\n/**\n * @param {unknown} a\n * @param {unknown} b\n * @returns {boolean}\n */\nexport function safe_not_equal(a, b) {\n\treturn a != a\n\t\t? b == b\n\t\t: a !== b || (a !== null && typeof a === 'object') || typeof a === 'function';\n}\n\n/**\n * @param {unknown} a\n * @param {unknown} b\n * @returns {boolean}\n */\nexport function not_equal(a, b) {\n\treturn a !== b;\n}\n\n/** @type {Equals} */\nexport function safe_equals(value) {\n\treturn !safe_not_equal(value, this.v);\n}\n","/* This file is generated by scripts/process-messages/index.js. Do not edit! */\n\nimport { DEV } from 'esm-env';\n\n/**\n * Cannot use `%name%(...)` unless the `experimental.async` compiler option is `true`\n * @param {string} name\n * @returns {never}\n */\nexport function experimental_async_required(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`experimental_async_required\\nCannot use \\`${name}(...)\\` unless the \\`experimental.async\\` compiler option is \\`true\\`\\nhttps://svelte.dev/e/experimental_async_required`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/experimental_async_required`);\n\t}\n}\n\n/**\n * Cannot use `{@render children(...)}` if the parent component uses `let:` directives. Consider using a named snippet instead\n * @returns {never}\n */\nexport function invalid_default_snippet() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_default_snippet\\nCannot use \\`{@render children(...)}\\` if the parent component uses \\`let:\\` directives. Consider using a named snippet instead\\nhttps://svelte.dev/e/invalid_default_snippet`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invalid_default_snippet`);\n\t}\n}\n\n/**\n * A snippet function was passed invalid arguments. Snippets should only be instantiated via `{@render ...}`\n * @returns {never}\n */\nexport function invalid_snippet_arguments() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_snippet_arguments\\nA snippet function was passed invalid arguments. Snippets should only be instantiated via \\`{@render ...}\\`\\nhttps://svelte.dev/e/invalid_snippet_arguments`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invalid_snippet_arguments`);\n\t}\n}\n\n/**\n * An invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: \"%message%\"\n * @param {string} message\n * @returns {never}\n */\nexport function invariant_violation(message) {\n\tif (DEV) {\n\t\tconst error = new Error(`invariant_violation\\nAn invariant violation occurred, meaning Svelte's internal assumptions were flawed. This is a bug in Svelte, not your app — please open an issue at https://github.com/sveltejs/svelte, citing the following message: \"${message}\"\\nhttps://svelte.dev/e/invariant_violation`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invariant_violation`);\n\t}\n}\n\n/**\n * `%name%(...)` can only be used during component initialisation\n * @param {string} name\n * @returns {never}\n */\nexport function lifecycle_outside_component(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`lifecycle_outside_component\\n\\`${name}(...)\\` can only be used during component initialisation\\nhttps://svelte.dev/e/lifecycle_outside_component`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/lifecycle_outside_component`);\n\t}\n}\n\n/**\n * Context was not set in 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 * Cannot create a `$derived(...)` with an `await` expression outside of an effect tree\n * @returns {never}\n */\nexport function async_derived_orphan() {\n\tif (DEV) {\n\t\tconst error = new Error(`async_derived_orphan\\nCannot create a \\`$derived(...)\\` with an \\`await\\` expression outside of an effect tree\\nhttps://svelte.dev/e/async_derived_orphan`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/async_derived_orphan`);\n\t}\n}\n\n/**\n * Using `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\n * @returns {never}\n */\nexport function bind_invalid_checkbox_value() {\n\tif (DEV) {\n\t\tconst error = new Error(`bind_invalid_checkbox_value\\nUsing \\`bind:value\\` together with a checkbox input is not allowed. Use \\`bind:checked\\` instead\\nhttps://svelte.dev/e/bind_invalid_checkbox_value`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/bind_invalid_checkbox_value`);\n\t}\n}\n\n/**\n * Component %component% has an export named `%key%` that a consumer component is trying to access using `bind:%key%`, which is disallowed. Instead, use `bind:this` (e.g. `<%name% bind:this={component} />`) and then access the property on the bound component instance (e.g. `component.%key%`)\n * @param {string} component\n * @param {string} key\n * @param {string} name\n * @returns {never}\n */\nexport function bind_invalid_export(component, key, name) {\n\tif (DEV) {\n\t\tconst error = new Error(`bind_invalid_export\\nComponent ${component} has an export named \\`${key}\\` that a consumer component is trying to access using \\`bind:${key}\\`, which is disallowed. Instead, use \\`bind:this\\` (e.g. \\`<${name} bind:this={component} />\\`) and then access the property on the bound component instance (e.g. \\`component.${key}\\`)\\nhttps://svelte.dev/e/bind_invalid_export`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/bind_invalid_export`);\n\t}\n}\n\n/**\n * A component is attempting to bind to a non-bindable property `%key%` belonging to %component% (i.e. `<%name% bind:%key%={...}>`). To mark a property as bindable: `let { %key% = $bindable() } = $props()`\n * @param {string} key\n * @param {string} component\n * @param {string} name\n * @returns {never}\n */\nexport function bind_not_bindable(key, component, name) {\n\tif (DEV) {\n\t\tconst error = new Error(`bind_not_bindable\\nA component is attempting to bind to a non-bindable property \\`${key}\\` belonging to ${component} (i.e. \\`<${name} bind:${key}={...}>\\`). To mark a property as bindable: \\`let { ${key} = $bindable() } = $props()\\`\\nhttps://svelte.dev/e/bind_not_bindable`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/bind_not_bindable`);\n\t}\n}\n\n/**\n * Calling `%method%` on a component instance (of %component%) is no longer valid in Svelte 5\n * @param {string} method\n * @param {string} component\n * @returns {never}\n */\nexport function component_api_changed(method, component) {\n\tif (DEV) {\n\t\tconst error = new Error(`component_api_changed\\nCalling \\`${method}\\` on a component instance (of ${component}) is no longer valid in Svelte 5\\nhttps://svelte.dev/e/component_api_changed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/component_api_changed`);\n\t}\n}\n\n/**\n * Attempted to instantiate %component% with `new %name%`, which is no longer valid in Svelte 5. If this component is not under your control, set the `compatibility.componentApi` compiler option to `4` to keep it working.\n * @param {string} component\n * @param {string} name\n * @returns {never}\n */\nexport function component_api_invalid_new(component, name) {\n\tif (DEV) {\n\t\tconst error = new Error(`component_api_invalid_new\\nAttempted to instantiate ${component} with \\`new ${name}\\`, which is no longer valid in Svelte 5. If this component is not under your control, set the \\`compatibility.componentApi\\` compiler option to \\`4\\` to keep it working.\\nhttps://svelte.dev/e/component_api_invalid_new`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/component_api_invalid_new`);\n\t}\n}\n\n/**\n * A derived value cannot reference itself recursively\n * @returns {never}\n */\nexport function derived_references_self() {\n\tif (DEV) {\n\t\tconst error = new Error(`derived_references_self\\nA derived value cannot reference itself recursively\\nhttps://svelte.dev/e/derived_references_self`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/derived_references_self`);\n\t}\n}\n\n/**\n * Keyed each block has duplicate key `%value%` at indexes %a% and %b%\n * @param {string} a\n * @param {string} b\n * @param {string | undefined | null} [value]\n * @returns {never}\n */\nexport function each_key_duplicate(a, b, value) {\n\tif (DEV) {\n\t\tconst error = new Error(`each_key_duplicate\\n${value\n\t\t\t? `Keyed each block has duplicate key \\`${value}\\` at indexes ${a} and ${b}`\n\t\t\t: `Keyed each block has duplicate key at indexes ${a} and ${b}`}\\nhttps://svelte.dev/e/each_key_duplicate`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/each_key_duplicate`);\n\t}\n}\n\n/**\n * Keyed each block has key that is not idempotent — the key for item at index %index% was `%a%` but is now `%b%`. Keys must be the same each time for a given item\n * @param {string} index\n * @param {string} a\n * @param {string} b\n * @returns {never}\n */\nexport function each_key_volatile(index, a, b) {\n\tif (DEV) {\n\t\tconst error = new Error(`each_key_volatile\\nKeyed each block has key that is not idempotent — the key for item at index ${index} was \\`${a}\\` but is now \\`${b}\\`. Keys must be the same each time for a given item\\nhttps://svelte.dev/e/each_key_volatile`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/each_key_volatile`);\n\t}\n}\n\n/**\n * `%rune%` cannot be used inside an effect cleanup function\n * @param {string} rune\n * @returns {never}\n */\nexport function effect_in_teardown(rune) {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_in_teardown\\n\\`${rune}\\` cannot be used inside an effect cleanup function\\nhttps://svelte.dev/e/effect_in_teardown`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_in_teardown`);\n\t}\n}\n\n/**\n * Effect cannot be created inside a `$derived` value that was not itself created inside an effect\n * @returns {never}\n */\nexport function effect_in_unowned_derived() {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_in_unowned_derived\\nEffect cannot be created inside a \\`$derived\\` value that was not itself created inside an effect\\nhttps://svelte.dev/e/effect_in_unowned_derived`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_in_unowned_derived`);\n\t}\n}\n\n/**\n * `%rune%` can only be used inside an effect (e.g. during component initialisation)\n * @param {string} rune\n * @returns {never}\n */\nexport function effect_orphan(rune) {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_orphan\\n\\`${rune}\\` can only be used inside an effect (e.g. during component initialisation)\\nhttps://svelte.dev/e/effect_orphan`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_orphan`);\n\t}\n}\n\n/**\n * `$effect.pending()` can only be called inside an effect or derived\n * @returns {never}\n */\nexport function effect_pending_outside_reaction() {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_pending_outside_reaction\\n\\`$effect.pending()\\` can only be called inside an effect or derived\\nhttps://svelte.dev/e/effect_pending_outside_reaction`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_pending_outside_reaction`);\n\t}\n}\n\n/**\n * Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state\n * @returns {never}\n */\nexport function effect_update_depth_exceeded() {\n\tif (DEV) {\n\t\tconst error = new Error(`effect_update_depth_exceeded\\nMaximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state\\nhttps://svelte.dev/e/effect_update_depth_exceeded`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);\n\t}\n}\n\n/**\n * Cannot use `flushSync` inside an effect\n * @returns {never}\n */\nexport function flush_sync_in_effect() {\n\tif (DEV) {\n\t\tconst error = new Error(`flush_sync_in_effect\\nCannot use \\`flushSync\\` inside an effect\\nhttps://svelte.dev/e/flush_sync_in_effect`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/flush_sync_in_effect`);\n\t}\n}\n\n/**\n * Cannot commit a fork that was already discarded\n * @returns {never}\n */\nexport function fork_discarded() {\n\tif (DEV) {\n\t\tconst error = new Error(`fork_discarded\\nCannot commit a fork that was already discarded\\nhttps://svelte.dev/e/fork_discarded`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/fork_discarded`);\n\t}\n}\n\n/**\n * Cannot create a fork inside an effect or when state changes are pending\n * @returns {never}\n */\nexport function fork_timing() {\n\tif (DEV) {\n\t\tconst error = new Error(`fork_timing\\nCannot create a fork inside an effect or when state changes are pending\\nhttps://svelte.dev/e/fork_timing`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/fork_timing`);\n\t}\n}\n\n/**\n * `getAbortSignal()` can only be called inside an effect or derived\n * @returns {never}\n */\nexport function get_abort_signal_outside_reaction() {\n\tif (DEV) {\n\t\tconst error = new Error(`get_abort_signal_outside_reaction\\n\\`getAbortSignal()\\` can only be called inside an effect or derived\\nhttps://svelte.dev/e/get_abort_signal_outside_reaction`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/get_abort_signal_outside_reaction`);\n\t}\n}\n\n/**\n * Expected to find a hydratable with key `%key%` during hydration, but did not.\n * @param {string} key\n * @returns {never}\n */\nexport function hydratable_missing_but_required(key) {\n\tif (DEV) {\n\t\tconst error = new Error(`hydratable_missing_but_required\\nExpected to find a hydratable with key \\`${key}\\` during hydration, but did not.\\nhttps://svelte.dev/e/hydratable_missing_but_required`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/hydratable_missing_but_required`);\n\t}\n}\n\n/**\n * Failed to hydrate the application\n * @returns {never}\n */\nexport function hydration_failed() {\n\tif (DEV) {\n\t\tconst error = new Error(`hydration_failed\\nFailed to hydrate the application\\nhttps://svelte.dev/e/hydration_failed`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/hydration_failed`);\n\t}\n}\n\n/**\n * Could not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`\n * @returns {never}\n */\nexport function invalid_snippet() {\n\tif (DEV) {\n\t\tconst error = new Error(`invalid_snippet\\nCould not \\`{@render}\\` snippet due to the expression being \\`null\\` or \\`undefined\\`. Consider using optional chaining \\`{@render snippet?.()}\\`\\nhttps://svelte.dev/e/invalid_snippet`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/invalid_snippet`);\n\t}\n}\n\n/**\n * `%name%(...)` cannot be used in runes mode\n * @param {string} name\n * @returns {never}\n */\nexport function lifecycle_legacy_only(name) {\n\tif (DEV) {\n\t\tconst error = new Error(`lifecycle_legacy_only\\n\\`${name}(...)\\` cannot be used in runes mode\\nhttps://svelte.dev/e/lifecycle_legacy_only`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/lifecycle_legacy_only`);\n\t}\n}\n\n/**\n * Cannot do `bind:%key%={undefined}` when `%key%` has a fallback value\n * @param {string} key\n * @returns {never}\n */\nexport function props_invalid_value(key) {\n\tif (DEV) {\n\t\tconst error = new Error(`props_invalid_value\\nCannot do \\`bind:${key}={undefined}\\` when \\`${key}\\` has a fallback value\\nhttps://svelte.dev/e/props_invalid_value`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/props_invalid_value`);\n\t}\n}\n\n/**\n * Rest element properties of `$props()` such as `%property%` are readonly\n * @param {string} property\n * @returns {never}\n */\nexport function props_rest_readonly(property) {\n\tif (DEV) {\n\t\tconst error = new Error(`props_rest_readonly\\nRest element properties of \\`$props()\\` such as \\`${property}\\` are readonly\\nhttps://svelte.dev/e/props_rest_readonly`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/props_rest_readonly`);\n\t}\n}\n\n/**\n * The `%rune%` rune is only available inside `.svelte` and `.svelte.js/ts` files\n * @param {string} rune\n * @returns {never}\n */\nexport function rune_outside_svelte(rune) {\n\tif (DEV) {\n\t\tconst error = new Error(`rune_outside_svelte\\nThe \\`${rune}\\` rune is only available inside \\`.svelte\\` and \\`.svelte.js/ts\\` files\\nhttps://svelte.dev/e/rune_outside_svelte`);\n\n\t\terror.name = 'Svelte error';\n\n\t\tthrow error;\n\t} else {\n\t\tthrow new Error(`https://svelte.dev/e/rune_outside_svelte`);\n\t}\n}\n\n/**\n * 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 { 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 { 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.deps === null) {\n\t\tset_signal_status(derived, CLEAN);\n\t} else {\n\t\tset_signal_status(derived, MAYBE_DIRTY);\n\t}\n}\n","/** @import { Effect } from '#client' */\nimport { CLEAN, DIRTY, MAYBE_DIRTY } from '#client/constants';\nimport { set_signal_status } from './status.js';\n\n/**\n * @param {Effect} effect\n * @param {Set<Effect>} dirty_effects\n * @param {Set<Effect>} maybe_dirty_effects\n */\nexport function defer_effect(effect, dirty_effects, maybe_dirty_effects) {\n\tif ((effect.f & DIRTY) !== 0) {\n\t\tdirty_effects.add(effect);\n\t} else if ((effect.f & MAYBE_DIRTY) !== 0) {\n\t\tmaybe_dirty_effects.add(effect);\n\t}\n\n\t// mark as clean so they get scheduled if they depend on pending async state\n\tset_signal_status(effect, CLEAN);\n}\n","import { hydrating } from '../hydration.js';\nimport { clear_text_content, get_first_child } 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\tdocument.addEventListener(\n\t\t\t'reset',\n\t\t\t(evt) => {\n\t\t\t\t// Needs to happen one tick later or else the dom properties of the form\n\t\t\t\t// elements have not updated to their reset values yet\n\t\t\t\tPromise.resolve().then(() => {\n\t\t\t\t\tif (!evt.defaultPrevented) {\n\t\t\t\t\t\tfor (const e of /**@type {HTMLFormElement} */ (evt.target).elements) {\n\t\t\t\t\t\t\t/** @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 { Blocker, Effect, Source, Value } from '#client' */\nimport { DESTROYED, STALE_REACTION } from '#client/constants';\nimport { DEV } from 'esm-env';\nimport {\n\tcomponent_context,\n\tdev_stack,\n\tis_runes,\n\tset_component_context,\n\tset_dev_stack\n} from '../context.js';\nimport { invoke_error_boundary } from '../error-handling.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tset_active_effect,\n\tset_active_reaction\n} from '../runtime.js';\nimport { Batch, current_batch } from './batch.js';\nimport {\n\tasync_derived,\n\treactivity_loss_tracker,\n\tderived,\n\tderived_safe_equal,\n\tset_reactivity_loss_tracker\n} from './deriveds.js';\nimport { aborted } from './effects.js';\n\n/**\n * @param {Blocker[]} blockers\n * @param {Array<() => any>} sync\n * @param {Array<() => Promise<any>>} async\n * @param {(values: Value[]) => any} fn\n */\nexport function flatten(blockers, sync, async, fn) {\n\tconst d = is_runes() ? derived : derived_safe_equal;\n\n\t// Filter out already-settled blockers - no need to wait for them\n\tvar pending = blockers.filter((b) => !b.settled);\n\n\tvar deriveds = sync.map(d);\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\tif (async.length === 0 && pending.length === 0) {\n\t\tfn(deriveds);\n\t\treturn;\n\t}\n\n\tvar parent = /** @type {Effect} */ (active_effect);\n\n\tvar restore = capture();\n\tvar blocker_promise =\n\t\tpending.length === 1\n\t\t\t? pending[0].promise\n\t\t\t: pending.length > 1\n\t\t\t\t? Promise.all(pending.map((b) => b.promise))\n\t\t\t\t: null;\n\n\t/**\n\t * @param {Source[]} async\n\t */\n\tfunction finish(async) {\n\t\tif ((parent.f & DESTROYED) !== 0) {\n\t\t\treturn;\n\t\t}\n\n\t\trestore();\n\n\t\ttry {\n\t\t\tfn([...deriveds, ...async]);\n\t\t} catch (error) {\n\t\t\tinvoke_error_boundary(error, parent);\n\t\t}\n\n\t\tunset_context();\n\t}\n\n\tvar decrement_pending = increment_pending();\n\n\t// Fast path: blockers but no async expressions\n\tif (async.length === 0) {\n\t\t/** @type {Promise<any>} */ (blocker_promise).then(() => finish([])).finally(decrement_pending);\n\t\treturn;\n\t}\n\n\t// Full path: has async expressions\n\tfunction run() {\n\t\tPromise.all(async.map((expression) => async_derived(expression)))\n\t\t\t.then(finish)\n\t\t\t.catch((error) => invoke_error_boundary(error, parent))\n\t\t\t.finally(decrement_pending);\n\t}\n\n\tif (blocker_promise) {\n\t\tblocker_promise.then(() => {\n\t\t\tif ((parent.f & DESTROYED) !== 0) {\n\t\t\t\tdecrement_pending();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\trestore();\n\t\t\trun();\n\t\t\tunset_context();\n\t\t});\n\t} else {\n\t\trun();\n\t}\n}\n\n/**\n * @param {Blocker[]} blockers\n * @param {(values: Value[]) => any} fn\n */\nexport function run_after_blockers(blockers, fn) {\n\tflatten(blockers, [], [], fn);\n}\n\n/**\n * Captures the current effect context so that we can restore it after\n * some asynchronous work has happened (so that e.g. `await a + b`\n * causes `b` to be registered as a dependency).\n */\nexport function capture() {\n\tvar previous_effect = /** @type {Effect} */ (active_effect);\n\tvar previous_reaction = active_reaction;\n\tvar previous_component_context = component_context;\n\tvar previous_batch = /** @type {Batch} */ (current_batch);\n\n\tif (DEV) {\n\t\tvar previous_dev_stack = dev_stack;\n\t}\n\n\treturn function restore(activate_batch = true) {\n\t\tset_active_effect(previous_effect);\n\t\tset_active_reaction(previous_reaction);\n\t\tset_component_context(previous_component_context);\n\n\t\tif (activate_batch && (previous_effect.f & DESTROYED) === 0) {\n\t\t\t// TODO we only need optional chaining here because `{#await ...}` blocks\n\t\t\t// are anomalous. Once we retire them we can get rid of it\n\t\t\tprevious_batch?.activate();\n\t\t\tprevious_batch?.apply();\n\t\t}\n\n\t\tif (DEV) {\n\t\t\tset_reactivity_loss_tracker(null);\n\t\t\tset_dev_stack(previous_dev_stack);\n\t\t}\n\t};\n}\n\n/** `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 (deactivate_batch) current_batch?.deactivate();\n\n\tif (DEV) {\n\t\tset_reactivity_loss_tracker(null);\n\t\tset_dev_stack(null);\n\t}\n}\n\n/**\n * @param {Array<() => void | Promise<void>>} thunks\n */\nexport function run(thunks) {\n\tconst restore = capture();\n\n\tconst decrement_pending = increment_pending();\n\n\tvar active = /** @type {Effect} */ (active_effect);\n\n\t/** @type {null | { error: any }} */\n\tvar errored = null;\n\n\t/** @param {any} error */\n\tconst handle_error = (error) => {\n\t\terrored = { error }; // wrap in object in case a promise rejects with a falsy value\n\n\t\tif (!aborted(active)) {\n\t\t\tinvoke_error_boundary(error, active);\n\t\t}\n\t};\n\n\tvar promise = Promise.resolve(thunks[0]()).catch(handle_error);\n\n\t/** @type {Blocker} */\n\tvar blocker = { promise, settled: false };\n\tvar blockers = [blocker];\n\n\tpromise.finally(() => {\n\t\tblocker.settled = true;\n\t\tunset_context();\n\t});\n\n\tfor (const fn of thunks.slice(1)) {\n\t\tpromise = promise\n\t\t\t.then(() => {\n\t\t\t\trestore();\n\n\t\t\t\ttry {\n\t\t\t\t\tif (errored) {\n\t\t\t\t\t\tthrow errored.error;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (aborted(active)) {\n\t\t\t\t\t\tthrow STALE_REACTION;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn 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}\n\t\t\t})\n\t\t\t.catch(handle_error);\n\n\t\tconst blocker = { promise, settled: false };\n\t\tblockers.push(blocker);\n\n\t\tpromise.finally(() => {\n\t\t\tblocker.settled = true;\n\t\t\t// ... but we also need it after such a promise has resolved in case it restores our context\n\t\t\tunset_context();\n\t\t});\n\t}\n\n\tpromise\n\t\t// wait one more tick, so that template effects are\n\t\t// guaranteed to run before `$effect(...)`\n\t\t.then(() => Promise.resolve())\n\t\t.finally(decrement_pending);\n\n\treturn blockers;\n}\n\n/**\n * @param {Blocker[]} blockers\n */\nexport function wait(blockers) {\n\treturn Promise.all(blockers.map((b) => b.promise));\n}\n\n/**\n * @returns {(skip?: boolean) => void}\n */\nexport function increment_pending() {\n\tvar effect = /** @type {Effect} */ (active_effect);\n\tvar boundary = effect.b; // undefined if called outside the render tree, e.g. a standalone $effect.root\n\tvar batch = /** @type {Batch} */ (current_batch);\n\tvar blocking = !!boundary?.is_rendered();\n\n\tboundary?.update_pending_count(1, batch);\n\tbatch.increment(blocking, effect);\n\n\treturn () => {\n\t\tboundary?.update_pending_count(-1, batch);\n\t\tbatch.decrement(blocking, effect);\n\t};\n}\n","/** @import { Derived, Effect, Reaction, Source, Value } from '#client' */\n/** @import { Batch } from './batch.js'; */\n/** @import { Boundary } from '../dom/blocks/boundary.js'; */\nimport { DEV } from 'esm-env';\nimport {\n\tERROR_VALUE,\n\tDERIVED,\n\tDIRTY,\n\tEFFECT_PRESERVED,\n\tSTALE_REACTION,\n\tASYNC,\n\tDESTROYED,\n\tCLEAN,\n\tREACTION_RAN,\n\tINERT\n} from '#client/constants';\nimport {\n\tactive_reaction,\n\tactive_effect,\n\tupdate_reaction,\n\tincrement_write_version,\n\tset_active_effect,\n\tpush_reaction_value,\n\tis_destroying_effect,\n\tupdate_effect,\n\tremove_reactions,\n\tskipped_deps,\n\tnew_deps\n} from '../runtime.js';\nimport { without_reactive_context } from '../dom/elements/bindings/shared.js';\nimport { equals, safe_equals } from './equality.js';\nimport * as e from '../errors.js';\nimport * as w from '../warnings.js';\nimport {\n\tasync_effect,\n\tdestroy_effect,\n\tdestroy_effect_children,\n\teffect_tracking,\n\tteardown\n} from './effects.js';\nimport { eager_effects, internal_set, set_eager_effects, source } from './sources.js';\nimport { get_error } from '../../shared/dev.js';\nimport { async_mode_flag, tracing_mode_flag } from '../../flags/index.js';\nimport { component_context } from '../context.js';\nimport { UNINITIALIZED } from '../../../constants.js';\nimport { batch_values, current_batch, previous_batch } from './batch.js';\nimport { increment_pending, unset_context } from './async.js';\nimport { deferred, includes, noop } from '../../shared/utils.js';\nimport { set_signal_status, update_derived_status } from './status.js';\n\n/**\n * This allows us to track 'reactivity loss' that occurs when signals\n * are read after a non-context-restoring `await`. Dev-only\n * @type {{ effect: Effect, effect_deps: Set<Value>, warned: boolean } | null}\n */\nexport let reactivity_loss_tracker = null;\n\n/** @param {{ effect: Effect, effect_deps: Set<Value>, warned: boolean } | null} v */\nexport function set_reactivity_loss_tracker(v) {\n\treactivity_loss_tracker = v;\n}\n\nexport const recent_async_deriveds = new Set();\n\n/**\n * @template V\n * @param {() => V} fn\n * @returns {Derived<V>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function derived(fn) {\n\tvar flags = DERIVED | DIRTY;\n\n\tif (active_effect !== null) {\n\t\t// Since deriveds are evaluated lazily, any effects created inside them are\n\t\t// created too late to ensure that the parent effect is added to the tree\n\t\tactive_effect.f |= EFFECT_PRESERVED;\n\t}\n\n\t/** @type {Derived<V>} */\n\tconst signal = {\n\t\tctx: component_context,\n\t\tdeps: null,\n\t\teffects: null,\n\t\tequals,\n\t\tf: flags,\n\t\tfn,\n\t\treactions: null,\n\t\trv: 0,\n\t\tv: /** @type {V} */ (UNINITIALIZED),\n\t\twv: 0,\n\t\tparent: active_effect,\n\t\tac: null\n\t};\n\n\tif (DEV && tracing_mode_flag) {\n\t\tsignal.created = get_error('created at');\n\t}\n\n\treturn signal;\n}\n\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 * @returns {Promise<Source<V>>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function async_derived(fn, label, location) {\n\tlet parent = /** @type {Effect | null} */ (active_effect);\n\n\tif (parent === null) {\n\t\te.async_derived_orphan();\n\t}\n\n\tvar promise = /** @type {Promise<V>} */ (/** @type {unknown} */ (undefined));\n\tvar signal = source(/** @type {V} */ (UNINITIALIZED));\n\n\tif (DEV) signal.label = label ?? fn.toString();\n\n\t// only suspend in async deriveds created on initialisation\n\tvar should_suspend = !active_reaction;\n\n\t/** @type {Set<ReturnType<typeof deferred<V>>>} */\n\tvar deferreds = new Set();\n\n\tasync_effect(() => {\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\tif (DEV) {\n\t\t\treactivity_loss_tracker = { effect, effect_deps: new Set(), warned: false };\n\t\t}\n\n\t\t/** @type {ReturnType<typeof deferred<V>>} */\n\t\tvar d = deferred();\n\t\tpromise = d.promise;\n\n\t\ttry {\n\t\t\t// If this code is changed at some point, make sure to still access the then property\n\t\t\t// of fn() to read any signals it might access, so that we track them as dependencies.\n\t\t\t// We call `unset_context` to undo any `save` calls that happen inside `fn()`\n\t\t\tPromise.resolve(fn())\n\t\t\t\t.then(d.resolve, (e) => {\n\t\t\t\t\t// if the promise was rejected by the user, via `getAbortSignal`, then\n\t\t\t\t\t// wait for a subsequent resolution instead of flushing the batch\n\t\t\t\t\tif (e !== STALE_REACTION) d.reject(e);\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\tunset_context();\n\t\t}\n\n\t\tif (DEV) {\n\t\t\tif (reactivity_loss_tracker) {\n\t\t\t\t// Reused deps from previous run (indices 0 to skipped_deps-1)\n\t\t\t\t// We deliberately only track direct dependencies of the async expression to encourage\n\t\t\t\t// dependencies being directly visible at the point of the expression\n\t\t\t\tif (effect.deps !== null) {\n\t\t\t\t\tfor (let i = 0; i < skipped_deps; i += 1) {\n\t\t\t\t\t\treactivity_loss_tracker.effect_deps.add(effect.deps[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// New deps discovered this run\n\t\t\t\tif (new_deps !== null) {\n\t\t\t\t\tfor (let i = 0; i < new_deps.length; i += 1) {\n\t\t\t\t\t\treactivity_loss_tracker.effect_deps.add(new_deps[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treactivity_loss_tracker = null;\n\t\t}\n\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\n\t\tif (should_suspend) {\n\t\t\t// we only increment the batch's pending state for updates, not creation, otherwise\n\t\t\t// we will decrement to zero before the work that depends on this promise (e.g. a\n\t\t\t// template effect) has initialized, causing the batch to resolve prematurely\n\t\t\tif ((effect.f & REACTION_RAN) !== 0) {\n\t\t\t\tvar decrement_pending = increment_pending();\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\t// boundary can be null if the async derived is inside an $effect.root not connected to the component render tree\n\t\t\t\tparent.b?.is_rendered()\n\t\t\t) {\n\t\t\t\tbatch.async_deriveds.get(effect)?.reject(OBSOLETE);\n\t\t\t} else {\n\t\t\t\t// While the boundary is still showing pending, a new run supersedes all older in-flight runs\n\t\t\t\t// for this async expression. Cancel eagerly so resolution cannot commit stale values.\n\t\t\t\tfor (const d of deferreds.values()) {\n\t\t\t\t\td.reject(OBSOLETE);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tdeferreds.add(d);\n\t\t\tbatch.async_deriveds.set(effect, d);\n\t\t}\n\n\t\t/**\n\t\t * @param {any} value\n\t\t * @param {unknown} error\n\t\t */\n\t\tconst handler = (value, error = undefined) => {\n\t\t\tif (DEV) {\n\t\t\t\treactivity_loss_tracker = null;\n\t\t\t}\n\n\t\t\tdecrement_pending?.();\n\t\t\tdeferreds.delete(d);\n\n\t\t\tif (error === OBSOLETE) return;\n\n\t\t\tbatch.activate();\n\n\t\t\tif (error) {\n\t\t\t\tsignal.f |= ERROR_VALUE;\n\n\t\t\t\t// @ts-expect-error the error is the wrong type, but we don't care\n\t\t\t\tinternal_set(signal, error);\n\t\t\t} else {\n\t\t\t\tif ((signal.f & ERROR_VALUE) !== 0) {\n\t\t\t\t\tsignal.f ^= ERROR_VALUE;\n\t\t\t\t}\n\n\t\t\t\tif (DEV && location !== undefined && !signal.equals(value)) {\n\t\t\t\t\trecent_async_deriveds.add(signal);\n\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tif (recent_async_deriveds.has(signal) && (effect.f & DESTROYED) === 0) {\n\t\t\t\t\t\t\tw.await_waterfall(/** @type {string} */ (signal.label), location);\n\t\t\t\t\t\t\trecent_async_deriveds.delete(signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tinternal_set(signal, value);\n\t\t\t}\n\n\t\t\tbatch.deactivate();\n\t\t};\n\n\t\td.promise.then(handler, (e) => handler(null, e || 'unknown'));\n\t});\n\n\tteardown(() => {\n\t\tfor (const d of deferreds) {\n\t\t\td.reject(OBSOLETE);\n\t\t}\n\t});\n\n\tif (DEV) {\n\t\t// add a flag that lets this be printed as a derived\n\t\t// when using `$inspect.trace()`\n\t\tsignal.f |= ASYNC;\n\t}\n\n\treturn new Promise((fulfil) => {\n\t\t/** @param {Promise<V>} p */\n\t\tfunction next(p) {\n\t\t\tfunction go() {\n\t\t\t\tif (p === promise) {\n\t\t\t\t\tfulfil(signal);\n\t\t\t\t} else {\n\t\t\t\t\t// if the effect re-runs before the initial promise\n\t\t\t\t\t// resolves, delay resolution until we have a value\n\t\t\t\t\tnext(promise);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tp.then(go, go);\n\t\t}\n\n\t\tnext(promise);\n\t});\n}\n\n/**\n * @template V\n * @param {() => V} fn\n * @returns {Derived<V>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function user_derived(fn) {\n\tconst d = derived(fn);\n\n\tif (!async_mode_flag) push_reaction_value(d);\n\n\treturn d;\n}\n\n/**\n * @template V\n * @param {() => V} fn\n * @returns {Derived<V>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function derived_safe_equal(fn) {\n\tconst signal = derived(fn);\n\tsignal.equals = safe_equals;\n\treturn signal;\n}\n\n/**\n * @param {Derived} derived\n * @returns {void}\n */\nexport function destroy_derived_effects(derived) {\n\tvar effects = derived.effects;\n\n\tif (effects !== null) {\n\t\tderived.effects = null;\n\n\t\tfor (var i = 0; i < effects.length; i += 1) {\n\t\t\tdestroy_effect(/** @type {Effect} */ (effects[i]));\n\t\t}\n\t}\n}\n\n/**\n * The currently updating deriveds, used to detect infinite recursion\n * in dev mode and provide a nicer error than 'too much recursion'\n * @type {Derived[]}\n */\nlet stack = [];\n\n/**\n * @template T\n * @param {Derived} derived\n * @returns {T}\n */\nexport function execute_derived(derived) {\n\tvar value;\n\tvar prev_active_effect = active_effect;\n\tvar parent = derived.parent;\n\n\tif (\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\treturn derived.v;\n\t}\n\n\tset_active_effect(parent);\n\n\tif (DEV) {\n\t\tlet prev_eager_effects = eager_effects;\n\t\tset_eager_effects(new Set());\n\t\ttry {\n\t\t\tif (includes.call(stack, derived)) {\n\t\t\t\te.derived_references_self();\n\t\t\t}\n\n\t\t\tstack.push(derived);\n\n\t\t\tdestroy_derived_effects(derived);\n\t\t\tvalue = update_reaction(derived);\n\t\t} finally {\n\t\t\tset_active_effect(prev_active_effect);\n\t\t\tset_eager_effects(prev_eager_effects);\n\t\t\tstack.pop();\n\t\t}\n\t} else {\n\t\ttry {\n\t\t\tdestroy_derived_effects(derived);\n\t\t\tvalue = update_reaction(derived);\n\t\t} finally {\n\t\t\tset_active_effect(prev_active_effect);\n\t\t}\n\t}\n\n\treturn value;\n}\n\n/**\n * @param {Derived} derived\n * @returns {void}\n */\nexport function update_derived(derived) {\n\tvar value = execute_derived(derived);\n\n\tif (!derived.equals(value)) {\n\t\tderived.wv = increment_write_version();\n\n\t\t// in a fork, we don't update the underlying value, just `batch_values`.\n\t\t// the underlying value will be updated when the fork is committed.\n\t\t// otherwise, the next time we get here after a 'real world' state\n\t\t// change, `derived.equals` may incorrectly return `true`\n\t\tif (!current_batch?.is_fork || derived.deps === null) {\n\t\t\tif (current_batch !== null) {\n\t\t\t\t// We also write to previous_batch because if it exists, it is a sign that we're\n\t\t\t\t// currently in the process of flushing effects. These updates to deriveds may belong\n\t\t\t\t// to the previous batch, not the new one (which can already exist if an earlier\n\t\t\t\t// effect wrote to a source). This can cause bugs when running batch.#commit() later,\n\t\t\t\t// but not adding it to current_batch can, too, so we add it to both.\n\t\t\t\t// See https://github.com/sveltejs/svelte/pull/18117 for more details.\n\t\t\t\tcurrent_batch.capture(derived, value, true);\n\t\t\t\tprevious_batch?.capture(derived, value, true);\n\t\t\t} else {\n\t\t\t\tderived.v = value;\n\t\t\t}\n\n\t\t\t// deriveds without dependencies should never be recomputed\n\t\t\tif (derived.deps === null) {\n\t\t\t\tset_signal_status(derived, CLEAN);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\n\t// don't mark derived clean if we're reading it inside a\n\t// cleanup function, or it will cache a stale value\n\tif (is_destroying_effect) {\n\t\treturn;\n\t}\n\n\t// During time traveling we don't want to reset the status so that\n\t// traversal of the graph in the other batches still happens\n\tif (batch_values !== null) {\n\t\t// only cache the value if we're in a tracking context, otherwise we won't\n\t\t// clear the cache in `mark_reactions` when dependencies are updated\n\t\tif (effect_tracking() || current_batch?.is_fork) {\n\t\t\tbatch_values.set(derived, value);\n\t\t}\n\t} else {\n\t\tupdate_derived_status(derived);\n\t}\n}\n\n/**\n * @param {Derived} derived\n */\nexport function freeze_derived_effects(derived) {\n\tif (derived.effects === null) return;\n\n\tfor (const e of derived.effects) {\n\t\t// if the effect has a teardown function or abort signal, call it\n\t\tif (e.teardown || e.ac) {\n\t\t\te.teardown?.();\n\t\t\tif (e.ac !== null) {\n\t\t\t\twithout_reactive_context(() => {\n\t\t\t\t\t/** @type {AbortController} */ (e.ac).abort(STALE_REACTION);\n\t\t\t\t\te.ac = null;\n\t\t\t\t});\n\t\t\t}\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, 0);\n\t\t\tdestroy_effect_children(e);\n\t\t}\n\t}\n}\n\n/**\n * @param {Derived} derived\n */\nexport function unfreeze_derived_effects(derived) {\n\tif (derived.effects === null) return;\n\n\tfor (const e of derived.effects) {\n\t\t// if the effect was previously frozen — indicated by the presence\n\t\t// of a teardown function — unfreeze it\n\t\tif (e.teardown && e.fn !== null) {\n\t\t\tupdate_effect(e);\n\t\t}\n\t}\n}\n","/** @import { Fork } from 'svelte' */\n/** @import { Derived, Effect, Reaction, Source, Value } from '#client' */\nimport {\n\tBLOCK_EFFECT,\n\tBRANCH_EFFECT,\n\tCLEAN,\n\tDESTROYED,\n\tDIRTY,\n\tEFFECT,\n\tASYNC,\n\tINERT,\n\tRENDER_EFFECT,\n\tROOT_EFFECT,\n\tMAYBE_DIRTY,\n\tDERIVED,\n\tEAGER_EFFECT,\n\tERROR_VALUE,\n\tMANAGED_EFFECT,\n\tREACTION_RAN,\n\tDESTROYING\n} from '#client/constants';\nimport { async_mode_flag } from '../../flags/index.js';\nimport { deferred, define_property, includes } from '../../shared/utils.js';\nimport {\n\tactive_reaction,\n\tget,\n\tincrement_write_version,\n\tis_dirty,\n\tupdate_effect\n} from '../runtime.js';\nimport * as e from '../errors.js';\nimport { flush_tasks, queue_micro_task } from '../dom/task.js';\nimport { DEV } from 'esm-env';\nimport { invoke_error_boundary } from '../error-handling.js';\nimport { flush_eager_effects, old_values, set_eager_effects, source, update } from './sources.js';\nimport { eager_effect, teardown, unlink_effect } from './effects.js';\nimport { defer_effect } from './utils.js';\nimport { UNINITIALIZED } from '../../../constants.js';\nimport { set_signal_status } from './status.js';\nimport { invariant } from '../../shared/dev.js';\nimport { log_effect_tree } from '../dev/debug.js';\nimport { OBSOLETE } from './deriveds.js';\n\n/** @type {Batch | null} */\nlet 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 * This is needed to avoid overwriting inputs\n * @type {Batch | null}\n */\nexport let previous_batch = null;\n\n/**\n * When time travelling (i.e. working in one batch, while other batches\n * still have ongoing work), we ignore the real values of affected\n * signals in favour of their values within the batch\n * @type {Map<Value, any> | null}\n */\nexport let batch_values = null;\n\n/** @type {Effect | null} */\nlet last_scheduled_effect = null;\n\nexport let is_flushing_sync = false;\nlet is_processing = false;\n\n/**\n * During traversal, this is an array. Newly created effects are (if not immediately\n * executed) pushed to this array, rather than going through the scheduling\n * rigamarole that would cause another turn of the flush loop.\n * @type {Effect[] | null}\n */\nexport let collected_effects = null;\n\n/**\n * An array of effects that are marked during traversal as a result of a `set`\n * (not `internal_set`) call. These will be added to the next batch and\n * trigger another `batch.process()`\n * @type {Effect[] | null}\n * @deprecated when we get rid of legacy mode and stores, we can get rid of this\n */\nexport let legacy_updates = null;\n\nvar flush_count = 0;\n\n/** @type {Set<Value>} */\nvar source_stacks = new Set();\n\nlet uid = 1;\n\nexport class Batch {\n\tid = uid++;\n\n\t/** True as soon as `#process` was called */\n\t#started = false;\n\n\tlinked = true;\n\n\t/** @type {Batch | null} */\n\t#prev = null;\n\n\t/** @type {Batch | null} */\n\t#next = null;\n\n\t/** @type {Map<Effect, ReturnType<typeof deferred<any>>>} */\n\tasync_deriveds = new Map();\n\n\t/**\n\t * The current values of any signals that are updated in this batch.\n\t * Tuple format: [value, is_derived] (note: is_derived is false for deriveds, too, if they were overridden via assignment)\n\t * They keys of this map are identical to `this.#previous`\n\t * @type {Map<Value, [any, boolean]>}\n\t */\n\tcurrent = new Map();\n\n\t/**\n\t * The values of any signals (sources and deriveds) that are updated in this batch _before_ those updates took place.\n\t * They keys of this map are identical to `this.#current`\n\t * @type {Map<Value, any>}\n\t */\n\tprevious = new Map();\n\n\t/**\n\t * When the batch is committed (and the DOM is updated), we need to remove old branches\n\t * and append new ones by calling the functions added inside (if/each/key/etc) blocks\n\t * @type {Set<(batch: Batch) => void>}\n\t */\n\t#commit_callbacks = new Set();\n\n\t/**\n\t * If a fork is discarded, we need to destroy any effects that are no longer needed\n\t * @type {Set<(batch: Batch) => void>}\n\t */\n\t#discard_callbacks = new Set();\n\n\t/**\n\t * The number of async effects that are currently in flight\n\t */\n\t#pending = 0;\n\n\t/**\n\t * Async effects that are currently in flight, _not_ inside a pending boundary\n\t * @type {Map<Effect, number>}\n\t */\n\t#blocking_pending = new Map();\n\n\t/**\n\t * A deferred that resolves when the batch is committed, used with `settled()`\n\t * TODO replace with Promise.withResolvers once supported widely enough\n\t * @type {{ promise: Promise<void>, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null}\n\t */\n\t#deferred = null;\n\n\t/**\n\t * 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 * Effects created while this batch was active.\n\t * @type {Effect[]}\n\t */\n\t#new_effects = [];\n\n\t/**\n\t * Deferred effects (which run after async work has completed) that are DIRTY\n\t * @type {Set<Effect>}\n\t */\n\t#dirty_effects = new Set();\n\n\t/**\n\t * Deferred effects that are MAYBE_DIRTY\n\t * @type {Set<Effect>}\n\t */\n\t#maybe_dirty_effects = new Set();\n\n\t/**\n\t * A map of branches that still exist, but will be destroyed when this batch\n\t * is committed — we skip over these during `process`.\n\t * The value contains child effects that were dirty/maybe_dirty before being reset,\n\t * so they can be rescheduled if the branch survives.\n\t * @type {Map<Effect, { d: Effect[], m: Effect[] }>}\n\t */\n\t#skipped_branches = new Map();\n\n\t/**\n\t * Inverse of #skipped_branches which we need to tell prior batches to unskip them when committing\n\t * @type {Set<Effect>}\n\t */\n\t#unskipped_branches = new Set();\n\n\tis_fork = false;\n\n\t#decrement_queued = false;\n\n\tconstructor() {\n\t\t// link batch\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.#blocking_pending.keys()) {\n\t\t\tvar e = effect;\n\t\t\tvar skipped = false;\n\n\t\t\twhile (e.parent !== null) {\n\t\t\t\tif (this.#skipped_branches.has(e)) {\n\t\t\t\t\tskipped = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\te = e.parent;\n\t\t\t}\n\n\t\t\tif (!skipped) {\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 * Add an effect to the #skipped_branches map and reset its children\n\t * @param {Effect} effect\n\t */\n\tskip_effect(effect) {\n\t\tif (!this.#skipped_branches.has(effect)) {\n\t\t\tthis.#skipped_branches.set(effect, { d: [], m: [] });\n\t\t}\n\t\tthis.#unskipped_branches.delete(effect);\n\t}\n\n\t/**\n\t * Remove an effect from the #skipped_branches map and reschedule\n\t * any tracked dirty/maybe_dirty child effects\n\t * @param {Effect} effect\n\t * @param {(e: Effect) => void} callback\n\t */\n\tunskip_effect(effect, callback = (e) => this.schedule(e)) {\n\t\tvar tracked = this.#skipped_branches.get(effect);\n\t\tif (tracked) {\n\t\t\tthis.#skipped_branches.delete(effect);\n\n\t\t\tfor (var e of tracked.d) {\n\t\t\t\tset_signal_status(e, DIRTY);\n\t\t\t\tcallback(e);\n\t\t\t}\n\n\t\t\tfor (e of tracked.m) {\n\t\t\t\tset_signal_status(e, MAYBE_DIRTY);\n\t\t\t\tcallback(e);\n\t\t\t}\n\t\t}\n\t\tthis.#unskipped_branches.add(effect);\n\t}\n\n\t/**\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\tthis.#started = true;\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\t// We always reschedule previously-deferred effects, not just when\n\t\t// #is_deferred() is true, because traversing the tree could make\n\t\t// an if block that contains the last blocking pending effect falsy,\n\t\t// causing the block to no longer be deferred.\n\t\tfor (const e of this.#dirty_effects) {\n\t\t\tthis.#maybe_dirty_effects.delete(e);\n\t\t\tset_signal_status(e, DIRTY);\n\t\t\tthis.schedule(e);\n\t\t}\n\n\t\tfor (const e of this.#maybe_dirty_effects) {\n\t\t\tset_signal_status(e, MAYBE_DIRTY);\n\t\t\tthis.schedule(e);\n\t\t}\n\n\t\tthis.apply();\n\n\t\t/** @type {Effect[]} */\n\t\tvar effects = (collected_effects = []);\n\n\t\t/** @type {Effect[]} */\n\t\tvar render_effects = [];\n\n\t\t/**\n\t\t * @type {Effect[]}\n\t\t * @deprecated when we get rid of legacy mode and stores, we can get rid of this\n\t\t */\n\t\tvar updates = (legacy_updates = []);\n\n\t\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_all() 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);\n\t\t\t\t} catch (e) {\n\t\t\t\t\treset_all(root);\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\t\t}\n\n\t\t// any writes should take effect in a subsequent batch\n\t\tcurrent_batch = null;\n\n\t\tif (updates.length > 0) {\n\t\t\tvar batch = Batch.ensure();\n\t\t\tfor (const e of updates) {\n\t\t\t\tbatch.schedule(e);\n\t\t\t}\n\t\t}\n\n\t\tcollected_effects = null;\n\t\tlegacy_updates = null;\n\n\t\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, t] of this.#skipped_branches) {\n\t\t\t\treset_branch(e, t);\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\treturn;\n\t\t}\n\n\t\t// clear effects. Those that are still needed will be rescheduled through unskipping the skipped branches.\n\t\tthis.#dirty_effects.clear();\n\t\tthis.#maybe_dirty_effects.clear();\n\n\t\t// append/remove branches\n\t\tfor (const fn of this.#commit_callbacks) fn(this);\n\t\tthis.#commit_callbacks.clear();\n\n\t\tprevious_batch = this;\n\t\tflush_queued_effects(render_effects);\n\t\tflush_queued_effects(effects);\n\t\tprevious_batch = null;\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 === 0 && (this.#scheduled.length === 0 || next_batch !== null)) {\n\t\t\tthis.#unlink();\n\n\t\t\t// Order matters here - we need to commit and THEN continue flushing new batches, not the other way around,\n\t\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\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\t// TODO fix the underlying cause, otherwise this will likely regress when non-async mode is removed\n\t\t\tif (async_mode_flag) {\n\t\t\t\tthis.#commit();\n\t\t\t\t// Rebases can activate other batches or null it out, therefore restore the new one here\n\t\t\t\tcurrent_batch = next_batch;\n\t\t\t}\n\t\t}\n\n\t\t// Edge case: During traversal new branches might create effects that run immediately and set state,\n\t\t// causing an effect to be scheduled again. We need to traverse the current batch\n\t\t// once more in that case - most of the time this will just clean up dirty branches.\n\t\tif (this.#scheduled.length > 0) {\n\t\t\tif (next_batch !== null) {\n\t\t\t\tfor (const e of this.#scheduled) {\n\t\t\t\t\tnext_batch.#scheduled.push(e);\n\t\t\t\t}\n\n\t\t\t\tthis.#scheduled = [];\n\t\t\t} else {\n\t\t\t\tnext_batch = this;\n\t\t\t}\n\t\t}\n\n\t\tif (next_batch !== null) {\n\t\t\told_values.clear();\n\t\t\tnext_batch.#process();\n\t\t}\n\t}\n\n\t/**\n\t * Traverse the effect tree, executing effects or stashing\n\t * them for later execution as appropriate\n\t * @param {Effect} root\n\t * @param {Effect[]} effects\n\t * @param {Effect[]} render_effects\n\t */\n\t#traverse(root, effects, render_effects) {\n\t\troot.f ^= CLEAN;\n\n\t\tvar effect = root.first;\n\n\t\twhile (effect !== null) {\n\t\t\tvar flags = effect.f;\n\t\t\tvar is_branch = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;\n\t\t\tvar is_skippable_branch = is_branch && (flags & CLEAN) !== 0;\n\n\t\t\tvar skip = is_skippable_branch || (flags & INERT) !== 0 || this.#skipped_branches.has(effect);\n\n\t\t\tif (!skip && effect.fn !== null) {\n\t\t\t\tif (is_branch) {\n\t\t\t\t\teffect.f ^= CLEAN;\n\t\t\t\t} else if ((flags & EFFECT) !== 0) {\n\t\t\t\t\teffects.push(effect);\n\t\t\t\t} else if (async_mode_flag && (flags & (RENDER_EFFECT | MANAGED_EFFECT)) !== 0) {\n\t\t\t\t\trender_effects.push(effect);\n\t\t\t\t} else if (is_dirty(effect)) {\n\t\t\t\t\tif ((flags & BLOCK_EFFECT) !== 0) this.#maybe_dirty_effects.add(effect);\n\t\t\t\t\tupdate_effect(effect);\n\t\t\t\t}\n\n\t\t\t\tvar child = effect.first;\n\n\t\t\t\tif (child !== null) {\n\t\t\t\t\teffect = child;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\twhile (effect !== null) {\n\t\t\t\tvar next = effect.next;\n\n\t\t\t\tif (next !== null) {\n\t\t\t\t\teffect = next;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\teffect = effect.parent;\n\t\t\t}\n\t\t}\n\t}\n\n\t#find_earlier_batch() {\n\t\tvar batch = this.#prev;\n\n\t\twhile (batch !== null) {\n\t\t\tif (!batch.is_fork) {\n\t\t\t\t// if the batches are connected, break\n\t\t\t\tfor (const [value, [, is_derived]] of this.current) {\n\t\t\t\t\tif (batch.current.has(value) && !is_derived) {\n\t\t\t\t\t\treturn batch;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbatch = batch.#prev;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#merge(batch) {\n\t\tfor (const [source, value] of batch.current) {\n\t\t\tif (!this.previous.has(source) && batch.previous.has(source)) {\n\t\t\t\tthis.previous.set(source, batch.previous.get(source));\n\t\t\t}\n\n\t\t\tthis.current.set(source, value);\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) deferred.promise.then(d.resolve).catch(d.reject);\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// Mark is not guaranteed not touch these, so we transfer them\n\t\tthis.transfer_effects(batch.#dirty_effects, batch.#maybe_dirty_effects);\n\n\t\t/**\n\t\t * mark all effects that depend on `batch.current`, except the\n\t\t * async effects that we just resolved (TODO unless they depend\n\t\t * on values in this batch that are NOT in the later batch?).\n\t\t * Through this we also will populate the correct #skipped_branches,\n\t\t * oncommit callbacks etc, so we don't need to merge them separately.\n\t\t * @param {Value} value\n\t\t */\n\t\tconst mark = (value) => {\n\t\t\tvar reactions = value.reactions;\n\t\t\tif (reactions === null) return;\n\t\t\t// skip if value is derived and is neither dirty nor maybe dirty. transitive\n\t\t\t// deriveds (a derived depending on another derived) are only MAYBE_DIRTY, so\n\t\t\t// we must continue traversing them to reach the effects that depend on them\n\t\t\tif ((value.f & DERIVED) !== 0 && (value.f & (DIRTY | MAYBE_DIRTY)) === 0) {\n\t\t\t\treturn;\n\t\t\t}\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\tmark(/** @type {Derived} */ (reaction));\n\t\t\t\t} else {\n\t\t\t\t\tvar effect = /** @type {Effect} */ (reaction);\n\n\t\t\t\t\tif (flags & (ASYNC | BLOCK_EFFECT) && !this.async_deriveds.has(effect)) {\n\t\t\t\t\t\tthis.#maybe_dirty_effects.delete(effect);\n\t\t\t\t\t\tset_signal_status(effect, DIRTY);\n\t\t\t\t\t\tthis.schedule(effect);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tfor (const source of this.current.keys()) {\n\t\t\tmark(source);\n\t\t}\n\n\t\tthis.oncommit(() => batch.discard());\n\t\tbatch.#unlink();\n\n\t\tcurrent_batch = this;\n\t\tthis.#process();\n\t}\n\n\t/**\n\t * @param {Effect[]} effects\n\t */\n\t#defer_effects(effects) {\n\t\tfor (var i = 0; i < effects.length; i += 1) {\n\t\t\tdefer_effect(effects[i], this.#dirty_effects, this.#maybe_dirty_effects);\n\t\t}\n\t}\n\n\t/**\n\t * Associate a change to a given source with the current\n\t * batch, noting its previous and current values\n\t * @param {Value} source\n\t * @param {any} value\n\t * @param {boolean} [is_derived]\n\t */\n\tcapture(source, value, is_derived = false) {\n\t\tif (source.v !== UNINITIALIZED && !this.previous.has(source)) {\n\t\t\tthis.previous.set(source, source.v);\n\t\t}\n\n\t\t// Don't save errors in `batch_values`, or they won't be thrown in `runtime.js#get`\n\t\tif ((source.f & ERROR_VALUE) === 0) {\n\t\t\tthis.current.set(source, [value, is_derived]);\n\t\t\tbatch_values?.set(source, value);\n\t\t}\n\n\t\tif (!this.is_fork) {\n\t\t\tsource.v = value;\n\t\t}\n\t}\n\n\tactivate() {\n\t\tcurrent_batch = this;\n\t}\n\n\tdeactivate() {\n\t\tcurrent_batch = null;\n\t\tbatch_values = null;\n\t}\n\n\tflush() {\n\t\ttry {\n\t\t\tif (DEV) {\n\t\t\t\tsource_stacks.clear();\n\t\t\t}\n\n\t\t\tis_processing = true;\n\t\t\tcurrent_batch = this;\n\n\t\t\tthis.#process();\n\t\t} finally {\n\t\t\tflush_count = 0;\n\t\t\tlast_scheduled_effect = null;\n\t\t\tcollected_effects = null;\n\t\t\tlegacy_updates = null;\n\t\t\tis_processing = false;\n\n\t\t\tcurrent_batch = null;\n\t\t\tbatch_values = null;\n\n\t\t\told_values.clear();\n\n\t\t\tif (DEV) {\n\t\t\t\tfor (const source of source_stacks) {\n\t\t\t\t\tsource.updated = null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tdiscard() {\n\t\tfor (const fn of this.#discard_callbacks) fn(this);\n\t\tthis.#discard_callbacks.clear();\n\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/**\n\t * @param {Effect} effect\n\t */\n\tregister_created_effect(effect) {\n\t\tthis.#new_effects.push(effect);\n\t}\n\n\t#commit() {\n\t\t// If there are other pending batches, they now need to be 'rebased' —\n\t\t// in other words, we re-run block/async effects with the newly\n\t\t// committed state, unless the batch in question has a more\n\t\t// recent value for a given source\n\t\tfor (let batch = first_batch; batch !== null; batch = batch.#next) {\n\t\t\tvar is_earlier = batch.id < this.id;\n\n\t\t\t/** @type {Source[]} */\n\t\t\tvar sources = [];\n\n\t\t\tfor (const [source, [value, is_derived]] of this.current) {\n\t\t\t\tif (batch.current.has(source)) {\n\t\t\t\t\tvar batch_value = /** @type {[any, boolean]} */ (batch.current.get(source))[0]; // faster than destructuring\n\n\t\t\t\t\tif (is_earlier && value !== batch_value) {\n\t\t\t\t\t\t// bring the value up to date\n\t\t\t\t\t\tbatch.current.set(source, [value, is_derived]);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// same value or later batch has more recent value,\n\t\t\t\t\t\t// no need to re-run these effects\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tsources.push(source);\n\t\t\t}\n\n\t\t\tif (is_earlier) {\n\t\t\t\t// TODO do we need to restart these in some cases, instead of\n\t\t\t\t// immediately resolving them? Likely not because of how this.apply() works.\n\t\t\t\tfor (const [effect, deferred] of this.async_deriveds) {\n\t\t\t\t\tconst d = batch.async_deriveds.get(effect);\n\t\t\t\t\tif (d) deferred.promise.then(d.resolve).catch(d.reject);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar current = [...batch.current.keys()].filter(\n\t\t\t\t(source) => !(/** @type {[any, boolean]} */ (batch.current.get(source))[1])\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 || current.length === 0) continue;\n\n\t\t\t// Re-run async/block effects that depend on distinct values changed in both batches (ignoring deriveds)\n\t\t\tvar others = current.filter((source) => !this.current.has(source));\n\n\t\t\tif (others.length === 0) {\n\t\t\t\tif (is_earlier) {\n\t\t\t\t\t// this batch is now obsolete and can be discarded\n\t\t\t\t\tbatch.discard();\n\t\t\t\t}\n\t\t\t} else if (sources.length > 0) {\n\t\t\t\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// A batch was unskipped in a later batch -> tell prior batches to unskip it, too\n\t\t\t\tif (is_earlier) {\n\t\t\t\t\tfor (const unskipped of this.#unskipped_branches) {\n\t\t\t\t\t\tbatch.unskip_effect(unskipped, (e) => {\n\t\t\t\t\t\t\tif ((e.f & (BLOCK_EFFECT | ASYNC)) !== 0) {\n\t\t\t\t\t\t\t\tbatch.schedule(e);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbatch.#defer_effects([e]);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbatch.activate();\n\n\t\t\t\t/** @type {Set<Value>} */\n\t\t\t\tvar marked = new Set();\n\n\t\t\t\t/** @type {Map<Reaction, boolean>} */\n\t\t\t\tvar checked = new Map();\n\n\t\t\t\tfor (var source of sources) {\n\t\t\t\t\tmark_effects(source, others, marked, checked);\n\t\t\t\t}\n\n\t\t\t\tchecked = new Map();\n\t\t\t\tvar current_unequal = [...batch.current]\n\t\t\t\t\t.filter(([c, v1]) => {\n\t\t\t\t\t\tconst v2 = this.current.get(c);\n\t\t\t\t\t\tif (!v2) return true;\n\t\t\t\t\t\t// Either their values are different or one is a derived but not the other\n\t\t\t\t\t\treturn v2[0] !== v1[0] || v2[1] !== v1[1];\n\t\t\t\t\t})\n\t\t\t\t\t.map(([c]) => c);\n\n\t\t\t\tif (current_unequal.length > 0) {\n\t\t\t\t\tfor (const effect of this.#new_effects) {\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t(effect.f & (DESTROYED | INERT | EAGER_EFFECT)) === 0 &&\n\t\t\t\t\t\t\tdepends_on(effect, current_unequal, checked)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tif ((effect.f & (ASYNC | BLOCK_EFFECT)) !== 0) {\n\t\t\t\t\t\t\t\tset_signal_status(effect, DIRTY);\n\t\t\t\t\t\t\t\tbatch.schedule(effect);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tbatch.#dirty_effects.add(effect);\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\t// Only apply and traverse when we know we triggered async work with marking the effects\n\t\t\t\t// and know this won't run anyway right afterwards\n\t\t\t\tif (batch.#scheduled.length > 0 && !batch.#decrement_queued) {\n\t\t\t\t\tbatch.apply();\n\n\t\t\t\t\tfor (var root of batch.#resolve()) {\n\t\t\t\t\t\tbatch.#traverse(root, [], []);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbatch.deactivate();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {boolean} blocking\n\t * @param {Effect} effect\n\t */\n\tincrement(blocking, effect) {\n\t\tthis.#pending += 1;\n\n\t\tif (blocking) {\n\t\t\tlet blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;\n\t\t\tthis.#blocking_pending.set(effect, blocking_pending_count + 1);\n\t\t}\n\t}\n\n\t/**\n\t * @param {boolean} blocking\n\t * @param {Effect} effect\n\t */\n\tdecrement(blocking, effect) {\n\t\tthis.#pending -= 1;\n\n\t\tif (blocking) {\n\t\t\tlet blocking_pending_count = this.#blocking_pending.get(effect) ?? 0;\n\n\t\t\tif (blocking_pending_count === 1) {\n\t\t\t\tthis.#blocking_pending.delete(effect);\n\t\t\t} else {\n\t\t\t\tthis.#blocking_pending.set(effect, blocking_pending_count - 1);\n\t\t\t}\n\t\t}\n\n\t\tif (this.#decrement_queued) 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/**\n\t * @param {Set<Effect>} dirty_effects\n\t * @param {Set<Effect>} maybe_dirty_effects\n\t */\n\ttransfer_effects(dirty_effects, maybe_dirty_effects) {\n\t\tfor (const e of dirty_effects) {\n\t\t\tthis.#dirty_effects.add(e);\n\t\t}\n\n\t\tfor (const e of maybe_dirty_effects) {\n\t\t\tthis.#maybe_dirty_effects.add(e);\n\t\t}\n\n\t\tdirty_effects.clear();\n\t\tmaybe_dirty_effects.clear();\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\toncommit(fn) {\n\t\tthis.#commit_callbacks.add(fn);\n\t}\n\n\t/** @param {(batch: Batch) => void} fn */\n\tondiscard(fn) {\n\t\tthis.#discard_callbacks.add(fn);\n\t}\n\n\tsettled() {\n\t\treturn (this.#deferred ??= deferred()).promise;\n\t}\n\n\tstatic ensure() {\n\t\tif (current_batch === null) {\n\t\t\tconst batch = (current_batch = new Batch());\n\n\t\t\tif (!is_processing && !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\tapply() {\n\t\tif (!async_mode_flag || (!this.is_fork && this.#prev === null && this.#next === null)) {\n\t\t\tbatch_values = null;\n\t\t\treturn;\n\t\t}\n\n\t\t// if there are multiple batches, we are 'time travelling' —\n\t\t// we need to override values with the ones in this batch...\n\t\tbatch_values = new Map();\n\t\tfor (const [source, [value]] of this.current) {\n\t\t\tbatch_values.set(source, value);\n\t\t}\n\n\t\t// ...and undo changes belonging to other batches unless they 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// If two batches intersect, the latter batch will be merged into the earlier batch,\n\t\t\t// and we should treat them as a single set of changes\n\t\t\tvar intersects = false;\n\n\t\t\tif (batch.id < this.id) {\n\t\t\t\tfor (const [source, [, is_derived]] of batch.current) {\n\t\t\t\t\t// Derived values don't partake in the intersection mechanism, because a derived could\n\t\t\t\t\t// be triggered in one batch already but not the other one yet, causing a false-positive\n\t\t\t\t\tif (is_derived) continue;\n\n\t\t\t\t\tif (this.current.has(source)) {\n\t\t\t\t\t\tintersects = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\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 (!intersects) {\n\t\t\t\tfor (const [source, previous] of batch.previous) {\n\t\t\t\t\tif (!batch_values.has(source)) {\n\t\t\t\t\t\tbatch_values.set(source, previous);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t *\n\t * @param {Effect} effect\n\t */\n\tschedule(effect) {\n\t\tlast_scheduled_effect = effect;\n\n\t\t// defer render effects inside a pending boundary\n\t\t// TODO the `REACTION_RAN` check is only necessary because of legacy `$:` effects AFAICT — we can remove later\n\t\tif (\n\t\t\teffect.b?.is_pending &&\n\t\t\t(effect.f & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0 &&\n\t\t\t(effect.f & REACTION_RAN) === 0\n\t\t) {\n\t\t\teffect.b.defer_effect(effect);\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#scheduled.push(effect);\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}\n}\n\n// TODO Svelte@6 think about removing the callback argument.\n/**\n * Synchronously flush any pending updates.\n * Returns void if no callback is provided, otherwise returns the result of calling the callback.\n * @template [T=void]\n * @param {(() => T) | undefined} [fn]\n * @returns {T}\n */\nexport function flushSync(fn) {\n\tvar was_flushing_sync = is_flushing_sync;\n\tvar prev_previous_batch = previous_batch;\n\tprevious_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\tprevious_batch = prev_previous_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 * @param {Array<Effect>} effects\n * @returns {void}\n */\nfunction flush_queued_effects(effects) {\n\tvar length = effects.length;\n\tif (length === 0) return;\n\n\tvar i = 0;\n\n\twhile (i < length) {\n\t\tvar effect = effects[i++];\n\n\t\tif ((effect.f & (DESTROYED | INERT)) === 0 && is_dirty(effect)) {\n\t\t\teager_block_effects = new Set();\n\n\t\t\tupdate_effect(effect);\n\n\t\t\t// Effects with no dependencies or teardown do not get added to the effect tree.\n\t\t\t// Deferred effects (e.g. `$effect(...)`) _are_ added to the tree because we\n\t\t\t// don't know if we need to keep them until they are executed. Doing the check\n\t\t\t// here (rather than in `update_effect`) allows us to skip the work for\n\t\t\t// immediate effects.\n\t\t\tif (\n\t\t\t\teffect.deps === null &&\n\t\t\t\teffect.first === null &&\n\t\t\t\teffect.nodes === null &&\n\t\t\t\teffect.teardown === null &&\n\t\t\t\teffect.ac === null\n\t\t\t) {\n\t\t\t\t// remove this effect from the graph\n\t\t\t\tunlink_effect(effect);\n\t\t\t}\n\n\t\t\t// If update_effect() has a flushSync() in it, we may have flushed another flush_queued_effects(),\n\t\t\t// which already handled this logic and did set eager_block_effects to null.\n\t\t\tif (eager_block_effects?.size > 0) {\n\t\t\t\told_values.clear();\n\n\t\t\t\tfor (const e of eager_block_effects) {\n\t\t\t\t\t// Skip eager effects that have already been unmounted\n\t\t\t\t\tif ((e.f & (DESTROYED | INERT)) !== 0) continue;\n\n\t\t\t\t\t// Run effects in order from ancestor to descendant, else we could run into nullpointers\n\t\t\t\t\t/** @type {Effect[]} */\n\t\t\t\t\tconst ordered_effects = [e];\n\t\t\t\t\tlet ancestor = e.parent;\n\t\t\t\t\twhile (ancestor !== null) {\n\t\t\t\t\t\tif (eager_block_effects.has(ancestor)) {\n\t\t\t\t\t\t\teager_block_effects.delete(ancestor);\n\t\t\t\t\t\t\tordered_effects.push(ancestor);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tancestor = ancestor.parent;\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (let j = ordered_effects.length - 1; j >= 0; j--) {\n\t\t\t\t\t\tconst e = ordered_effects[j];\n\t\t\t\t\t\t// Skip eager effects that have already been unmounted\n\t\t\t\t\t\tif ((e.f & (DESTROYED | INERT)) !== 0) continue;\n\t\t\t\t\t\tupdate_effect(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\teager_block_effects.clear();\n\t\t\t}\n\t\t}\n\t}\n\n\teager_block_effects = null;\n}\n\n/**\n * This is similar to `mark_reactions`, but it only marks async/block effects\n * depending on `value` and at least one of the other `sources`, so that\n * these effects can re-run after another batch has been committed\n * @param {Value} value\n * @param {Source[]} sources\n * @param {Set<Value>} marked\n * @param {Map<Reaction, boolean>} checked\n */\nfunction mark_effects(value, sources, marked, checked) {\n\tif (marked.has(value)) return;\n\tmarked.add(value);\n\n\tif (value.reactions !== null) {\n\t\tfor (const reaction of value.reactions) {\n\t\t\tconst flags = reaction.f;\n\n\t\t\tif ((flags & DERIVED) !== 0) {\n\t\t\t\tmark_effects(/** @type {Derived} */ (reaction), sources, marked, checked);\n\t\t\t} else if (\n\t\t\t\t(flags & (ASYNC | BLOCK_EFFECT)) !== 0 &&\n\t\t\t\t(flags & DIRTY) === 0 &&\n\t\t\t\tdepends_on(reaction, sources, checked)\n\t\t\t) {\n\t\t\t\tset_signal_status(reaction, DIRTY);\n\t\t\t\tschedule_effect(/** @type {Effect} */ (reaction));\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * When committing a fork, we need to trigger eager effects so that\n * any `$state.eager(...)` expressions update immediately. This\n * function allows us to discover them\n * @param {Value} value\n * @param {Set<Effect>} effects\n */\nfunction mark_eager_effects(value, effects) {\n\tif (value.reactions === null) return;\n\n\tfor (const reaction of value.reactions) {\n\t\tconst flags = reaction.f;\n\n\t\tif ((flags & DERIVED) !== 0) {\n\t\t\tmark_eager_effects(/** @type {Derived} */ (reaction), effects);\n\t\t} else if ((flags & EAGER_EFFECT) !== 0) {\n\t\t\tset_signal_status(reaction, DIRTY);\n\t\t\teffects.add(/** @type {Effect} */ (reaction));\n\t\t}\n\t}\n}\n\n/**\n * @param {Reaction} reaction\n * @param {Source[]} sources\n * @param {Map<Reaction, boolean>} checked\n */\nfunction depends_on(reaction, sources, checked) {\n\tconst depends = checked.get(reaction);\n\tif (depends !== undefined) return depends;\n\n\tif (reaction.deps !== null) {\n\t\tfor (const dep of reaction.deps) {\n\t\t\tif (includes.call(sources, dep)) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif ((dep.f & DERIVED) !== 0 && depends_on(/** @type {Derived} */ (dep), sources, checked)) {\n\t\t\t\tchecked.set(/** @type {Derived} */ (dep), true);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\tchecked.set(reaction, false);\n\n\treturn false;\n}\n\n/**\n * @param {Effect} effect\n * @returns {void}\n */\nexport function schedule_effect(effect) {\n\t/** @type {Batch} */ (current_batch).schedule(effect);\n}\n\n/** @type {Source<number>[]} */\nlet eager_versions = [];\n\nfunction eager_flush() {\n\tflushSync(() => {\n\t\tconst eager = eager_versions;\n\t\teager_versions = [];\n\t\tfor (const version of eager) {\n\t\t\tupdate(version);\n\t\t}\n\t});\n}\n\n/** @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\teager_effect(() => {\n\t\tif (initial) {\n\t\t\t// the first time this runs, we create an eager effect\n\t\t\t// that will run eagerly whenever the expression changes\n\t\t\tvar previous_batch_values = batch_values;\n\n\t\t\ttry {\n\t\t\t\tbatch_values = null;\n\t\t\t\tvalue = fn();\n\t\t\t} finally {\n\t\t\t\tbatch_values = previous_batch_values;\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\t// the second time this effect runs, it's to schedule a\n\t\t// `version` update. since this will recreate the effect,\n\t\t// we don't need to evaluate the expression here\n\t\tif (eager_versions.length === 0) {\n\t\t\tqueue_micro_task(eager_flush);\n\t\t}\n\n\t\teager_versions.push(version);\n\t});\n\n\tinitial = false;\n\n\treturn value;\n}\n\n/**\n * Mark all the effects inside a skipped branch CLEAN, so that\n * they can be correctly rescheduled later. Tracks dirty and maybe_dirty\n * effects so they can be rescheduled if the branch survives.\n * @param {Effect} effect\n * @param {{ d: Effect[], m: Effect[] }} tracked\n */\nfunction reset_branch(effect, tracked) {\n\t// clean branch = nothing dirty inside, no need to traverse further\n\tif ((effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) {\n\t\treturn;\n\t}\n\n\tif ((effect.f & DIRTY) !== 0) {\n\t\ttracked.d.push(effect);\n\t} else if ((effect.f & MAYBE_DIRTY) !== 0) {\n\t\ttracked.m.push(effect);\n\t}\n\n\tset_signal_status(effect, CLEAN);\n\n\tvar e = effect.first;\n\twhile (e !== null) {\n\t\treset_branch(e, tracked);\n\t\te = e.next;\n\t}\n}\n\n/**\n * Mark an entire effect tree clean following an error\n * @param {Effect} effect\n */\nfunction reset_all(effect) {\n\tset_signal_status(effect, CLEAN);\n\n\tvar e = effect.first;\n\twhile (e !== null) {\n\t\treset_all(e);\n\t\te = e.next;\n\t}\n}\n\n/**\n * Creates a 'fork', in which state changes are evaluated but not applied to the DOM.\n * This is useful for speculatively loading data (for example) when you suspect that\n * the user is about to take some action.\n *\n * Frameworks like SvelteKit can use this to preload data when the user touches or\n * hovers over a link, making any subsequent navigation feel instantaneous.\n *\n * The `fn` parameter is a synchronous function that modifies some state. The\n * state changes will be reverted after the fork is initialised, then reapplied\n * if and when the fork is eventually committed.\n *\n * When it becomes clear that a fork will _not_ be committed (e.g. because the\n * user navigated elsewhere), it must be discarded to avoid leaking memory.\n *\n * @param {() => void} fn\n * @returns {Fork}\n * @since 5.42\n */\nexport function fork(fn) {\n\tif (!async_mode_flag) {\n\t\te.experimental_async_required('fork');\n\t}\n\n\tif (current_batch !== null) {\n\t\te.fork_timing();\n\t}\n\n\tflushSync();\n\n\tvar batch = Batch.ensure();\n\tbatch.is_fork = true;\n\tbatch_values = new Map();\n\n\tvar committed = false;\n\tvar settled = batch.settled();\n\n\tfn();\n\tflushSync();\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 (!batch.linked) {\n\t\t\t\te.fork_discarded();\n\t\t\t}\n\n\t\t\tcommitted = true;\n\n\t\t\tbatch.is_fork = false;\n\n\t\t\t// apply changes and update write versions so deriveds see the change\n\t\t\tfor (var [source, [value]] of batch.current) {\n\t\t\t\tsource.v = value;\n\t\t\t\tsource.wv = increment_write_version();\n\t\t\t}\n\n\t\t\t// trigger any `$state.eager(...)` expressions with the new state.\n\t\t\t// eager effects don't get scheduled like other effects, so we\n\t\t\t// can't just encounter them during traversal, we need to\n\t\t\t// proactively flush them\n\t\t\t// TODO maybe there's a better implementation?\n\t\t\tflushSync(() => {\n\t\t\t\t/** @type {Set<Effect>} */\n\t\t\t\tvar eager_effects = new Set();\n\n\t\t\t\tfor (var source of batch.current.keys()) {\n\t\t\t\t\tmark_eager_effects(source, eager_effects);\n\t\t\t\t}\n\n\t\t\t\tset_eager_effects(eager_effects);\n\t\t\t\tflush_eager_effects();\n\t\t\t});\n\n\t\t\tbatch.flush();\n\t\t\tawait settled;\n\t\t},\n\t\tdiscard: () => {\n\t\t\t// cause any MAYBE_DIRTY deriveds to update\n\t\t\t// if they depend on things thath changed\n\t\t\t// inside the discarded fork\n\t\t\tfor (var source of batch.current.keys()) {\n\t\t\t\tsource.wv = increment_write_version();\n\t\t\t}\n\n\t\t\tif (!committed && batch.linked) {\n\t\t\t\tbatch.discard();\n\t\t\t}\n\t\t}\n\t};\n}\n\n/**\n * Forcibly remove all current batches, to prevent cross-talk between tests\n */\nexport function clear() {\n\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\tincrement_write_version,\n\tupdate_effect,\n\tcurrent_sources,\n\tis_dirty,\n\tuntracking,\n\tis_destroying_effect,\n\tpush_reaction_value\n} from '../runtime.js';\nimport { equals, safe_equals } from './equality.js';\nimport {\n\tCLEAN,\n\tDERIVED,\n\tDIRTY,\n\tBRANCH_EFFECT,\n\tEAGER_EFFECT,\n\tMAYBE_DIRTY,\n\tBLOCK_EFFECT,\n\tROOT_EFFECT,\n\tASYNC\n} 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\teager_block_effects,\n\tschedule_effect,\n\tlegacy_updates\n} from './batch.js';\nimport { proxy } from '../proxy.js';\nimport { execute_derived } from './deriveds.js';\nimport { set_signal_status, update_derived_status } from './status.js';\n\n/** @type {Set<Effect>} */\nexport let eager_effects = new Set();\n\n/** @type {Map<Value, any>} */\nexport const old_values = new Map();\n\n/**\n * @param {Set<any>} v\n */\nexport function set_eager_effects(v) {\n\teager_effects = v;\n}\n\nlet eager_effects_deferred = false;\n\nexport function set_eager_effects_deferred() {\n\teager_effects_deferred = true;\n}\n\n/**\n * @template V\n * @param {V} v\n * @param {Error | null} [stack]\n * @returns {Source<V>}\n */\n// TODO rename this to `state` throughout the codebase\nexport function source(v, stack) {\n\t/** @type {Value} */\n\tvar signal = {\n\t\tf: 0, // TODO ideally we could skip this altogether, but it causes type errors\n\t\tv,\n\t\treactions: null,\n\t\tequals,\n\t\trv: 0,\n\t\twv: 0\n\t};\n\n\tif (DEV && tracing_mode_flag) {\n\t\tsignal.created = stack ?? get_error('created at');\n\t\tsignal.updated = null;\n\t\tsignal.set_during_effect = false;\n\t\tsignal.trace = null;\n\t}\n\n\treturn signal;\n}\n\n/**\n * @template V\n * @param {V} v\n * @param {Error | null} [stack]\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function state(v, stack) {\n\tconst s = source(v, stack);\n\n\tpush_reaction_value(s);\n\n\treturn s;\n}\n\n/**\n * @template V\n * @param {V} initial_value\n * @param {boolean} [immutable]\n * @returns {Source<V>}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function mutable_source(initial_value, immutable = false, trackable = true) {\n\tconst s = source(initial_value);\n\tif (!immutable) {\n\t\ts.equals = safe_equals;\n\t}\n\n\t// bind the signal to the component context, in case we need to\n\t// track updates to trigger beforeUpdate/afterUpdate callbacks\n\tif (legacy_mode_flag && trackable && component_context !== null && component_context.l !== null) {\n\t\t(component_context.l.s ??= []).push(s);\n\t}\n\n\treturn s;\n}\n\n/**\n * @template V\n * @param {Value<V>} source\n * @param {V} value\n */\nexport function mutate(source, value) {\n\tset(\n\t\tsource,\n\t\tuntrack(() => get(source))\n\t);\n\treturn value;\n}\n\n/**\n * @template V\n * @param {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 * A set of signals we have already seen while traversing in mark_reactions.\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\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\tif (!source.equals(value)) {\n\t\tif (is_destroying_effect) {\n\t\t\told_values.set(source, value);\n\t\t} else if (!old_values.has(source)) {\n\t\t\t// only record the value from before the first write in this flush, otherwise a\n\t\t\t// teardown would see the value from before whichever write happened to be last\n\t\t\told_values.set(source, source.v);\n\t\t}\n\n\t\tvar batch = Batch.ensure();\n\t\tbatch.capture(source, value);\n\n\t\tif (DEV) {\n\t\t\tif (tracing_mode_flag || active_effect !== null) {\n\t\t\t\tsource.updated ??= new Map();\n\n\t\t\t\t// For performance reasons, when not using $inspect.trace, we only start collecting stack traces\n\t\t\t\t// after the same source has been updated more than 5 times in the same flush cycle.\n\t\t\t\tconst count = (source.updated.get('')?.count ?? 0) + 1;\n\t\t\t\tsource.updated.set('', { error: /** @type {any} */ (null), count });\n\n\t\t\t\tif (tracing_mode_flag || count > 5) {\n\t\t\t\t\tconst error = get_error('updated at');\n\n\t\t\t\t\tif (error !== null) {\n\t\t\t\t\t\tlet entry = source.updated.get(error.stack);\n\n\t\t\t\t\t\tif (!entry) {\n\t\t\t\t\t\t\tentry = { error, count: 0 };\n\t\t\t\t\t\t\tsource.updated.set(error.stack, entry);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tentry.count++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (active_effect !== null) {\n\t\t\t\tsource.set_during_effect = true;\n\t\t\t}\n\t\t}\n\n\t\tif ((source.f & DERIVED) !== 0) {\n\t\t\tconst derived = /** @type {Derived} */ (source);\n\n\t\t\t// if we are assigning to a dirty derived we set it to clean/maybe dirty but we also eagerly execute it to track the dependencies\n\t\t\tif ((source.f & DIRTY) !== 0) {\n\t\t\t\texecute_derived(derived);\n\t\t\t}\n\n\t\t\t// During time traveling we don't want to reset the status so that\n\t\t\t// traversal of the graph in the other batches still happens\n\t\t\tif (batch_values === null) {\n\t\t\t\tupdate_derived_status(derived);\n\t\t\t}\n\t\t}\n\n\t\tsource.wv = increment_write_version();\n\n\t\t// For debugging, in case you want to know which reactions are being scheduled:\n\t\t// log_reactions(source);\n\t\tseen = null;\n\t\tcount_deps = 0;\n\t\tmark_reactions(source, DIRTY, updated_during_traversal);\n\t\tseen = null;\n\n\t\t// It's possible that the current reaction might not have up-to-date dependencies\n\t\t// whilst it's actively running. So in the case of ensuring it registers the reaction\n\t\t// properly for itself, we need to ensure the current effect actually gets\n\t\t// scheduled. i.e: `$effect(() => x++)`\n\t\tif (\n\t\t\tis_runes() &&\n\t\t\tactive_effect !== null &&\n\t\t\t(active_effect.f & CLEAN) !== 0 &&\n\t\t\t(active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0\n\t\t) {\n\t\t\tif (untracked_writes === null) {\n\t\t\t\tset_untracked_writes([source]);\n\t\t\t} else {\n\t\t\t\tuntracked_writes.push(source);\n\t\t\t}\n\t\t}\n\n\t\tif (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) {\n\t\t\tflush_eager_effects();\n\t\t}\n\t}\n\n\treturn value;\n}\n\nexport function flush_eager_effects() {\n\teager_effects_deferred = false;\n\n\tfor (const effect of eager_effects) {\n\t\t// Mark clean inspect-effects as maybe dirty and then check their dirtiness\n\t\t// instead of just updating the effects - this way we avoid overfiring.\n\t\tif ((effect.f & CLEAN) !== 0) {\n\t\t\tset_signal_status(effect, MAYBE_DIRTY);\n\t\t}\n\n\t\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\n/**\n * @param {Value} signal\n * @param {number} status should be DIRTY or MAYBE_DIRTY\n * @param {Effect[] | null} updated_during_traversal\n * @returns {void}\n */\nfunction mark_reactions(signal, status, updated_during_traversal) {\n\tvar reactions = signal.reactions;\n\tif (reactions === null) return;\n\n\tvar runes = is_runes();\n\tvar length = reactions.length;\n\n\tcount_deps += length;\n\t// Activate the `seen` Set if we think from the unusually high number of deps that\n\t// there might be cycles in the graph, to avoid repeated lookups for reactions\n\t// Example: https://github.com/sveltejs/svelte/issues/16658 has a graph with one source\n\t// reaching ~10000 distinct deriveds/effects each, resulting in 65 million walks through repeated visits.\n\tif (count_deps > 100000 && seen === null) seen = new Set();\n\n\tif (seen !== null) {\n\t\tif (seen.has(signal)) return;\n\t\tseen.add(signal);\n\t}\n\n\tfor (var i = 0; i < length; i++) {\n\t\tvar reaction = reactions[i];\n\t\tvar flags = reaction.f;\n\n\t\t// In legacy mode, skip the current effect to prevent infinite loops\n\t\tif (!runes && reaction === active_effect) continue;\n\n\t\tvar not_dirty = (flags & DIRTY) === 0;\n\n\t\t// don't set a DIRTY reaction to MAYBE_DIRTY\n\t\tif (not_dirty) {\n\t\t\tset_signal_status(reaction, status);\n\t\t}\n\n\t\tif ((flags & EAGER_EFFECT) !== 0) {\n\t\t\t// Eager effects need to run immediately:\n\t\t\t// - for $inspect so that the stack trace makes sense\n\t\t\t// - for $state.eager because they might be without an effect parent\n\t\t\teager_effects.add(/** @type {Effect} */ (reaction));\n\t\t} else if ((flags & DERIVED) !== 0) {\n\t\t\tvar derived = /** @type {Derived} */ (reaction);\n\n\t\t\tbatch_values?.delete(derived);\n\t\t\tmark_reactions(derived, MAYBE_DIRTY, updated_during_traversal);\n\t\t} else if (not_dirty) {\n\t\t\tvar effect = /** @type {Effect} */ (reaction);\n\n\t\t\tif ((flags & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) {\n\t\t\t\teager_block_effects.add(effect);\n\t\t\t}\n\n\t\t\tif (updated_during_traversal !== null) {\n\t\t\t\tupdated_during_traversal.push(effect);\n\t\t\t} else {\n\t\t\t\tschedule_effect(effect);\n\t\t\t}\n\t\t}\n\t}\n}\n","/** @import { Source } from '#client' */\nimport { DEV } from 'esm-env';\nimport {\n\tget,\n\tactive_effect,\n\tupdate_version,\n\tactive_reaction,\n\tset_update_version,\n\tset_active_reaction\n} from './runtime.js';\nimport {\n\tarray_prototype,\n\tget_descriptor,\n\tget_prototype_of,\n\tis_array,\n\tobject_prototype\n} from '../shared/utils.js';\nimport {\n\tstate as source,\n\tset,\n\tincrement,\n\tflush_eager_effects,\n\tset_eager_effects_deferred\n} from './reactivity/sources.js';\nimport { 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 && (!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} from '#client/constants';\nimport { eager_block_effects } from '../reactivity/batch.js';\nimport { NAMESPACE_HTML } from '../../../constants.js';\n\n// export these for reference in the compiled code, making global name deduplication unnecessary\n/** @type {Window} */\nexport var $window;\n\n/** @type {Document} */\nexport var $document;\n\n/** @type {boolean} */\nexport var is_firefox;\n\n/** @type {() => Node | null} */\nvar first_child_getter;\n/** @type {() => Node | null} */\nvar next_sibling_getter;\n\n/**\n * Initialize these lazily to avoid issues when using the runtime in a server context\n * where these globals are not available while avoiding a separate server entry point\n */\nexport function init_operations() {\n\tif ($window !== undefined) {\n\t\treturn;\n\t}\n\n\t$window = window;\n\t$document = document;\n\tis_firefox = /Firefox/.test(navigator.userAgent);\n\n\tvar element_prototype = Element.prototype;\n\tvar node_prototype = Node.prototype;\n\tvar text_prototype = Text.prototype;\n\n\t// @ts-ignore\n\tfirst_child_getter = get_descriptor(node_prototype, 'firstChild').get;\n\t// @ts-ignore\n\tnext_sibling_getter = get_descriptor(node_prototype, 'nextSibling').get;\n\n\tif (is_extensible(element_prototype)) {\n\t\t// the following assignments improve perf of lookups on DOM nodes\n\t\t/** @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\treturn document.createTextNode(value);\n}\n\n/**\n * @template {Node} N\n * @param {N} node\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function get_first_child(node) {\n\treturn /** @type {TemplateNode | null} */ (first_child_getter.call(node));\n}\n\n/**\n * @template {Node} N\n * @param {N} node\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function get_next_sibling(node) {\n\treturn /** @type {TemplateNode | null} */ (next_sibling_getter.call(node));\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @template {Node} N\n * @param {N} node\n * @param {boolean} is_text\n * @returns {TemplateNode | null}\n */\nexport function child(node, is_text) {\n\tif (!hydrating) {\n\t\treturn get_first_child(node);\n\t}\n\n\tvar child = get_first_child(hydrate_node);\n\n\t// Child can be null if we have an element with a single child, like `<p>{text}</p>`, where `text` is empty\n\tif (child === null) {\n\t\tchild = hydrate_node.appendChild(create_text());\n\t} else if (is_text && child.nodeType !== TEXT_NODE) {\n\t\tvar text = create_text();\n\t\tchild?.before(text);\n\t\tset_hydrate_node(text);\n\t\treturn text;\n\t}\n\n\tif (is_text) {\n\t\tmerge_text_nodes(/** @type {Text} */ (child));\n\t}\n\n\tset_hydrate_node(child);\n\treturn child;\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @param {TemplateNode} node\n * @param {boolean} [is_text]\n * @returns {TemplateNode | null}\n */\nexport function first_child(node, is_text = false) {\n\tif (!hydrating) {\n\t\tvar first = get_first_child(node);\n\n\t\t// TODO prevent user comments with the empty string when preserveComments is true\n\t\tif (first instanceof Comment && first.data === '') return get_next_sibling(first);\n\n\t\treturn first;\n\t}\n\n\tif (is_text) {\n\t\t// if an {expression} is empty during SSR, there might be no\n\t\t// text node to hydrate — we must therefore create one\n\t\tif (hydrate_node?.nodeType !== TEXT_NODE) {\n\t\t\tvar text = create_text();\n\n\t\t\thydrate_node?.before(text);\n\t\t\tset_hydrate_node(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tmerge_text_nodes(/** @type {Text} */ (hydrate_node));\n\t}\n\n\treturn hydrate_node;\n}\n\n/**\n * `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 (next_sibling?.nodeType !== TEXT_NODE) {\n\t\t\tvar text = create_text();\n\t\t\t// If the next sibling is `null` and we're handling text then it's because\n\t\t\t// the SSR content was empty for the text, so we need to generate a new text\n\t\t\t// node and insert it after the last sibling\n\t\t\tif (next_sibling === null) {\n\t\t\t\tlast_sibling?.after(text);\n\t\t\t} else {\n\t\t\t\tnext_sibling.before(text);\n\t\t\t}\n\t\t\tset_hydrate_node(text);\n\t\t\treturn text;\n\t\t}\n\n\t\tmerge_text_nodes(/** @type {Text} */ (next_sibling));\n\t}\n\n\tset_hydrate_node(next_sibling);\n\treturn next_sibling;\n}\n\n/**\n * @template {Node} N\n * @param {N} node\n * @returns {void}\n */\nexport function clear_text_content(node) {\n\tnode.textContent = '';\n}\n\n/**\n * Returns `true` if we're updating the current block, for example `condition` in\n * an `{#if condition}` block just changed. In this case, the branch should be\n * appended (or removed) at the same time as other updates within the\n * current `<svelte:boundary>`\n */\nexport function should_defer_append() {\n\tif (!async_mode_flag) return false;\n\tif (eager_block_effects !== null) return false;\n\n\tvar flags = /** @type {Effect} */ (active_effect).f;\n\treturn (flags & REACTION_RAN) !== 0;\n}\n\n/**\n * 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 (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\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\treturn document.createDocumentFragment();\n}\n\n/**\n * @param {string} data\n * @returns\n */\nexport function create_comment(data = '') {\n\treturn document.createComment(data);\n}\n\n/**\n * @param {Element} element\n * @param {string} key\n * @param {string} value\n * @returns\n */\nexport function set_attribute(element, key, value = '') {\n\tif (key.startsWith('xlink:')) {\n\t\telement.setAttributeNS('http://www.w3.org/1999/xlink', key, value);\n\t\treturn;\n\t}\n\treturn element.setAttribute(key, value);\n}\n\n/**\n * Browsers split text nodes larger than 65536 bytes when parsing.\n * For hydration to succeed, we need to stitch them back together\n * @param {Text} text\n */\nexport function merge_text_nodes(text) {\n\tif (/** @type {string} */ (text.nodeValue).length < 65536) {\n\t\treturn;\n\t}\n\n\tlet next = text.nextSibling;\n\n\twhile (next !== null && next.nodeType === TEXT_NODE) {\n\t\tnext.remove();\n\n\t\t/** @type {string} */ (text.nodeValue) += /** @type {string} */ (next.nodeValue);\n\n\t\tnext = text.nextSibling;\n\t}\n}\n","/** @import { Derived, 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 {\n\tERROR_VALUE,\n\tBOUNDARY_EFFECT,\n\tREACTION_RAN,\n\tEFFECT,\n\tDESTROYED,\n\tDESTROYING\n} from './constants.js';\nimport { define_property, get_descriptor } from '../shared/utils.js';\nimport { active_effect, active_reaction } from './runtime.js';\n\nconst adjustments = new WeakMap();\n\n/**\n * @param {unknown} error\n */\nexport function handle_error(error) {\n\tvar effect = active_effect;\n\n\t// for unowned deriveds, don't throw until we read the value\n\tif (effect === null) {\n\t\t/** @type {Derived} */ (active_reaction).f |= ERROR_VALUE;\n\t\treturn error;\n\t}\n\n\tif (DEV && error instanceof Error && !adjustments.has(error)) {\n\t\tadjustments.set(error, get_adjustments(error, effect));\n\t}\n\n\t// if the error occurred while creating this subtree, we let it\n\t// bubble up until it hits a boundary that can handle it, unless\n\t// it's an $effect in which case it doesn't run immediately\n\tif ((effect.f & REACTION_RAN) === 0 && (effect.f & EFFECT) === 0) {\n\t\tif (DEV && !effect.parent && error instanceof Error) {\n\t\t\tapply_adjustments(error);\n\t\t}\n\n\t\tthrow error;\n\t}\n\n\t// otherwise we bubble up the effect tree ourselves\n\tinvoke_error_boundary(error, effect);\n}\n\n/**\n * @param {unknown} error\n * @param {Effect | null} effect\n */\nexport function invoke_error_boundary(error, effect) {\n\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 { Blocker, ComponentContext, ComponentContextLegacy, Derived, Effect, TemplateNode, TransitionManager } from '#client' */\nimport {\n\tis_dirty,\n\tactive_effect,\n\tactive_reaction,\n\tupdate_effect,\n\tget,\n\tis_destroying_effect,\n\tremove_reactions,\n\tset_active_reaction,\n\tset_is_destroying_effect,\n\tuntrack,\n\tuntracking,\n\tset_active_effect\n} from '../runtime.js';\nimport {\n\tDIRTY,\n\tBRANCH_EFFECT,\n\tRENDER_EFFECT,\n\tEFFECT,\n\tDESTROYED,\n\tINERT,\n\tBLOCK_EFFECT,\n\tROOT_EFFECT,\n\tEFFECT_TRANSPARENT,\n\tDERIVED,\n\tCLEAN,\n\tEAGER_EFFECT,\n\tHEAD_EFFECT,\n\tMAYBE_DIRTY,\n\tEFFECT_PRESERVED,\n\tSTALE_REACTION,\n\tUSER_EFFECT,\n\tASYNC,\n\tCONNECTED,\n\tMANAGED_EFFECT,\n\tDESTROYING,\n\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 } from '../dom/operations.js';\nimport { component_context, dev_current_component_function, dev_stack } from '../context.js';\nimport { Batch, collected_effects, current_batch } from './batch.js';\nimport { flatten } from './async.js';\nimport { without_reactive_context } from '../dom/elements/bindings/shared.js';\nimport { set_signal_status } from './status.js';\n\n/**\n * @param {'$effect' | '$effect.pre' | '$inspect'} rune\n */\nexport function validate_effect(rune) {\n\tif (active_effect === null) {\n\t\tif (active_reaction === null) {\n\t\t\te.effect_orphan(rune);\n\t\t}\n\n\t\te.effect_in_unowned_derived();\n\t}\n\n\tif (is_destroying_effect) {\n\t\te.effect_in_teardown(rune);\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {Effect} parent_effect\n */\nfunction push_effect(effect, parent_effect) {\n\tvar parent_last = parent_effect.last;\n\tif (parent_last === null) {\n\t\tparent_effect.last = parent_effect.first = effect;\n\t} else {\n\t\tparent_last.next = effect;\n\t\teffect.prev = parent_last;\n\t\tparent_effect.last = effect;\n\t}\n}\n\n/**\n * @param {number} type\n * @param {null | (() => void | (() => void))} fn\n * @returns {Effect}\n */\nfunction create_effect(type, fn) {\n\tvar parent = active_effect;\n\n\tif (DEV) {\n\t\t// Ensure the parent is never an inspect effect\n\t\twhile (parent !== null && (parent.f & EAGER_EFFECT) !== 0) {\n\t\t\tparent = parent.parent;\n\t\t}\n\t}\n\n\tif (parent !== null && (parent.f & INERT) !== 0) {\n\t\ttype |= INERT;\n\t}\n\n\t/** @type {Effect} */\n\tvar effect = {\n\t\tctx: component_context,\n\t\tdeps: null,\n\t\tnodes: null,\n\t\tf: type | DIRTY | CONNECTED,\n\t\tfirst: null,\n\t\tfn,\n\t\tlast: null,\n\t\tnext: null,\n\t\tparent,\n\t\tb: parent && parent.b,\n\t\tprev: null,\n\t\tteardown: null,\n\t\twv: 0,\n\t\tac: null\n\t};\n\n\tif (DEV) {\n\t\teffect.component_function = dev_current_component_function;\n\t}\n\n\tcurrent_batch?.register_created_effect(effect);\n\n\t/** @type {Effect | null} */\n\tvar e = effect;\n\n\tif ((type & EFFECT) !== 0) {\n\t\tif (collected_effects !== null) {\n\t\t\t// created during traversal — collect and run afterwards\n\t\t\tcollected_effects.push(effect);\n\t\t} else {\n\t\t\t// schedule for later\n\t\t\tBatch.ensure().schedule(effect);\n\t\t}\n\t} else if (fn !== null) {\n\t\ttry {\n\t\t\tupdate_effect(effect);\n\t\t} catch (e) {\n\t\t\tdestroy_effect(effect);\n\t\t\tthrow e;\n\t\t}\n\n\t\t// if an effect doesn't need to be kept in the tree (because it\n\t\t// won't re-run, has no DOM, and has no teardown etc)\n\t\t// then we skip it and go to its child (if any)\n\t\tif (\n\t\t\te.deps === null &&\n\t\t\te.teardown === null &&\n\t\t\te.nodes === null &&\n\t\t\te.first === e.last && // either `null`, or a singular child\n\t\t\t(e.f & EFFECT_PRESERVED) === 0\n\t\t) {\n\t\t\te = e.first;\n\t\t\tif ((type & BLOCK_EFFECT) !== 0 && (type & EFFECT_TRANSPARENT) !== 0 && e !== null) {\n\t\t\t\te.f |= EFFECT_TRANSPARENT;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (e !== null) {\n\t\te.parent = parent;\n\n\t\tif (parent !== null) {\n\t\t\tpush_effect(e, parent);\n\t\t}\n\n\t\t// if we're in a derived, add the effect there too\n\t\tif (\n\t\t\tactive_reaction !== null &&\n\t\t\t(active_reaction.f & DERIVED) !== 0 &&\n\t\t\t(type & ROOT_EFFECT) === 0\n\t\t) {\n\t\t\tvar derived = /** @type {Derived} */ (active_reaction);\n\t\t\t(derived.effects ??= []).push(e);\n\t\t}\n\t}\n\n\treturn effect;\n}\n\n/**\n * Internal representation of `$effect.tracking()`\n * @returns {boolean}\n */\nexport function effect_tracking() {\n\treturn active_reaction !== null && !untracking;\n}\n\n/**\n * @param {() => void} fn\n */\nexport function teardown(fn) {\n\tconst effect = create_effect(RENDER_EFFECT, null);\n\tset_signal_status(effect, CLEAN);\n\teffect.teardown = fn;\n\treturn effect;\n}\n\n/**\n * Internal representation of `$effect(...)`\n * @param {() => void | (() => void)} fn\n */\nexport function user_effect(fn) {\n\tvalidate_effect('$effect');\n\n\tif (DEV) {\n\t\tdefine_property(fn, 'name', {\n\t\t\tvalue: '$effect'\n\t\t});\n\t}\n\n\t// Non-nested `$effect(...)` in a component should be deferred\n\t// until the component is mounted\n\tvar flags = /** @type {Effect} */ (active_effect).f;\n\tvar defer =\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.deps !== null) {\n\t\t\t\tset_signal_status(effect, MAYBE_DIRTY);\n\t\t\t}\n\n\t\t\tif (is_dirty(effect)) {\n\t\t\t\tupdate_effect(effect);\n\t\t\t}\n\n\t\t\ttoken.ran = false;\n\t\t}\n\t});\n}\n\n/**\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function async_effect(fn) {\n\treturn create_effect(ASYNC | EFFECT_PRESERVED, fn);\n}\n\n/**\n * @param {() => void | (() => void)} fn\n * @returns {Effect}\n */\nexport function render_effect(fn, flags = 0) {\n\treturn create_effect(RENDER_EFFECT | flags, fn);\n}\n\n/**\n * @param {(...expressions: any) => void | (() => void)} fn\n * @param {Array<() => any>} sync\n * @param {Array<() => Promise<any>>} async\n * @param {Blocker[]} blockers\n */\nexport function template_effect(fn, sync = [], async = [], blockers = []) {\n\tflatten(blockers, sync, async, (values) => {\n\t\tcreate_effect(RENDER_EFFECT, () => {\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_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);\n\t\t\tset_active_reaction(previous_reaction);\n\t\t}\n\t}\n}\n\n/**\n * @param {Effect} signal\n * @param {boolean} remove_dom\n * @returns {void}\n */\nexport function destroy_effect_children(signal, remove_dom = false) {\n\tvar effect = signal.first;\n\tsignal.first = signal.last = null;\n\n\twhile (effect !== null) {\n\t\tconst controller = effect.ac;\n\n\t\tif (controller !== null) {\n\t\t\twithout_reactive_context(() => {\n\t\t\t\tcontroller.abort(STALE_REACTION);\n\t\t\t});\n\t\t}\n\n\t\tvar next = effect.next;\n\n\t\tif ((effect.f & ROOT_EFFECT) !== 0) {\n\t\t\t// this is now an independent root\n\t\t\teffect.parent = null;\n\t\t} else {\n\t\t\tdestroy_effect(effect, remove_dom);\n\t\t}\n\n\t\teffect = next;\n\t}\n}\n\n/**\n * @param {Effect} signal\n * @returns {void}\n */\nexport function destroy_block_effect_children(signal) {\n\tvar effect = signal.first;\n\n\twhile (effect !== null) {\n\t\tvar next = effect.next;\n\t\tif ((effect.f & BRANCH_EFFECT) === 0) {\n\t\t\tdestroy_effect(effect);\n\t\t}\n\t\teffect = next;\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {boolean} [remove_dom]\n * @returns {void}\n */\nexport function destroy_effect(effect, remove_dom = true) {\n\tvar removed = false;\n\n\tif (\n\t\t(remove_dom || (effect.f & HEAD_EFFECT) !== 0) &&\n\t\teffect.nodes !== null &&\n\t\teffect.nodes.end !== null\n\t) {\n\t\tremove_effect_dom(effect.nodes.start, /** @type {TemplateNode} */ (effect.nodes.end));\n\t\tremoved = true;\n\t}\n\n\teffect.f |= DESTROYING;\n\tdestroy_effect_children(effect, remove_dom && !removed);\n\tremove_reactions(effect, 0);\n\n\tvar transitions = effect.nodes && effect.nodes.t;\n\n\tif (transitions !== null) {\n\t\tfor (const transition of transitions) {\n\t\t\ttransition.stop();\n\t\t}\n\t}\n\n\texecute_effect_teardown(effect);\n\n\teffect.f ^= DESTROYING;\n\teffect.f |= DESTROYED;\n\n\tvar parent = effect.parent;\n\n\t// If the parent doesn't have any children, then skip this work altogether\n\tif (parent !== null && parent.first !== null) {\n\t\tunlink_effect(effect);\n\t}\n\n\tif (DEV) {\n\t\teffect.component_function = null;\n\t}\n\n\t// `first` and `child` are nulled out in destroy_effect_children\n\t// we don't null out `parent` so that error propagation can work correctly\n\teffect.next =\n\t\teffect.prev =\n\t\teffect.teardown =\n\t\teffect.ctx =\n\t\teffect.deps =\n\t\teffect.fn =\n\t\teffect.nodes =\n\t\teffect.ac =\n\t\teffect.b =\n\t\t\tnull;\n}\n\n/**\n *\n * @param {TemplateNode | null} node\n * @param {TemplateNode} end\n */\nexport function remove_effect_dom(node, end) {\n\twhile (node !== null) {\n\t\t/** @type {TemplateNode | null} */\n\t\tvar next = node === end ? null : get_next_sibling(node);\n\n\t\tnode.remove();\n\t\tnode = next;\n\t}\n}\n\n/**\n * Detach an effect from the effect tree, freeing up memory and\n * reducing the amount of work that happens on subsequent traversals\n * @param {Effect} effect\n */\nexport function unlink_effect(effect) {\n\tvar parent = effect.parent;\n\tvar prev = effect.prev;\n\tvar next = effect.next;\n\n\tif (prev !== null) prev.next = next;\n\tif (next !== null) next.prev = prev;\n\n\tif (parent !== null) {\n\t\tif (parent.first === effect) parent.first = next;\n\t\tif (parent.last === effect) parent.last = prev;\n\t}\n}\n\n/**\n * When a block effect is removed, we don't immediately destroy it or yank it\n * out of the DOM, because it might have transitions. Instead, we 'pause' it.\n * It stays around (in memory, and in the DOM) until outro transitions have\n * completed, and if the state change is reversed then we _resume_ it.\n * A paused effect does not update, and the DOM subtree becomes inert.\n * @param {Effect} effect\n * @param {() => void} [callback]\n * @param {boolean} [destroy]\n */\nexport function pause_effect(effect, callback, destroy = true) {\n\t/** @type {TransitionManager[]} */\n\tvar transitions = [];\n\n\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\tif (remaining > 0) {\n\t\tvar check = () => --remaining || fn();\n\t\tfor (var transition of transitions) {\n\t\t\ttransition.out(check);\n\t\t}\n\t} else {\n\t\tfn();\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @param {TransitionManager[]} transitions\n * @param {boolean} local\n */\nfunction pause_children(effect, transitions, local) {\n\tif ((effect.f & INERT) !== 0) return;\n\teffect.f ^= INERT;\n\n\tvar t = effect.nodes && effect.nodes.t;\n\n\tif (t !== null) {\n\t\tfor (const transition of t) {\n\t\t\tif (transition.is_global || local) {\n\t\t\t\ttransitions.push(transition);\n\t\t\t}\n\t\t}\n\t}\n\n\tvar child = effect.first;\n\n\twhile (child !== null) {\n\t\tvar sibling = child.next;\n\n\t\t// If this child is a root effect, then it will become an independent root when its parent\n\t\t// is destroyed, it should therefore not become inert nor partake in transitions.\n\t\tif ((child.f & ROOT_EFFECT) === 0) {\n\t\t\tvar transparent =\n\t\t\t\t(child.f & EFFECT_TRANSPARENT) !== 0 ||\n\t\t\t\t// If this is a branch effect without a block effect parent,\n\t\t\t\t// it means the parent block effect was pruned. In that case,\n\t\t\t\t// transparency information was transferred to the branch effect.\n\t\t\t\t((child.f & BRANCH_EFFECT) !== 0 && (effect.f & BLOCK_EFFECT) !== 0);\n\t\t\t// TODO we don't need to call pause_children recursively with a linked list in place\n\t\t\t// it's slightly more involved though as we have to account for `transparent` changing\n\t\t\t// through the tree.\n\t\t\tpause_children(child, transitions, transparent ? local : false);\n\t\t}\n\n\t\tchild = sibling;\n\t}\n}\n\n/**\n * The opposite of `pause_effect`. We call this if (for example)\n * `x` becomes falsy then truthy: `{#if x}...{/if}`\n * @param {Effect} effect\n */\nexport function resume_effect(effect) {\n\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 changed while it was paused,\n\t// schedule the effect to update. we don't use `is_dirty`\n\t// here because we don't want to eagerly recompute a derived like\n\t// `{#if foo}{foo.bar()}{/if}` if `foo` is now `undefined\n\tif ((effect.f & CLEAN) === 0) {\n\t\tset_signal_status(effect, DIRTY);\n\t\tBatch.ensure().schedule(effect); // Assumption: This happens during the commit phase of the batch, causing another flush, but it's safe\n\t}\n\n\tvar child = effect.first;\n\n\twhile (child !== null) {\n\t\tvar sibling = child.next;\n\t\tvar transparent = (child.f & EFFECT_TRANSPARENT) !== 0 || (child.f & BRANCH_EFFECT) !== 0;\n\t\t// TODO we don't need to call resume_children recursively with a linked list in place\n\t\t// it's slightly more involved though as we have to account for `transparent` changing\n\t\t// through the tree.\n\t\tresume_children(child, transparent ? local : false);\n\t\tchild = sibling;\n\t}\n\n\tvar t = effect.nodes && effect.nodes.t;\n\n\tif (t !== null) {\n\t\tfor (const transition of t) {\n\t\t\tif (transition.is_global || local) {\n\t\t\t\ttransition.in();\n\t\t\t}\n\t\t}\n\t}\n}\n\nexport function aborted(effect = /** @type {Effect} */ (active_effect)) {\n\treturn (effect.f & DESTROYED) !== 0;\n}\n\n/**\n * @param {Effect} effect\n * @param {DocumentFragment} fragment\n */\nexport function move_effect(effect, fragment) {\n\tif (!effect.nodes) return;\n\n\t/** @type {TemplateNode | null} */\n\tvar node = effect.nodes.start;\n\tvar end = effect.nodes.end;\n\n\twhile (node !== null) {\n\t\t/** @type {TemplateNode | null} */\n\t\tvar next = node === end ? null : get_next_sibling(node);\n\n\t\tfragment.append(node);\n\t\tnode = next;\n\t}\n}\n","/** @import { Value } from '#client' */\nimport { internal_set } from './reactivity/sources.js';\nimport { untrack } from './runtime.js';\n\n/**\n * @type {Set<Value> | null}\n * @deprecated\n */\nexport let captured_signals = null;\n\n/**\n * Capture an array of all the signals that are read when `fn` is called\n * @template T\n * @param {() => T} fn\n */\nfunction capture_signals(fn) {\n\tvar previous_captured_signals = captured_signals;\n\n\ttry {\n\t\tcaptured_signals = new Set();\n\n\t\tuntrack(fn);\n\n\t\tif (previous_captured_signals !== null) {\n\t\t\tfor (var signal of captured_signals) {\n\t\t\t\tprevious_captured_signals.add(signal);\n\t\t\t}\n\t\t}\n\n\t\treturn captured_signals;\n\t} finally {\n\t\tcaptured_signals = previous_captured_signals;\n\t}\n}\n\n/**\n * Invokes a function and captures all signals that are read during the invocation,\n * then invalidates them.\n * @param {() => any} fn\n * @deprecated\n */\nexport function invalidate_inner_signals(fn) {\n\tfor (var signal of capture_signals(fn)) {\n\t\tinternal_set(signal, signal.v);\n\t}\n}\n","/** @import { Derived, Effect, Reaction, Source, Value } from '#client' */\nimport { DEV } from 'esm-env';\nimport { get_descriptors, get_prototype_of, includes, index_of } from '../shared/utils.js';\nimport {\n\tdestroy_block_effect_children,\n\tdestroy_effect_children,\n\teffect_tracking,\n\texecute_effect_teardown\n} from './reactivity/effects.js';\nimport {\n\tDIRTY,\n\tMAYBE_DIRTY,\n\tCLEAN,\n\tDERIVED,\n\tDESTROYED,\n\tBRANCH_EFFECT,\n\tSTATE_SYMBOL,\n\tBLOCK_EFFECT,\n\tROOT_EFFECT,\n\tCONNECTED,\n\tREACTION_IS_UPDATING,\n\tSTALE_REACTION,\n\tERROR_VALUE,\n\tMANAGED_EFFECT,\n\tREACTION_RAN\n} from './constants.js';\nimport { old_values } from './reactivity/sources.js';\nimport {\n\treactivity_loss_tracker,\n\texecute_derived,\n\tfreeze_derived_effects,\n\trecent_async_deriveds,\n\tunfreeze_derived_effects,\n\tupdate_derived\n} from './reactivity/deriveds.js';\nimport { async_mode_flag, tracing_mode_flag } from '../flags/index.js';\nimport { tracing_expressions } from './dev/tracing.js';\nimport { get_error } from '../shared/dev.js';\nimport {\n\tcomponent_context,\n\tdev_current_component_function,\n\tdev_stack,\n\tis_runes,\n\tset_component_context,\n\tset_dev_current_component_function,\n\tset_dev_stack\n} from './context.js';\nimport {\n\tBatch,\n\tbatch_values,\n\tcurrent_batch,\n\tflushSync,\n\tprevious_batch,\n\tschedule_effect\n} from './reactivity/batch.js';\nimport { handle_error } from './error-handling.js';\nimport { UNINITIALIZED } from '../../constants.js';\nimport { captured_signals } from './legacy.js';\nimport { without_reactive_context } from './dom/elements/bindings/shared.js';\nimport { set_signal_status, update_derived_status } from './reactivity/status.js';\nimport * as w from './warnings.js';\n\nexport let is_destroying_effect = false;\n\n/** @param {boolean} value */\nexport function set_is_destroying_effect(value) {\n\tis_destroying_effect = value;\n}\n\n/** @type {null | Reaction} */\nexport let active_reaction = null;\n\nexport let untracking = false;\n\n/** @param {null | Reaction} reaction */\nexport function set_active_reaction(reaction) {\n\tactive_reaction = reaction;\n}\n\n/** @type {null | Effect} */\nexport let active_effect = null;\n\n/** @param {null | Effect} effect */\nexport function set_active_effect(effect) {\n\tactive_effect = effect;\n}\n\n/**\n * When sources are created within a reaction, reading and writing\n * them within that reaction should not cause a re-run\n * @type {null | 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.\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 * Determines whether a derived or effect is dirty.\n * If it is MAYBE_DIRTY, will set the status to CLEAN\n * @param {Reaction} reaction\n * @returns {boolean}\n */\nexport function is_dirty(reaction) {\n\tvar flags = reaction.f;\n\n\tif ((flags & DIRTY) !== 0) {\n\t\treturn true;\n\t}\n\n\tif ((flags & MAYBE_DIRTY) !== 0) {\n\t\tvar dependencies = /** @type {Value[]} */ (reaction.deps);\n\t\tvar length = dependencies.length;\n\n\t\tfor (var i = 0; i < length; i++) {\n\t\t\tvar dependency = dependencies[i];\n\n\t\t\tif (is_dirty(/** @type {Derived} */ (dependency))) {\n\t\t\t\tupdate_derived(/** @type {Derived} */ (dependency));\n\t\t\t}\n\n\t\t\tif (dependency.wv > reaction.wv) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tif (\n\t\t\t(flags & CONNECTED) !== 0 &&\n\t\t\t// During time traveling we don't want to reset the status so that\n\t\t\t// traversal of the graph in the other batches still happens\n\t\t\tbatch_values === null\n\t\t) {\n\t\t\tset_signal_status(reaction, CLEAN);\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * @param {Value} signal\n * @param {Effect} effect\n * @param {boolean} [root]\n */\nfunction schedule_possible_effect_self_invalidation(signal, effect, root = true) {\n\tvar reactions = signal.reactions;\n\tif (reactions === null) return;\n\n\tif (!async_mode_flag && current_sources !== null && 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\tif (root) {\n\t\t\t\tset_signal_status(reaction, DIRTY);\n\t\t\t} else if ((reaction.f & CLEAN) !== 0) {\n\t\t\t\tset_signal_status(reaction, MAYBE_DIRTY);\n\t\t\t}\n\t\t\tschedule_effect(/** @type {Effect} */ (reaction));\n\t\t}\n\t}\n}\n\n/** @param {Reaction} reaction */\nexport function update_reaction(reaction) {\n\tvar previous_deps = new_deps;\n\tvar previous_skipped_deps = skipped_deps;\n\tvar previous_untracked_writes = untracked_writes;\n\tvar previous_reaction = active_reaction;\n\tvar previous_sources = current_sources;\n\tvar previous_component_context = component_context;\n\tvar previous_untracking = untracking;\n\tvar previous_update_version = update_version;\n\n\tvar flags = reaction.f;\n\n\tnew_deps = /** @type {null | Value[]} */ (null);\n\tskipped_deps = 0;\n\tuntracked_writes = null;\n\tactive_reaction = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null;\n\n\tcurrent_sources = null;\n\tset_component_context(reaction.ctx);\n\tuntracking = false;\n\tupdate_version = ++read_version;\n\n\tif (reaction.ac !== null) {\n\t\twithout_reactive_context(() => {\n\t\t\t/** @type {AbortController} */ (reaction.ac).abort(STALE_REACTION);\n\t\t});\n\n\t\treaction.ac = null;\n\t}\n\n\ttry {\n\t\treaction.f |= REACTION_IS_UPDATING;\n\t\tvar fn = /** @type {Function} */ (reaction.fn);\n\t\tvar result = fn();\n\t\treaction.f |= REACTION_RAN;\n\t\tvar deps = update_dependencies(reaction);\n\n\t\t// If we're inside an effect and we have untracked writes, then we need to\n\t\t// ensure that if any of those untracked writes result in re-invalidation\n\t\t// of the current effect, then that happens accordingly\n\t\tif (\n\t\t\tis_runes() &&\n\t\t\tuntracked_writes !== null &&\n\t\t\t!untracking &&\n\t\t\tdeps !== null &&\n\t\t\t(reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0\n\t\t) {\n\t\t\tfor (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\tif ((reaction.f & ERROR_VALUE) !== 0) {\n\t\t\treaction.f ^= ERROR_VALUE;\n\t\t}\n\n\t\treturn result;\n\t} catch (error) {\n\t\t// still commit the deps read before the throw, otherwise deriveds connected by this run keep no reader and the reaction never re-runs when they change\n\t\tupdate_dependencies(reaction);\n\n\t\treturn handle_error(error);\n\t} finally {\n\t\treaction.f ^= REACTION_IS_UPDATING;\n\t\tnew_deps = previous_deps;\n\t\tskipped_deps = previous_skipped_deps;\n\t\tuntracked_writes = previous_untracked_writes;\n\t\tactive_reaction = previous_reaction;\n\t\tcurrent_sources = previous_sources;\n\t\tset_component_context(previous_component_context);\n\t\tuntracking = previous_untracking;\n\t\tupdate_version = previous_update_version;\n\t}\n}\n\n/**\n * @param {Reaction} reaction\n */\nfunction update_dependencies(reaction) {\n\tvar deps = reaction.deps;\n\n\t// Don't remove reactions during fork;\n\t// they must remain for when fork is discarded\n\tvar is_fork = current_batch?.is_fork;\n\n\tif (new_deps !== null) {\n\t\tvar i;\n\n\t\tif (!is_fork) {\n\t\t\tremove_reactions(reaction, skipped_deps);\n\t\t}\n\n\t\tif (deps !== null && skipped_deps > 0) {\n\t\t\tdeps.length = skipped_deps + new_deps.length;\n\t\t\tfor (i = 0; i < new_deps.length; i++) {\n\t\t\t\tdeps[skipped_deps + i] = new_deps[i];\n\t\t\t}\n\t\t} else {\n\t\t\treaction.deps = deps = new_deps;\n\t\t}\n\n\t\tif (effect_tracking() && (reaction.f & CONNECTED) !== 0) {\n\t\t\tfor (i = skipped_deps; i < deps.length; i++) {\n\t\t\t\t(deps[i].reactions ??= []).push(reaction);\n\t\t\t}\n\t\t}\n\t} else if (!is_fork && deps !== null && skipped_deps < deps.length) {\n\t\tremove_reactions(reaction, skipped_deps);\n\t\tdeps.length = skipped_deps;\n\t}\n\n\treturn deps;\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\n\t\tif (derived.ac !== null) {\n\t\t\twithout_reactive_context(() => {\n\t\t\t\t/** @type {AbortController} */ (derived.ac).abort(STALE_REACTION);\n\t\t\t\tderived.ac = null;\n\t\t\t\t// ensure it reruns right away next time instead of potentially returning a rejected promise as its value\n\t\t\t\tset_signal_status(derived, DIRTY);\n\t\t\t});\n\t\t}\n\n\t\t// freeze any effects inside this derived\n\t\tfreeze_derived_effects(derived);\n\n\t\t// Disconnect any reactions owned by this reaction\n\t\tremove_reactions(derived, 0);\n\t}\n}\n\n/**\n * @param {Reaction} signal\n * @param {number} start_index\n * @returns {void}\n */\nexport function remove_reactions(signal, start_index) {\n\tvar dependencies = signal.deps;\n\tif (dependencies === null) return;\n\n\tfor (var i = start_index; i < dependencies.length; i++) {\n\t\tremove_reaction(signal, dependencies[i]);\n\t}\n}\n\n/**\n * @param {Effect} effect\n * @returns {void}\n */\nexport function update_effect(effect) {\n\tvar flags = effect.f;\n\n\tif ((flags & DESTROYED) !== 0) {\n\t\treturn;\n\t}\n\n\tset_signal_status(effect, CLEAN);\n\n\tvar previous_effect = active_effect;\n\n\tactive_effect = effect;\n\n\tif (DEV) {\n\t\tvar previous_component_fn = dev_current_component_function;\n\t\tset_dev_current_component_function(effect.component_function);\n\t\tvar previous_stack = /** @type {any} */ (dev_stack);\n\t\t// only block effects have a dev stack, keep the current one otherwise\n\t\tset_dev_stack(effect.dev_stack ?? dev_stack);\n\t}\n\n\ttry {\n\t\tif ((flags & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) {\n\t\t\tdestroy_block_effect_children(effect);\n\t\t} else {\n\t\t\tdestroy_effect_children(effect);\n\t\t}\n\n\t\texecute_effect_teardown(effect);\n\t\tvar teardown = update_reaction(effect);\n\t\teffect.teardown = typeof teardown === 'function' ? teardown : null;\n\t\teffect.wv = write_version;\n\n\t\t// In DEV, increment versions of any sources that were written to during the effect,\n\t\t// so that they are correctly marked as dirty when the effect re-runs\n\t\tif (DEV && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.deps !== null) {\n\t\t\tfor (var dep of effect.deps) {\n\t\t\t\tif (dep.set_during_effect) {\n\t\t\t\t\tdep.wv = increment_write_version();\n\t\t\t\t\tdep.set_during_effect = false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tactive_effect = previous_effect;\n\n\t\tif (DEV) {\n\t\t\tset_dev_current_component_function(previous_component_fn);\n\t\t\tset_dev_stack(previous_stack);\n\t\t}\n\t}\n}\n\n/**\n * Returns a promise that resolves once any pending state changes have been applied.\n * @returns {Promise<void>}\n */\nexport async function tick() {\n\tif (async_mode_flag) {\n\t\treturn new Promise((f) => {\n\t\t\t// Race them against each other - in almost all cases requestAnimationFrame will fire first,\n\t\t\t// but e.g. in case the window is not focused or a view transition happens, requestAnimationFrame\n\t\t\t// will be delayed and setTimeout helps us resolve fast enough in that case\n\t\t\trequestAnimationFrame(() => f());\n\t\t\tsetTimeout(() => f());\n\t\t});\n\t}\n\n\tawait Promise.resolve();\n\n\t// By calling flushSync we guarantee that any pending state changes are applied after one tick.\n\t// TODO look into whether we can make flushing subsequent updates synchronously in the future.\n\tflushSync();\n}\n\n/**\n * Returns a promise that resolves once any state changes, and asynchronous work resulting from them,\n * have resolved and the DOM has been updated\n * @returns {Promise<void>}\n * @since 5.36\n */\nexport function settled() {\n\treturn Batch.ensure().settled();\n}\n\n/**\n * @template V\n * @param {Value<V>} signal\n * @returns {V}\n */\nexport function get(signal) {\n\tvar flags = signal.f;\n\tvar is_derived = (flags & DERIVED) !== 0;\n\n\tcaptured_signals?.add(signal);\n\n\t// Register the dependency on the current reaction signal.\n\tif (active_reaction !== null && !untracking) {\n\t\t// if we're in a derived that is being read inside an _async_ derived,\n\t\t// it's possible that the effect was already destroyed. In this case,\n\t\t// we don't add the dependency, because that would create a memory leak\n\t\tvar destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0;\n\n\t\tif (!destroyed && (current_sources === null || !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\t// We're adding a dependency outside the init/update cycle (i.e. after an `await`).\n\t\t\t\t// We have to deduplicate deps/reactions in this case or remove_reactions could\n\t\t\t\t// disconnect deps/reactions that are actually still in use (if skip_deps says\n\t\t\t\t// \"disconnect all after this index\" and some of the signals are also present in\n\t\t\t\t// list prior to the cutoff index, i.e. that should be kept).\n\t\t\t\tactive_reaction.deps ??= [];\n\t\t\t\tif (!includes.call(active_reaction.deps, signal)) {\n\t\t\t\t\tactive_reaction.deps.push(signal);\n\t\t\t\t}\n\n\t\t\t\tvar reactions = signal.reactions;\n\n\t\t\t\tif (reactions === null) {\n\t\t\t\t\tsignal.reactions = [active_reaction];\n\t\t\t\t} else if (!includes.call(reactions, active_reaction)) {\n\t\t\t\t\treactions.push(active_reaction);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (DEV) {\n\t\tif (\n\t\t\t!untracking &&\n\t\t\treactivity_loss_tracker &&\n\t\t\t// By checking that current/previous batch are null 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\tcurrent_batch === null &&\n\t\t\tprevious_batch === null &&\n\t\t\t!reactivity_loss_tracker.warned &&\n\t\t\t(reactivity_loss_tracker.effect.f & REACTION_IS_UPDATING) === 0 &&\n\t\t\t!reactivity_loss_tracker.effect_deps.has(signal)\n\t\t) {\n\t\t\treactivity_loss_tracker.warned = true;\n\n\t\t\tw.await_reactivity_loss(/** @type {string} */ (signal.label));\n\n\t\t\tvar trace = get_error('traced at');\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tif (trace) console.warn(trace);\n\t\t}\n\n\t\trecent_async_deriveds.delete(signal);\n\n\t\tif (\n\t\t\ttracing_mode_flag &&\n\t\t\t!untracking &&\n\t\t\ttracing_expressions !== null &&\n\t\t\tactive_reaction !== null &&\n\t\t\ttracing_expressions.reaction === active_reaction\n\t\t) {\n\t\t\t// Used when mapping state between special blocks like `each`\n\t\t\tif (signal.trace) {\n\t\t\t\tsignal.trace();\n\t\t\t} else {\n\t\t\t\ttrace = get_error('traced at');\n\n\t\t\t\tif (trace) {\n\t\t\t\t\tvar entry = tracing_expressions.entries.get(signal);\n\n\t\t\t\t\tif (entry === undefined) {\n\t\t\t\t\t\tentry = { traces: [] };\n\t\t\t\t\t\ttracing_expressions.entries.set(signal, entry);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar last = entry.traces[entry.traces.length - 1];\n\n\t\t\t\t\t// traces can be duplicated, e.g. by `snapshot` invoking both\n\t\t\t\t\t// both `getOwnPropertyDescriptor` and `get` traps at once\n\t\t\t\t\tif (trace.stack !== last?.stack) {\n\t\t\t\t\t\tentry.traces.push(trace);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif (is_destroying_effect && old_values.has(signal)) {\n\t\treturn old_values.get(signal);\n\t}\n\n\tif (is_derived) {\n\t\tvar derived = /** @type {Derived} */ (signal);\n\n\t\tif (is_destroying_effect) {\n\t\t\tvar value = derived.v;\n\n\t\t\t// if the derived is dirty and has reactions, or depends on the values that just changed, re-execute\n\t\t\t// (a derived can be maybe_dirty due to the effect destroy removing its last reaction)\n\t\t\tif (\n\t\t\t\t((derived.f & CLEAN) === 0 && derived.reactions !== null) ||\n\t\t\t\tdepends_on_old_values(derived)\n\t\t\t) {\n\t\t\t\tvalue = execute_derived(derived);\n\t\t\t}\n\n\t\t\told_values.set(derived, value);\n\n\t\t\treturn value;\n\t\t}\n\n\t\t// connect disconnected deriveds 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 (is_dirty(derived)) {\n\t\t\tif (should_connect) {\n\t\t\t\t// set the flag before `update_derived`, so that the derived\n\t\t\t\t// is added as a reaction to its dependencies\n\t\t\t\tderived.f |= CONNECTED;\n\t\t\t}\n\n\t\t\tupdate_derived(derived);\n\t\t}\n\n\t\tif (should_connect && !is_new) {\n\t\t\tunfreeze_derived_effects(derived);\n\t\t\treconnect(derived);\n\t\t}\n\t}\n\n\tif (batch_values?.has(signal)) {\n\t\treturn batch_values.get(signal);\n\t}\n\n\tif ((signal.f & ERROR_VALUE) !== 0) {\n\t\tthrow signal.v;\n\t}\n\n\treturn signal.v;\n}\n\n/**\n * (Re)connect a disconnected derived, so that it is notified\n * of changes in `mark_reactions`\n * @param {Derived} derived\n */\nfunction reconnect(derived) {\n\tderived.f |= CONNECTED;\n\n\tif (derived.deps === null) return;\n\n\tfor (const dep of derived.deps) {\n\t\tvar reactions = dep.reactions;\n\n\t\tif (reactions === null) {\n\t\t\tdep.reactions = [derived];\n\t\t} else if (!includes.call(reactions, derived)) {\n\t\t\treactions.push(derived);\n\t\t}\n\n\t\tif ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) {\n\t\t\tunfreeze_derived_effects(/** @type {Derived} */ (dep));\n\t\t\treconnect(/** @type {Derived} */ (dep));\n\t\t}\n\t}\n}\n\n/** @param {Derived} derived */\nfunction depends_on_old_values(derived) {\n\tif (derived.v === UNINITIALIZED) return true; // we don't know, so assume the worst\n\tif (derived.deps === null) return false;\n\n\tfor (const dep of derived.deps) {\n\t\tif (old_values.has(dep)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif ((dep.f & DERIVED) !== 0 && depends_on_old_values(/** @type {Derived} */ (dep))) {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\treturn false;\n}\n\n/**\n * Like `get`, but checks for `undefined`. Used for `var` declarations because they can be accessed before being declared\n * @template V\n * @param {Value<V> | undefined} signal\n * @returns {V | undefined}\n */\nexport function safe_get(signal) {\n\treturn signal && get(signal);\n}\n\n/**\n * When used inside a [`$derived`](https://svelte.dev/docs/svelte/$derived) or [`$effect`](https://svelte.dev/docs/svelte/$effect),\n * any state read inside `fn` will not be treated as a dependency.\n *\n * ```ts\n * $effect(() => {\n *   // this will run when `data` changes, but not when `time` changes\n *   save(data, {\n *     timestamp: untrack(() => time)\n *   });\n * });\n * ```\n * @template T\n * @param {() => T} fn\n * @returns {T}\n */\nexport function untrack(fn) {\n\tvar previous_untracking = untracking;\n\ttry {\n\t\tuntracking = true;\n\t\treturn fn();\n\t} finally {\n\t\tuntracking = previous_untracking;\n\t}\n}\n\n/**\n * Possibly traverse an object and read all its properties so that they're all reactive in case this is `$state`.\n * Does only check first level of an object for performance reasons (heuristic should be good for 99% of all cases).\n * @param {any} value\n * @returns {void}\n */\nexport function deep_read_state(value) {\n\tif (typeof value !== 'object' || !value || value instanceof EventTarget) {\n\t\treturn;\n\t}\n\n\tif (STATE_SYMBOL in value) {\n\t\tdeep_read(value);\n\t} else if (!Array.isArray(value)) {\n\t\tfor (let key in value) {\n\t\t\tconst prop = value[key];\n\t\t\tif (typeof prop === 'object' && prop && STATE_SYMBOL in prop) {\n\t\t\t\tdeep_read(prop);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Deeply traverse an object and read all its properties\n * so that they're all reactive in case this is `$state`\n * @param {any} value\n * @param {Set<any>} visited\n * @returns {void}\n */\nexport function deep_read(value, visited = new Set()) {\n\tif (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t// We don't want to traverse DOM elements\n\t\t!(value instanceof EventTarget) &&\n\t\t!visited.has(value)\n\t) {\n\t\tvisited.add(value);\n\t\t// When working with a possible SvelteDate, this\n\t\t// will ensure we capture changes to it.\n\t\tif (value instanceof Date) {\n\t\t\tvalue.getTime();\n\t\t}\n\t\tfor (let key in value) {\n\t\t\ttry {\n\t\t\t\tdeep_read(value[key], visited);\n\t\t\t} catch (e) {\n\t\t\t\t// continue\n\t\t\t}\n\t\t}\n\t\tconst proto = get_prototype_of(value);\n\t\tif (\n\t\t\tproto !== Object.prototype &&\n\t\t\tproto !== Array.prototype &&\n\t\t\tproto !== Map.prototype &&\n\t\t\tproto !== Set.prototype &&\n\t\t\tproto !== Date.prototype\n\t\t) {\n\t\t\tconst descriptors = get_descriptors(proto);\n\t\t\tfor (let key in descriptors) {\n\t\t\t\tconst get = descriptors[key].get;\n\t\t\t\tif (get) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tget.call(value);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t// continue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n","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","/** @type {Map<String, Set<HTMLStyleElement>>} */\nvar all_styles = new Map();\n\n/**\n * @param {String} hash\n * @param {HTMLStyleElement} style\n */\nexport function register_style(hash, style) {\n\tvar styles = all_styles.get(hash);\n\n\tif (!styles) {\n\t\tstyles = new Set();\n\t\tall_styles.set(hash, styles);\n\t}\n\n\tstyles.add(style);\n}\n\n/**\n * @param {String} hash\n */\nexport function cleanup_styles(hash) {\n\tvar styles = all_styles.get(hash);\n\tif (!styles) return;\n\n\tfor (const style of styles) {\n\t\tstyle.remove();\n\t}\n\n\tall_styles.delete(hash);\n}\n","import { teardown } from '../../reactivity/effects.js';\nimport { define_property } from '../../../shared/utils.js';\nimport { hydrating } from '../hydration.js';\nimport { queue_micro_task } from '../task.js';\nimport { FILENAME } from '../../../../constants.js';\nimport * as w from '../../warnings.js';\nimport {\n\tactive_effect,\n\tactive_reaction,\n\tset_active_effect,\n\tset_active_reaction\n} from '../../runtime.js';\nimport { without_reactive_context } from './bindings/shared.js';\n\n/**\n * Used on elements, as a map of event type -> event handler,\n * and on events themselves to track which element handled an event\n */\nexport const event_symbol = Symbol('events');\n\n/** @type {Set<string>} */\nexport const all_registered_events = new Set();\n\n/** @type {Set<(events: Array<string>) => void>} */\nexport const root_event_handles = new Set();\n\n/**\n * SSR adds onload and onerror attributes to catch those events before the hydration.\n * This function detects those cases, removes the attributes and replays the events.\n * @param {HTMLElement} dom\n */\nexport function replay_events(dom) {\n\tif (!hydrating) return;\n\n\tdom.removeAttribute('onload');\n\tdom.removeAttribute('onerror');\n\t// @ts-expect-error\n\tconst event = dom.__e;\n\tif (event !== undefined) {\n\t\t// @ts-expect-error\n\t\tdom.__e = undefined;\n\t\tqueueMicrotask(() => {\n\t\t\tif (dom.isConnected) {\n\t\t\t\tdom.dispatchEvent(event);\n\t\t\t}\n\t\t});\n\t}\n}\n\n/**\n * @param {string} event_name\n * @param {EventTarget} dom\n * @param {EventListener} [handler]\n * @param {AddEventListenerOptions} [options]\n */\nexport function create_event(event_name, dom, handler, options = {}) {\n\t/**\n\t * @this {EventTarget}\n\t */\n\tfunction target_handler(/** @type {Event} */ event) {\n\t\tif (!options.capture) {\n\t\t\t// Only call in the bubble phase, else delegated events would be called before the capturing events\n\t\t\thandle_event_propagation.call(dom, event);\n\t\t}\n\t\tif (!event.cancelBubble) {\n\t\t\treturn without_reactive_context(() => {\n\t\t\t\treturn handler?.call(this, event);\n\t\t\t});\n\t\t}\n\t}\n\n\t// Chrome has a bug where pointer events don't work when attached to a DOM element that has been cloned\n\t// with cloneNode() and the DOM element is disconnected from the document. To ensure the event works, we\n\t// defer the attachment till after it's been appended to the document. TODO: remove this once Chrome fixes\n\t// this bug. The same applies to wheel events and touch events.\n\tif (\n\t\tevent_name.startsWith('pointer') ||\n\t\tevent_name.startsWith('touch') ||\n\t\tevent_name === 'wheel'\n\t) {\n\t\ttarget_handler.__removed = false;\n\t\tqueue_micro_task(() => {\n\t\t\tif (!target_handler.__removed) {\n\t\t\t\tdom.addEventListener(event_name, target_handler, options);\n\t\t\t}\n\t\t});\n\t} else {\n\t\tdom.addEventListener(event_name, target_handler, options);\n\t}\n\n\treturn target_handler;\n}\n\n/**\n * Attaches an event handler to an element and returns a function that removes the handler. Using this\n * rather than `addEventListener` will preserve the correct order relative to handlers added declaratively\n * (with attributes like `onclick`), which use event delegation for performance reasons\n *\n * @param {EventTarget} element\n * @param {string} type\n * @param {EventListener} handler\n * @param {AddEventListenerOptions} [options]\n */\nexport function on(element, type, handler, options = {}) {\n\tvar target_handler = create_event(type, element, handler, options);\n\n\treturn () => {\n\t\ttarget_handler.__removed = true;\n\t\telement.removeEventListener(type, target_handler, options);\n\t};\n}\n\n/**\n * @param {string} event_name\n * @param {Element} dom\n * @param {EventListener} [handler]\n * @param {boolean} [capture]\n * @param {boolean} [passive]\n * @returns {void}\n */\nexport function event(event_name, dom, handler, capture, passive) {\n\tvar options = { capture, passive };\n\tvar target_handler = create_event(event_name, dom, handler, options);\n\n\tif (\n\t\tdom === document.body ||\n\t\t// @ts-ignore\n\t\tdom === window ||\n\t\t// @ts-ignore\n\t\tdom === document ||\n\t\t// Firefox has quirky behavior, it can happen that we still get \"canplay\" events when the element is already removed\n\t\tdom instanceof HTMLMediaElement\n\t) {\n\t\tteardown(() => {\n\t\t\ttarget_handler.__removed = true;\n\t\t\tdom.removeEventListener(event_name, target_handler, options);\n\t\t});\n\t}\n}\n\n/**\n * @param {string} event_name\n * @param {Element} element\n * @param {EventListener} [handler]\n * @returns {void}\n */\nexport function delegated(event_name, element, handler) {\n\t// @ts-expect-error\n\t(element[event_symbol] ??= {})[event_name] = handler;\n}\n\n/**\n * @param {Array<string>} events\n * @returns {void}\n */\nexport function delegate(events) {\n\tfor (var i = 0; i < events.length; i++) {\n\t\tall_registered_events.add(events[i]);\n\t}\n\n\tfor (var fn of root_event_handles) {\n\t\tfn(events);\n\t}\n}\n\n// used to store the reference to the currently propagated event\n// to prevent garbage collection between microtasks in Firefox (<= 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\tvar handler_element = this;\n\tvar owner_document = /** @type {Node} */ (handler_element).ownerDocument;\n\tvar event_name = event.type;\n\tvar path = event.composedPath?.() || [];\n\tvar current_target = /** @type {null | Element} */ (path[0] || event.target);\n\n\tlast_propagated_event = event;\n\n\t// 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) break;\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 } from './operations.js';\n\nconst policy =\n\t// We gotta write it like this because after downleveling the pure comment may end up in the wrong location\n\tglobalThis?.window?.trustedTypes &&\n\t/* @__PURE__ */ globalThis.window.trustedTypes.createPolicy('svelte-trusted-html', {\n\t\t/** @param {string} html */\n\t\tcreateHTML: (html) => {\n\t\t\treturn html;\n\t\t}\n\t});\n\n/** @param {string} html */\nexport function create_trusted_html(html) {\n\treturn /** @type {string} */ (policy?.createHTML(html) ?? html);\n}\n\n/**\n * @param {string} html\n */\nexport function create_fragment_from_html(html) {\n\tvar elem = create_element('template');\n\telem.innerHTML = create_trusted_html(html.replaceAll('<!>', '<!---->')); // XHTML compliance\n\treturn elem.content;\n}\n","/** @import { Effect, EffectNodes, TemplateNode } from '#client' */\n/** @import { TemplateStructure } from './types' */\nimport { hydrate_next, hydrate_node, hydrating, set_hydrate_node } from './hydration.js';\nimport {\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tis_firefox,\n\tcreate_element,\n\tcreate_fragment,\n\tcreate_comment,\n\tset_attribute,\n\tmerge_text_nodes\n} from './operations.js';\nimport { create_fragment_from_html } from './reconciler.js';\nimport { active_effect } from '../runtime.js';\nimport {\n\tNAMESPACE_MATHML,\n\tNAMESPACE_SVG,\n\tTEMPLATE_FRAGMENT,\n\tTEMPLATE_USE_IMPORT_NODE,\n\tTEMPLATE_USE_MATHML,\n\tTEMPLATE_USE_SVG\n} from '../../../constants.js';\nimport {\n\tCOMMENT_NODE,\n\tDOCUMENT_FRAGMENT_NODE,\n\tIS_XHTML,\n\tREACTION_RAN,\n\tTEXT_NODE\n} from '#client/constants';\n\nconst TEMPLATE_TAG = IS_XHTML ? 'template' : 'TEMPLATE';\nconst SCRIPT_TAG = IS_XHTML ? 'script' : 'SCRIPT';\n\n/**\n * @param {TemplateNode} start\n * @param {TemplateNode | null} end\n */\nexport function assign_nodes(start, end) {\n\tvar effect = /** @type {Effect} */ (active_effect);\n\tif (effect.nodes === null) {\n\t\teffect.nodes = { start, end, a: null, t: null };\n\t}\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n * @returns {() => Node | Node[]}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_html(content, flags) {\n\tvar is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;\n\tvar use_import_node = (flags & TEMPLATE_USE_IMPORT_NODE) !== 0;\n\n\t/** @type {Node} */\n\tvar node;\n\n\t/**\n\t * Whether or not the first item is a text/element node. If not, we need to\n\t * create an additional comment node to act as `effect.nodes.start`\n\t */\n\tvar has_start = !content.startsWith('<!>');\n\n\treturn () => {\n\t\tif (hydrating) {\n\t\t\tassign_nodes(hydrate_node, null);\n\t\t\treturn hydrate_node;\n\t\t}\n\n\t\tif (node === undefined) {\n\t\t\tnode = create_fragment_from_html(has_start ? content : '<!>' + content);\n\t\t\tif (!is_fragment) node = /** @type {TemplateNode} */ (get_first_child(node));\n\t\t}\n\n\t\tvar clone = /** @type {TemplateNode} */ (\n\t\t\tuse_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)\n\t\t);\n\n\t\tif (is_fragment) {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_first_child(clone));\n\t\t\tvar end = /** @type {TemplateNode} */ (clone.lastChild);\n\n\t\t\tassign_nodes(start, end);\n\t\t} else {\n\t\t\tassign_nodes(clone, clone);\n\t\t}\n\n\t\treturn clone;\n\t};\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n * @param {'svg' | 'math'} ns\n * @returns {() => Node | Node[]}\n */\n/*#__NO_SIDE_EFFECTS__*/\nfunction from_namespace(content, flags, ns = 'svg') {\n\t/**\n\t * Whether or not the first item is a text/element node. If not, we need to\n\t * create an additional comment node to act as `effect.nodes.start`\n\t */\n\tvar has_start = !content.startsWith('<!>');\n\n\tvar is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;\n\tvar wrapped = `<${ns}>${has_start ? content : '<!>' + content}</${ns}>`;\n\n\t/** @type {Element | DocumentFragment} */\n\tvar node;\n\n\treturn () => {\n\t\tif (hydrating) {\n\t\t\tassign_nodes(hydrate_node, null);\n\t\t\treturn hydrate_node;\n\t\t}\n\n\t\tif (!node) {\n\t\t\tvar fragment = /** @type {DocumentFragment} */ (create_fragment_from_html(wrapped));\n\t\t\tvar root = /** @type {Element} */ (get_first_child(fragment));\n\n\t\t\tif (is_fragment) {\n\t\t\t\tnode = document.createDocumentFragment();\n\t\t\t\twhile (get_first_child(root)) {\n\t\t\t\t\tnode.appendChild(/** @type {TemplateNode} */ (get_first_child(root)));\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tnode = /** @type {Element} */ (get_first_child(root));\n\t\t\t}\n\t\t}\n\n\t\tvar clone = /** @type {TemplateNode} */ (node.cloneNode(true));\n\n\t\tif (is_fragment) {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_first_child(clone));\n\t\t\tvar end = /** @type {TemplateNode} */ (clone.lastChild);\n\n\t\t\tassign_nodes(start, end);\n\t\t} else {\n\t\t\tassign_nodes(clone, clone);\n\t\t}\n\n\t\treturn clone;\n\t};\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_svg(content, flags) {\n\treturn from_namespace(content, flags, 'svg');\n}\n\n/**\n * @param {string} content\n * @param {number} flags\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_mathml(content, flags) {\n\treturn from_namespace(content, flags, 'math');\n}\n\n/**\n * @param {TemplateStructure[]} structure\n * @param {typeof NAMESPACE_SVG | typeof NAMESPACE_MATHML | undefined} [ns]\n */\nfunction fragment_from_tree(structure, ns) {\n\tvar fragment = create_fragment();\n\n\tfor (var item of structure) {\n\t\tif (typeof item === 'string') {\n\t\t\tfragment.append(create_text(item));\n\t\t\tcontinue;\n\t\t}\n\n\t\t// if `preserveComments === true`, comments are represented as `['// <data>']`\n\t\tif (item === undefined || item[0][0] === '/') {\n\t\t\tfragment.append(create_comment(item ? item[0].slice(3) : ''));\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst [name, attributes, ...children] = item;\n\n\t\tconst namespace = name === 'svg' ? NAMESPACE_SVG : name === 'math' ? NAMESPACE_MATHML : ns;\n\n\t\tvar element = create_element(name, namespace, attributes?.is);\n\n\t\tfor (var key in attributes) {\n\t\t\tset_attribute(element, key, attributes[key]);\n\t\t}\n\n\t\tif (children.length > 0) {\n\t\t\tvar target =\n\t\t\t\telement.nodeName === TEMPLATE_TAG\n\t\t\t\t\t? /** @type {HTMLTemplateElement} */ (element).content\n\t\t\t\t\t: element;\n\n\t\t\ttarget.append(\n\t\t\t\tfragment_from_tree(children, element.nodeName === 'foreignObject' ? undefined : namespace)\n\t\t\t);\n\t\t}\n\n\t\tfragment.append(element);\n\t}\n\n\treturn fragment;\n}\n\n/**\n * @param {TemplateStructure[]} structure\n * @param {number} flags\n * @returns {() => Node | Node[]}\n */\n/*#__NO_SIDE_EFFECTS__*/\nexport function from_tree(structure, flags) {\n\tvar is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;\n\tvar use_import_node = (flags & TEMPLATE_USE_IMPORT_NODE) !== 0;\n\n\t/** @type {Node} */\n\tvar node;\n\n\treturn () => {\n\t\tif (hydrating) {\n\t\t\tassign_nodes(hydrate_node, null);\n\t\t\treturn hydrate_node;\n\t\t}\n\n\t\tif (node === undefined) {\n\t\t\tconst ns =\n\t\t\t\t(flags & TEMPLATE_USE_SVG) !== 0\n\t\t\t\t\t? NAMESPACE_SVG\n\t\t\t\t\t: (flags & TEMPLATE_USE_MATHML) !== 0\n\t\t\t\t\t\t? NAMESPACE_MATHML\n\t\t\t\t\t\t: undefined;\n\n\t\t\tnode = fragment_from_tree(structure, ns);\n\t\t\tif (!is_fragment) node = /** @type {TemplateNode} */ (get_first_child(node));\n\t\t}\n\n\t\tvar clone = /** @type {TemplateNode} */ (\n\t\t\tuse_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)\n\t\t);\n\n\t\tif (is_fragment) {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_first_child(clone));\n\t\t\tvar end = /** @type {TemplateNode} */ (clone.lastChild);\n\n\t\t\tassign_nodes(start, end);\n\t\t} else {\n\t\t\tassign_nodes(clone, clone);\n\t\t}\n\n\t\treturn clone;\n\t};\n}\n\n/**\n * @param {() => Element | DocumentFragment} fn\n */\nexport function with_script(fn) {\n\treturn () => run_scripts(fn());\n}\n\n/**\n * Creating a document fragment from HTML that contains script tags will not execute\n * the scripts. We need to replace the script tags with new ones so that they are executed.\n * @param {Element | DocumentFragment} node\n * @returns {Node | Node[]}\n */\nfunction run_scripts(node) {\n\t// scripts were SSR'd, in which case they will run\n\tif (hydrating) return node;\n\n\tconst is_fragment = node.nodeType === DOCUMENT_FRAGMENT_NODE;\n\tconst scripts =\n\t\t/** @type {HTMLElement} */ (node).nodeName === SCRIPT_TAG\n\t\t\t? [/** @type {HTMLScriptElement} */ (node)]\n\t\t\t: node.querySelectorAll('script');\n\n\tconst effect = /** @type {Effect & { nodes: EffectNodes }} */ (active_effect);\n\n\tfor (const script of scripts) {\n\t\tconst clone = create_element('script');\n\t\tfor (var attribute of script.attributes) {\n\t\t\tclone.setAttribute(attribute.name, attribute.value);\n\t\t}\n\n\t\tclone.textContent = script.textContent;\n\n\t\t// The script has changed - if it's at the edges, the effect now points at dead nodes\n\t\tif (is_fragment ? node.firstChild === script : node === script) {\n\t\t\teffect.nodes.start = clone;\n\t\t}\n\t\tif (is_fragment ? node.lastChild === script : node === script) {\n\t\t\teffect.nodes.end = clone;\n\t\t}\n\n\t\tscript.replaceWith(clone);\n\t}\n\treturn node;\n}\n\n/**\n * Don't mark this as side-effect-free, hydration needs to walk all nodes\n * @param {any} value\n */\nexport function text(value = '') {\n\tif (!hydrating) {\n\t\tvar t = create_text(value + '');\n\t\tassign_nodes(t, t);\n\t\treturn t;\n\t}\n\n\tvar node = hydrate_node;\n\n\tif (node.nodeType !== TEXT_NODE) {\n\t\t// if an {expression} is empty during SSR, we need to insert an empty text node\n\t\tnode.before((node = create_text()));\n\t\tset_hydrate_node(node);\n\t} else {\n\t\tmerge_text_nodes(/** @type {Text} */ (node));\n\t}\n\n\tassign_nodes(node, node);\n\treturn node;\n}\n\n/**\n * @returns {TemplateNode | DocumentFragment}\n */\nexport function comment() {\n\t// we're not delegating to `template` here for performance reasons\n\tif (hydrating) {\n\t\tassign_nodes(hydrate_node, null);\n\t\treturn hydrate_node;\n\t}\n\n\tvar frag = document.createDocumentFragment();\n\tvar start = document.createComment('');\n\tvar anchor = create_text();\n\tfrag.append(start, anchor);\n\n\tassign_nodes(start, anchor);\n\n\treturn frag;\n}\n\n/**\n * Assign the created (or in hydration mode, traversed) dom elements to the current block\n * and insert the elements into the dom (in client mode).\n * @param {Text | Comment | Element} anchor\n * @param {DocumentFragment | Element} dom\n */\nexport function append(anchor, dom) {\n\tif (hydrating) {\n\t\tvar effect = /** @type {Effect & { nodes: EffectNodes }} */ (active_effect);\n\n\t\t// When hydrating and outer component and an inner component is async, i.e. blocked on a promise,\n\t\t// then by the time the inner resolves we have already advanced to the end of the hydrated nodes\n\t\t// of the parent component. Check for defined for that reason to avoid rewinding the parent's end marker.\n\t\tif ((effect.f & REACTION_RAN) === 0 || effect.nodes.end === null) {\n\t\t\teffect.nodes.end = hydrate_node;\n\t\t}\n\n\t\thydrate_next();\n\t\treturn;\n\t}\n\n\tif (anchor === null) {\n\t\t// edge case — void `<svelte:element>` with content\n\t\treturn;\n\t}\n\n\tanchor.before(/** @type {Node} */ (dom));\n}\n\n/**\n * Create (or hydrate) an unique UID for the component instance.\n */\nexport function props_id() {\n\tif (\n\t\thydrating &&\n\t\thydrate_node &&\n\t\thydrate_node.nodeType === COMMENT_NODE &&\n\t\thydrate_node.textContent?.startsWith(`$`)\n\t) {\n\t\tconst id = hydrate_node.textContent.substring(1);\n\t\thydrate_next();\n\t\treturn id;\n\t}\n\n\t// @ts-expect-error This way we ensure the id is unique even across Svelte runtimes\n\t(window.__svelte ??= {}).uid ??= 1;\n\n\t// @ts-expect-error\n\treturn `c${window.__svelte.uid++}`;\n}\n","import { get, tick, untrack } from '../internal/client/runtime.js';\nimport { effect_tracking, render_effect } from '../internal/client/reactivity/effects.js';\nimport { source, increment } from '../internal/client/reactivity/sources.js';\nimport { tag } from '../internal/client/dev/tracing.js';\nimport { DEV } from 'esm-env';\nimport { queue_micro_task } from '../internal/client/dom/task.js';\n\n/**\n * Returns a `subscribe` function that integrates external event-based systems with Svelte's reactivity.\n * It's particularly useful for integrating with web APIs like `MediaQuery`, `IntersectionObserver`, or `WebSocket`.\n *\n * If `subscribe` is called inside an effect (including indirectly, for example inside a getter),\n * the `start` callback will be called with an `update` function. Whenever `update` is called, the effect re-runs.\n *\n * If `start` returns a cleanup function, it will be called when the effect is destroyed.\n *\n * If `subscribe` is called in multiple effects, `start` will only be called once as long as the effects\n * are active, and the returned teardown function will only be called when all effects are destroyed.\n *\n * It's best understood with an example. Here's an implementation of [`MediaQuery`](https://svelte.dev/docs/svelte/svelte-reactivity#MediaQuery):\n *\n * ```js\n * import { createSubscriber } from 'svelte/reactivity';\n * import { on } from 'svelte/events';\n *\n * export class MediaQuery {\n * \t#query;\n * \t#subscribe;\n *\n * \tconstructor(query) {\n * \t\tthis.#query = window.matchMedia(`(${query})`);\n *\n * \t\tthis.#subscribe = createSubscriber((update) => {\n * \t\t\t// when the `change` event occurs, re-run any effects that read `this.current`\n * \t\t\tconst off = on(this.#query, 'change', update);\n *\n * \t\t\t// stop listening when all the effects are destroyed\n * \t\t\treturn () => off();\n * \t\t});\n * \t}\n *\n * \tget current() {\n * \t\t// This makes the getter reactive, if read in an effect\n * \t\tthis.#subscribe();\n *\n * \t\t// Return the current state of the query, whether or not we're in an effect\n * \t\treturn this.#query.matches;\n * \t}\n * }\n * ```\n * @param {(update: () => void) => (() => void) | void} start\n * @since 5.7.0\n */\nexport function createSubscriber(start) {\n\tlet subscribers = 0;\n\tlet version = source(0);\n\t/** @type {(() => void) | void} */\n\tlet stop;\n\n\tif (DEV) {\n\t\ttag(version, 'createSubscriber version');\n\t}\n\n\treturn () => {\n\t\tif (effect_tracking()) {\n\t\t\tget(version);\n\n\t\t\trender_effect(() => {\n\t\t\t\tif (subscribers === 0) {\n\t\t\t\t\tstop = untrack(() => start(() => increment(version)));\n\t\t\t\t}\n\n\t\t\t\tsubscribers += 1;\n\n\t\t\t\treturn () => {\n\t\t\t\t\tqueue_micro_task(() => {\n\t\t\t\t\t\t// Only count down after a microtask, else we would reach 0 before our own render effect reruns,\n\t\t\t\t\t\t// but reach 1 again when the tick callback of the prior teardown runs. That would mean we\n\t\t\t\t\t\t// re-subcribe unnecessarily and create a memory leak because the old subscription is never cleaned up.\n\t\t\t\t\t\tsubscribers -= 1;\n\n\t\t\t\t\t\tif (subscribers === 0) {\n\t\t\t\t\t\t\tstop?.();\n\t\t\t\t\t\t\tstop = undefined;\n\t\t\t\t\t\t\t// Increment the version to ensure any dependent deriveds are marked dirty when the subscription is picked up again later.\n\t\t\t\t\t\t\t// If we didn't do this then the comparison of write versions would determine that the derived has a later version than\n\t\t\t\t\t\t\t// the subscriber, and it would not be re-run.\n\t\t\t\t\t\t\tincrement(version);\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\t};\n}\n","/** @import { Effect, Source, TemplateNode, } from '#client' */\nimport {\n\tBOUNDARY_EFFECT,\n\tDESTROYED,\n\tDESTROYING,\n\tEFFECT_PRESERVED,\n\tEFFECT_TRANSPARENT\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 } from '../operations.js';\nimport { defer_effect } from '../../reactivity/utils.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 = 0;\n\t#pending_count_update_queued = false;\n\n\t/** @type {Set<Effect>} */\n\t#dirty_effects = new Set();\n\n\t/** @type {Set<Effect>} */\n\t#maybe_dirty_effects = new Set();\n\n\t/**\n\t * A source containing the number of pending async deriveds/expressions.\n\t * Only created if `$effect.pending()` is used inside the boundary,\n\t * otherwise updating the source results in needless `Batch.ensure()`\n\t * calls followed by no-op flushes\n\t * @type {Source<number> | null}\n\t */\n\t#effect_pending = null;\n\n\t#effect_pending_subscriber = createSubscriber(() => {\n\t\tthis.#effect_pending = source(this.#local_pending_count);\n\n\t\tif (DEV) {\n\t\t\ttag(this.#effect_pending, '$effect.pending()');\n\t\t}\n\n\t\treturn () => {\n\t\t\tthis.#effect_pending = null;\n\t\t};\n\t});\n\n\t/**\n\t * @param {TemplateNode} node\n\t * @param {BoundaryProps} props\n\t * @param {((anchor: Node) => void)} children\n\t * @param {((error: unknown) => unknown) | undefined} [transform_error]\n\t */\n\tconstructor(node, props, children, transform_error) {\n\t\tthis.#anchor = node;\n\t\tthis.#props = props;\n\n\t\tthis.#children = (anchor) => {\n\t\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\t\teffect.b = this;\n\t\t\teffect.f |= BOUNDARY_EFFECT;\n\n\t\t\tchildren(anchor);\n\t\t};\n\n\t\tthis.parent = /** @type {Effect} */ (active_effect).b;\n\n\t\t// Inherit transform_error from parent boundary, or use the provided one, or default to identity\n\t\tthis.transform_error = transform_error ?? this.parent?.transform_error ?? ((e) => e);\n\n\t\tthis.#effect = block(() => {\n\t\t\tif (hydrating) {\n\t\t\t\tconst comment_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 fragment = (this.#offscreen_fragment = document.createDocumentFragment());\n\t\t\tvar anchor = create_text();\n\t\t\tvar handled = false;\n\n\t\t\tfragment.append(anchor);\n\n\t\t\tthis.#main_effect = this.#run(() => {\n\t\t\t\ttry {\n\t\t\t\t\treturn branch(() => this.#children(anchor));\n\t\t\t\t} catch (error) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.error(error);\n\t\t\t\t\t\thandled = true;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tinvoke_error_boundary(error, this.#effect.parent);\n\t\t\t\t\t}\n\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tif (this.#main_effect === null) {\n\t\t\t\tthis.#offscreen_fragment = null;\n\t\t\t\tif (handled) this.#resolve(/** @type {Batch} */ (current_batch));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (this.#pending_count === 0) {\n\t\t\t\tthis.#anchor.before(fragment);\n\t\t\t\tthis.#offscreen_fragment = null;\n\n\t\t\t\tpause_effect(/** @type {Effect} */ (this.#pending_effect), () => {\n\t\t\t\t\tthis.#pending_effect = null;\n\t\t\t\t});\n\n\t\t\t\tthis.#resolve(/** @type {Batch} */ (current_batch));\n\t\t\t}\n\t\t});\n\t}\n\n\t#render() {\n\t\ttry {\n\t\t\tthis.is_pending = this.has_pending_snippet();\n\t\t\tthis.#pending_count = 0;\n\t\t\tthis.#local_pending_count = 0;\n\n\t\t\tthis.#main_effect = branch(() => {\n\t\t\t\tthis.#children(this.#anchor);\n\t\t\t});\n\n\t\t\tif (this.#pending_count > 0) {\n\t\t\t\tvar fragment = (this.#offscreen_fragment = document.createDocumentFragment());\n\t\t\t\tmove_effect(this.#main_effect, fragment);\n\n\t\t\t\tconst pending = /** @type {(anchor: Node) => void} */ (this.#props.pending);\n\t\t\t\tthis.#pending_effect = branch(() => pending(this.#anchor));\n\t\t\t} else {\n\t\t\t\tthis.#resolve(/** @type {Batch} */ (current_batch));\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis.error(error);\n\t\t}\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#resolve(batch) {\n\t\tthis.is_pending = false;\n\n\t\t// any effects that were previously deferred should be transferred\n\t\t// to the batch, which will flush in the next microtask\n\t\tbatch.transfer_effects(this.#dirty_effects, this.#maybe_dirty_effects);\n\t}\n\n\t/**\n\t * Defer an effect inside a pending boundary until the boundary resolves\n\t * @param {Effect} effect\n\t */\n\tdefer_effect(effect) {\n\t\tdefer_effect(effect, this.#dirty_effects, this.#maybe_dirty_effects);\n\t}\n\n\t/**\n\t * Returns `false` if the effect exists inside a boundary whose pending snippet is shown\n\t * @returns {boolean}\n\t */\n\tis_rendered() {\n\t\treturn !this.is_pending && (!this.parent || this.parent.is_rendered());\n\t}\n\n\thas_pending_snippet() {\n\t\treturn !!this.#props.pending;\n\t}\n\n\t/**\n\t * @template T\n\t * @param {() => T} fn\n\t */\n\t#run(fn) {\n\t\tvar previous_effect = active_effect;\n\t\tvar previous_reaction = active_reaction;\n\t\tvar previous_ctx = component_context;\n\n\t\tset_active_effect(this.#effect);\n\t\tset_active_reaction(this.#effect);\n\t\tset_component_context(this.#effect.ctx);\n\n\t\ttry {\n\t\t\tBatch.ensure();\n\t\t\treturn fn();\n\t\t} finally {\n\t\t\tset_active_effect(previous_effect);\n\t\t\tset_active_reaction(previous_reaction);\n\t\t\tset_component_context(previous_ctx);\n\t\t}\n\t}\n\n\t/**\n\t * Updates the pending count associated with the currently visible pending snippet,\n\t * if any, such that we can replace the snippet with content once work is done\n\t * @param {1 | -1} d\n\t * @param {Batch} batch\n\t */\n\t#update_pending_count(d, batch) {\n\t\tif (!this.has_pending_snippet()) {\n\t\t\tif (this.parent) {\n\t\t\t\tthis.parent.#update_pending_count(d, batch);\n\t\t\t}\n\n\t\t\t// if there's no parent, we're in a scope with no pending snippet\n\t\t\treturn;\n\t\t}\n\n\t\tthis.#pending_count += d;\n\n\t\tif (this.#pending_count === 0) {\n\t\t\tthis.#resolve(batch);\n\n\t\t\tif (this.#pending_effect) {\n\t\t\t\tpause_effect(this.#pending_effect, () => {\n\t\t\t\t\tthis.#pending_effect = null;\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (this.#offscreen_fragment) {\n\t\t\t\tthis.#anchor.before(this.#offscreen_fragment);\n\t\t\t\tthis.#offscreen_fragment = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Update the source that powers `$effect.pending()` inside this boundary,\n\t * and controls when the current `pending` snippet (if any) is removed.\n\t * Do not call from inside the class\n\t * @param {1 | -1} d\n\t * @param {Batch} batch\n\t */\n\tupdate_pending_count(d, batch) {\n\t\tthis.#update_pending_count(d, batch);\n\n\t\tthis.#local_pending_count += d;\n\n\t\tif (!this.#effect_pending || this.#pending_count_update_queued) return;\n\t\tthis.#pending_count_update_queued = true;\n\n\t\tqueue_micro_task(() => {\n\t\t\tthis.#pending_count_update_queued = false;\n\t\t\tif (this.#effect_pending) {\n\t\t\t\tinternal_set(this.#effect_pending, this.#local_pending_count);\n\t\t\t}\n\t\t});\n\t}\n\n\tget_effect_pending() {\n\t\tthis.#effect_pending_subscriber();\n\t\treturn get(/** @type {Source<number>} */ (this.#effect_pending));\n\t}\n\n\t/** @param {unknown} error */\n\terror(error) {\n\t\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' */\nimport { DEV } from 'esm-env';\nimport {\n\tclear_text_content,\n\tcreate_text,\n\tget_first_child,\n\tget_next_sibling,\n\tinit_operations\n} from './dom/operations.js';\nimport { HYDRATION_END, HYDRATION_ERROR, HYDRATION_START } from '../../constants.js';\nimport { active_effect } from './runtime.js';\nimport { push, pop, component_context, 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 { array_from } from '../shared/utils.js';\nimport {\n\tall_registered_events,\n\thandle_event_propagation,\n\troot_event_handles\n} from './dom/elements/events.js';\nimport * as w from './warnings.js';\nimport * as e from './errors.js';\nimport { assign_nodes } from './dom/template.js';\nimport { is_passive_event } from '../../utils.js';\nimport { COMMENT_NODE, TEXT_CACHE } from './constants.js';\nimport { boundary } from './dom/blocks/boundary.js';\n\n/**\n * This is normally true — block effects should run their intro transitions —\n * but is false during hydration (unless `options.intro` is `true`) and\n * when creating the children of a `<svelte:element>` that just changed tag\n */\nexport let should_intro = true;\n\n/** @param {boolean} value */\nexport function set_should_intro(value) {\n\tshould_intro = value;\n}\n\n/**\n * @param {Element} text\n * @param {string} value\n * @returns {void}\n */\nexport function set_text(text, value) {\n\t// For objects, we apply string coercion (which might make things like $state array references in the template reactive) before diffing\n\tvar str = value == null ? '' : typeof value === 'object' ? `${value}` : value;\n\t// prettier-ignore\n\tif (str !== (/** @type {any} */ (text)[TEXT_CACHE] ??= text.nodeValue)) {\n\t\t/** @type {any} */ (text)[TEXT_CACHE] = str;\n\t\ttext.nodeValue = `${str}`;\n\t}\n}\n\n/**\n * Mounts a component to the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component.\n * Transitions will play during the initial render unless the `intro` option is set to `false`.\n *\n * @template {Record<string, any>} Props\n * @template {Record<string, any>} Exports\n * @param {ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>} component\n * @param {MountOptions<Props>} options\n * @returns {Exports}\n */\nexport function mount(component, options) {\n\treturn _mount(component, options);\n}\n\n/**\n * Hydrates a component on the given target and returns the exports and potentially the props (if compiled with `accessors: true`) of the component\n *\n * @template {Record<string, any>} Props\n * @template {Record<string, any>} Exports\n * @param {ComponentType<SvelteComponent<Props>> | Component<Props, Exports, any>} component\n * @param {{} extends Props ? {\n * \t\ttarget: Document | Element | ShadowRoot;\n * \t\tprops?: Props;\n * \t\tevents?: Record<string, (e: any) => any>;\n *  \tcontext?: Map<any, any>;\n * \t\tintro?: boolean;\n * \t\trecover?: boolean;\n *\t\ttransformError?: (error: unknown) => unknown;\n * \t} : {\n * \t\ttarget: Document | Element | ShadowRoot;\n * \t\tprops: Props;\n * \t\tevents?: Record<string, (e: any) => any>;\n *  \tcontext?: Map<any, any>;\n * \t\tintro?: boolean;\n * \t\trecover?: boolean;\n *\t\ttransformError?: (error: unknown) => unknown;\n * \t}} options\n * @returns {Exports}\n */\nexport function hydrate(component, options) {\n\tinit_operations();\n\toptions.intro = options.intro ?? false;\n\tconst target = options.target;\n\tconst was_hydrating = hydrating;\n\tconst previous_hydrate_node = hydrate_node;\n\n\ttry {\n\t\tvar anchor = get_first_child(target);\n\n\t\twhile (\n\t\t\tanchor &&\n\t\t\t(anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ (anchor).data !== HYDRATION_START)\n\t\t) {\n\t\t\tanchor = get_next_sibling(anchor);\n\t\t}\n\n\t\tif (!anchor) {\n\t\t\tthrow HYDRATION_ERROR;\n\t\t}\n\n\t\tset_hydrating(true);\n\t\tset_hydrate_node(/** @type {Comment} */ (anchor));\n\n\t\tconst instance = _mount(component, { ...options, anchor });\n\n\t\tset_hydrating(false);\n\n\t\treturn /**  @type {Exports} */ (instance);\n\t} catch (error) {\n\t\t// re-throw Svelte errors - they are certainly not related to hydration\n\t\tif (\n\t\t\terror instanceof Error &&\n\t\t\terror.message.split('\\n').some((line) => line.startsWith('https://svelte.dev/e/'))\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tif (error !== HYDRATION_ERROR) {\n\t\t\t// eslint-disable-next-line no-console\n\t\t\tconsole.warn('Failed to hydrate: ', error);\n\t\t}\n\n\t\tif (options.recover === false) {\n\t\t\te.hydration_failed();\n\t\t}\n\n\t\t// If an error occurred above, the operations might not yet have been initialised.\n\t\tinit_operations();\n\t\tclear_text_content(target);\n\n\t\tset_hydrating(false);\n\t\treturn mount(component, options);\n\t} finally {\n\t\tset_hydrating(was_hydrating);\n\t\tset_hydrate_node(previous_hydrate_node);\n\t}\n}\n\n/** @type {Map<EventTarget, Map<string, number>>} */\nconst listeners = new Map();\n\n/**\n * @template {Record<string, any>} Exports\n * @param {ComponentType<SvelteComponent<any>> | Component<any>} Component\n * @param {MountOptions} options\n * @returns {Exports}\n */\nfunction _mount(\n\tComponent,\n\t{ target, anchor, props = {}, events, context, intro = true, transformError }\n) {\n\tinit_operations();\n\n\t/** @type {Exports} */\n\t// @ts-expect-error will be defined because the render effect runs synchronously\n\tvar component = undefined;\n\n\tvar unmount = component_root(() => {\n\t\tvar anchor_node = anchor ?? target.appendChild(create_text());\n\n\t\tboundary(\n\t\t\t/** @type {TemplateNode} */ (anchor_node),\n\t\t\t{\n\t\t\t\tpending: () => {}\n\t\t\t},\n\t\t\t(anchor_node) => {\n\t\t\t\tpush({});\n\t\t\t\tvar ctx = /** @type {ComponentContext} */ (component_context);\n\t\t\t\tif (context) ctx.c = context;\n\n\t\t\t\tif (events) {\n\t\t\t\t\t// We can't spread the object or else we'd lose the state proxy stuff, if it is one\n\t\t\t\t\t/** @type {any} */ (props).$$events = events;\n\t\t\t\t}\n\n\t\t\t\tif (hydrating) {\n\t\t\t\t\tassign_nodes(/** @type {TemplateNode} */ (anchor_node), null);\n\t\t\t\t}\n\n\t\t\t\tshould_intro = intro;\n\t\t\t\t// @ts-expect-error the public typings are not what the actual function looks like\n\t\t\t\tcomponent = Component(anchor_node, props) || 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\thydrate_node.nodeType !== COMMENT_NODE ||\n\t\t\t\t\t\t/** @type {Comment} */ (hydrate_node).data !== HYDRATION_END\n\t\t\t\t\t) {\n\t\t\t\t\t\tw.hydration_mismatch();\n\t\t\t\t\t\tthrow HYDRATION_ERROR;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tpop();\n\t\t\t},\n\t\t\ttransformError\n\t\t);\n\n\t\t// Setup event delegation _after_ component is mounted - if an error would happen during mount, it would otherwise not be cleaned up\n\t\t/** @type {Set<string>} */\n\t\tvar registered_events = new Set();\n\n\t\t/** @param {Array<string>} events */\n\t\tvar event_handle = (events) => {\n\t\t\tfor (var i = 0; i < events.length; i++) {\n\t\t\t\tvar event_name = events[i];\n\n\t\t\t\tif (registered_events.has(event_name)) continue;\n\t\t\t\tregistered_events.add(event_name);\n\n\t\t\t\tvar passive = is_passive_event(event_name);\n\n\t\t\t\t// Add the event listener to both the container and the document.\n\t\t\t\t// The container listener ensures we catch events from within in case\n\t\t\t\t// the outer content stops propagation of the event.\n\t\t\t\t//\n\t\t\t\t// The document listener ensures we catch events that originate from elements that were\n\t\t\t\t// manually moved outside of the container (e.g. via manual portals).\n\t\t\t\tfor (const node of [target, document]) {\n\t\t\t\t\tvar counts = listeners.get(node);\n\n\t\t\t\t\tif (counts === undefined) {\n\t\t\t\t\t\tcounts = new Map();\n\t\t\t\t\t\tlisteners.set(node, counts);\n\t\t\t\t\t}\n\n\t\t\t\t\tvar count = counts.get(event_name);\n\n\t\t\t\t\tif (count === undefined) {\n\t\t\t\t\t\tnode.addEventListener(event_name, handle_event_propagation, { passive });\n\t\t\t\t\t\tcounts.set(event_name, 1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcounts.set(event_name, count + 1);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\tevent_handle(array_from(all_registered_events));\n\t\troot_event_handles.add(event_handle);\n\n\t\treturn () => {\n\t\t\tfor (var event_name of registered_events) {\n\t\t\t\tfor (const node of [target, document]) {\n\t\t\t\t\tvar counts = /** @type {Map<string, number>} */ (listeners.get(node));\n\t\t\t\t\tvar count = /** @type {number} */ (counts.get(event_name));\n\n\t\t\t\t\tif (--count == 0) {\n\t\t\t\t\t\tnode.removeEventListener(event_name, handle_event_propagation);\n\t\t\t\t\t\tcounts.delete(event_name);\n\n\t\t\t\t\t\tif (counts.size === 0) {\n\t\t\t\t\t\t\tlisteners.delete(node);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcounts.set(event_name, count);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\troot_event_handles.delete(event_handle);\n\n\t\t\tif (anchor_node !== anchor) {\n\t\t\t\tanchor_node.parentNode?.removeChild(anchor_node);\n\t\t\t}\n\t\t};\n\t});\n\n\tmounted_components.set(component, unmount);\n\treturn component;\n}\n\n/**\n * References of the components that were mounted or hydrated.\n * Uses a `WeakMap` to avoid memory leaks.\n */\nlet mounted_components = new WeakMap();\n\n/**\n * Unmounts a component that was previously mounted using `mount` or `hydrate`.\n *\n * Since 5.13.0, if `options.outro` is `true`, [transitions](https://svelte.dev/docs/svelte/transition) will play before the component is removed from the DOM.\n *\n * Returns a `Promise` that resolves after transitions have completed if `options.outro` is true, or immediately otherwise (prior to 5.13.0, returns `void`).\n *\n * ```js\n * import { mount, unmount } from 'svelte';\n * import App from './App.svelte';\n *\n * const app = mount(App, { target: document.body });\n *\n * // later...\n * unmount(app, { outro: true });\n * ```\n * @param {Record<string, any>} component\n * @param {{ outro?: boolean }} [options]\n * @returns {Promise<void>}\n */\nexport function unmount(component, options) {\n\tconst fn = mounted_components.get(component);\n\n\tif (fn) {\n\t\tmounted_components.delete(component);\n\t\treturn fn(options);\n\t}\n\n\tif (DEV) {\n\t\tw.lifecycle_double_unmount();\n\t}\n\n\treturn Promise.resolve();\n}\n","/** @import { Effect, TemplateNode } from '#client' */\nimport { Batch, current_batch } from '../../reactivity/batch.js';\nimport {\n\tbranch,\n\tdestroy_effect,\n\tmove_effect,\n\tpause_effect,\n\tresume_effect\n} from '../../reactivity/effects.js';\nimport { HMR_ANCHOR } from '../../constants.js';\nimport { hydrate_node, hydrating } from '../hydration.js';\nimport { create_text, should_defer_append } from '../operations.js';\nimport { DEV } from 'esm-env';\n\n/**\n * @typedef {{ effect: Effect, fragment: DocumentFragment }} Branch\n */\n\n/**\n * @template Key\n */\nexport class BranchManager {\n\t/** @type {TemplateNode} */\n\tanchor;\n\n\t/** @type {Map<Batch, Key>} */\n\t#batches = new Map();\n\n\t/**\n\t * Map of keys to effects that are currently rendered in the DOM.\n\t * These effects are visible and actively part of the document tree.\n\t * Example:\n\t * ```\n\t * {#if condition}\n\t * \tfoo\n\t * {:else}\n\t * \tbar\n\t * {/if}\n\t * ```\n\t * Can result in the entries `true->Effect` and `false->Effect`\n\t * @type {Map<Key, Effect>}\n\t */\n\t#onscreen = new Map();\n\n\t/**\n\t * Similar to #onscreen with respect to the keys, but contains branches that are not yet\n\t * in the DOM, because their insertion is deferred.\n\t * @type {Map<Key, Branch>}\n\t */\n\t#offscreen = new Map();\n\n\t/**\n\t * Keys of effects that are currently outroing\n\t * @type {Set<Key>}\n\t */\n\t#outroing = new Set();\n\n\t/**\n\t * Whether to pause (i.e. outro) on change, or destroy immediately.\n\t * This is necessary for `<svelte:element>`\n\t */\n\t#transition = true;\n\n\t/**\n\t * @param {TemplateNode} anchor\n\t * @param {boolean} transition\n\t */\n\tconstructor(anchor, transition = true) {\n\t\tthis.anchor = anchor;\n\t\tthis.#transition = transition;\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#commit = (batch) => {\n\t\t// if this batch was made obsolete, bail\n\t\tif (!this.#batches.has(batch)) return;\n\n\t\tvar key = /** @type {Key} */ (this.#batches.get(batch));\n\n\t\tvar onscreen = this.#onscreen.get(key);\n\n\t\tif (onscreen) {\n\t\t\t// effect is already in the DOM — abort any current outro\n\t\t\tresume_effect(onscreen);\n\t\t\tthis.#outroing.delete(key);\n\t\t} else {\n\t\t\t// effect is currently offscreen. put it in the DOM\n\t\t\tvar offscreen = this.#offscreen.get(key);\n\n\t\t\tif (offscreen) {\n\t\t\t\t// effect could have been outro'ed before through a prior batch — resume if necessary\n\t\t\t\tresume_effect(offscreen.effect);\n\t\t\t\tthis.#onscreen.set(key, offscreen.effect);\n\t\t\t\tthis.#offscreen.delete(key);\n\n\t\t\t\tif (DEV) {\n\t\t\t\t\t// Tell hmr.js about the anchor it should use for updates,\n\t\t\t\t\t// since the initial one will be removed\n\t\t\t\t\t/** @type {any} */ (offscreen.fragment.lastChild)[HMR_ANCHOR] = this.anchor;\n\t\t\t\t}\n\n\t\t\t\t// remove the anchor...\n\t\t\t\t/** @type {TemplateNode} */ (offscreen.fragment.lastChild).remove();\n\n\t\t\t\t// ...and append the fragment\n\t\t\t\tthis.anchor.before(offscreen.fragment);\n\t\t\t\tonscreen = offscreen.effect;\n\t\t\t}\n\t\t}\n\n\t\tfor (const [b, k] of this.#batches) {\n\t\t\tthis.#batches.delete(b);\n\n\t\t\tif (b === batch) {\n\t\t\t\t// keep values for newer batches\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst offscreen = this.#offscreen.get(k);\n\n\t\t\tif (offscreen) {\n\t\t\t\t// for older batches, destroy offscreen effects\n\t\t\t\t// as they will never be committed\n\t\t\t\tdestroy_effect(offscreen.effect);\n\t\t\t\tthis.#offscreen.delete(k);\n\t\t\t}\n\t\t}\n\n\t\t// outro/destroy all onscreen effects...\n\t\tfor (const [k, effect] of this.#onscreen) {\n\t\t\t// ...except the one that was just committed\n\t\t\t//    or those that are already outroing (else the transition is aborted and the effect destroyed right away)\n\t\t\tif (k === key || this.#outroing.has(k)) continue;\n\n\t\t\tconst on_destroy = () => {\n\t\t\t\tconst keys = Array.from(this.#batches.values());\n\n\t\t\t\tif (keys.includes(k)) {\n\t\t\t\t\t// keep the effect offscreen, as another batch will need it\n\t\t\t\t\tvar fragment = document.createDocumentFragment();\n\t\t\t\t\tmove_effect(effect, fragment);\n\n\t\t\t\t\tfragment.append(create_text()); // TODO can we avoid this?\n\n\t\t\t\t\tthis.#offscreen.set(k, { effect, fragment });\n\t\t\t\t} else {\n\t\t\t\t\tdestroy_effect(effect);\n\t\t\t\t}\n\n\t\t\t\tthis.#outroing.delete(k);\n\t\t\t\tthis.#onscreen.delete(k);\n\t\t\t};\n\n\t\t\tif (this.#transition || !onscreen) {\n\t\t\t\tthis.#outroing.add(k);\n\t\t\t\tpause_effect(effect, on_destroy, false);\n\t\t\t} else {\n\t\t\t\ton_destroy();\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\t#discard = (batch) => {\n\t\tthis.#batches.delete(batch);\n\n\t\tconst keys = Array.from(this.#batches.values());\n\n\t\tfor (const [k, branch] of this.#offscreen) {\n\t\t\tif (!keys.includes(k)) {\n\t\t\t\tdestroy_effect(branch.effect);\n\t\t\t\tthis.#offscreen.delete(k);\n\t\t\t}\n\t\t}\n\t};\n\n\t/**\n\t *\n\t * @param {any} key\n\t * @param {null | ((target: TemplateNode) => void)} fn\n\t */\n\tensure(key, fn) {\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\t\tvar defer = should_defer_append();\n\n\t\tif (fn && !this.#onscreen.has(key) && !this.#offscreen.has(key)) {\n\t\t\tif (defer) {\n\t\t\t\tvar fragment = document.createDocumentFragment();\n\t\t\t\tvar target = create_text();\n\n\t\t\t\tfragment.append(target);\n\n\t\t\t\tthis.#offscreen.set(key, {\n\t\t\t\t\teffect: branch(() => fn(target)),\n\t\t\t\t\tfragment\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tthis.#onscreen.set(\n\t\t\t\t\tkey,\n\t\t\t\t\tbranch(() => fn(this.anchor))\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tthis.#batches.set(batch, key);\n\n\t\tif (defer) {\n\t\t\tfor (const [k, effect] of this.#onscreen) {\n\t\t\t\tif (k === key) {\n\t\t\t\t\tbatch.unskip_effect(effect);\n\t\t\t\t} else {\n\t\t\t\t\tbatch.skip_effect(effect);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor (const [k, branch] of this.#offscreen) {\n\t\t\t\tif (k === key) {\n\t\t\t\t\tbatch.unskip_effect(branch.effect);\n\t\t\t\t} else {\n\t\t\t\t\tbatch.skip_effect(branch.effect);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tbatch.oncommit(this.#commit);\n\t\t\tbatch.ondiscard(this.#discard);\n\t\t} else {\n\t\t\tif (hydrating) {\n\t\t\t\tthis.anchor = hydrate_node;\n\t\t\t}\n\n\t\t\tthis.#commit(batch);\n\t\t}\n\t}\n}\n","/** @import { 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\thydrate_node\n} from '../hydration.js';\nimport { queue_micro_task } from '../task.js';\nimport { HYDRATION_START_ELSE, UNINITIALIZED } from '../../../../constants.js';\nimport { is_runes } from '../../context.js';\nimport { Batch, current_batch, flushSync, is_flushing_sync } from '../../reactivity/batch.js';\nimport { BranchManager } from './branches.js';\nimport { capture, unset_context } from '../../reactivity/async.js';\nimport { DEV } from 'esm-env';\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\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\tblock(() => {\n\t\tvar batch = /** @type {Batch} */ (current_batch);\n\t\tvar input = get_input();\n\n\t\tvar destroyed = false;\n\n\t\t/** Whether or not there was a hydration mismatch. Needs to be a `let` or else it isn't treeshaken out */\n\t\t// @ts-ignore coercing `node` to a `Comment` causes TypeScript and Prettier to fight\n\t\tlet mismatch = hydrating && is_promise(input) === (node.data === HYDRATION_START_ELSE);\n\n\t\tif (mismatch) {\n\t\t\t// Hydration mismatch: remove everything inside the anchor and start fresh\n\t\t\tset_hydrate_node(skip_nodes());\n\t\t\tset_hydrating(false);\n\t\t}\n\n\t\tif (is_promise(input)) {\n\t\t\tvar restore = capture();\n\t\t\tvar resolved = false;\n\n\t\t\t/**\n\t\t\t * @param {() => void} fn\n\t\t\t */\n\t\t\tconst resolve = (fn) => {\n\t\t\t\tif (destroyed) return;\n\n\t\t\t\tresolved = true;\n\t\t\t\t// We don't want to restore the previous batch here; {#await} blocks don't follow the async logic\n\t\t\t\t// we have elsewhere, instead pending/resolve/fail states are each their own batch so to speak.\n\t\t\t\trestore(false);\n\t\t\t\t// ...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();\n\t\t\t\t} finally {\n\t\t\t\t\tunset_context(false);\n\n\t\t\t\t\t// without this, the DOM does not update until two ticks after the promise\n\t\t\t\t\t// resolves, which is unexpected behaviour (and somewhat irksome to test)\n\t\t\t\t\tif (!is_flushing_sync) flushSync();\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tinput.then(\n\t\t\t\t(v) => {\n\t\t\t\t\tresolve(() => {\n\t\t\t\t\t\tinternal_set(value, v);\n\t\t\t\t\t\tbranches.ensure(THEN, then_fn && ((target) => then_fn(target, value)));\n\t\t\t\t\t});\n\t\t\t\t},\n\t\t\t\t(e) => {\n\t\t\t\t\tresolve(() => {\n\t\t\t\t\t\tinternal_set(error, e);\n\t\t\t\t\t\tbranches.ensure(CATCH, catch_fn && ((target) => catch_fn(target, error)));\n\n\t\t\t\t\t\tif (!catch_fn) {\n\t\t\t\t\t\t\t// Rethrow the error if no catch block exists\n\t\t\t\t\t\t\tthrow error.v;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tif (hydrating) {\n\t\t\t\tbranches.ensure(PENDING, pending_fn);\n\t\t\t} else {\n\t\t\t\t// Wait a microtask before checking if we should show the pending state as\n\t\t\t\t// the promise might have resolved by then\n\t\t\t\tqueue_micro_task(() => {\n\t\t\t\t\tif (!resolved) {\n\t\t\t\t\t\tresolve(() => {\n\t\t\t\t\t\t\tbranches.ensure(PENDING, pending_fn);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t} else {\n\t\t\tinternal_set(value, input);\n\t\t\tbranches.ensure(THEN, then_fn && ((target) => then_fn(target, value)));\n\t\t}\n\n\t\tif (mismatch) {\n\t\t\t// continue in hydration mode\n\t\t\tset_hydrating(true);\n\t\t}\n\n\t\treturn () => {\n\t\t\tdestroyed = true;\n\t\t};\n\t});\n}\n","/** @import { TemplateNode } from '#client' */\nimport { EFFECT_TRANSPARENT } from '#client/constants';\nimport {\n\thydrate_next,\n\thydrating,\n\tread_hydration_instruction,\n\tskip_nodes,\n\tset_hydrate_node,\n\tset_hydrating,\n\thydrate_node\n} from '../hydration.js';\nimport { block } from '../../reactivity/effects.js';\nimport { BranchManager } from './branches.js';\n\n/**\n * @param {TemplateNode} node\n * @param {(branch: (fn: (anchor: Node) => void, key?: number | false) => void) => void} fn\n * @param {boolean} [elseif] True if this is an `{:else if ...}` block rather than an `{#if ...}`, as that affects which transitions are considered 'local'\n * @returns {void}\n */\nexport function if_block(node, fn, elseif = false) {\n\t/** @type {TemplateNode | undefined} */\n\tvar marker;\n\tif (hydrating) {\n\t\tmarker = hydrate_node;\n\t\thydrate_next();\n\t}\n\n\tvar branches = new BranchManager(node);\n\tvar flags = elseif ? EFFECT_TRANSPARENT : 0;\n\n\t/**\n\t * @param {number | false} key\n\t * @param {null | ((anchor: Node) => void)} fn\n\t */\n\tfunction update_branch(key, fn) {\n\t\tif (hydrating) {\n\t\t\tvar data = read_hydration_instruction(/** @type {TemplateNode} */ (marker));\n\n\t\t\t// \"[n\" = branch n, \"[-1\" = else\n\t\t\tif (key !== parseInt(data.substring(1))) {\n\t\t\t\t// Hydration mismatch: remove everything inside the anchor and start fresh.\n\t\t\t\t// This could happen with `{#if browser}...{/if}`, for example\n\t\t\t\tvar anchor = skip_nodes();\n\n\t\t\t\tset_hydrate_node(anchor);\n\t\t\t\tbranches.anchor = anchor;\n\n\t\t\t\tset_hydrating(false);\n\t\t\t\tbranches.ensure(key, fn);\n\t\t\t\tset_hydrating(true);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tbranches.ensure(key, fn);\n\t}\n\n\tblock(() => {\n\t\tvar has_branch = false;\n\n\t\tfn((fn, key = 0) => {\n\t\t\thas_branch = true;\n\t\t\tupdate_branch(key, fn);\n\t\t});\n\n\t\tif (!has_branch) {\n\t\t\tupdate_branch(-1, null);\n\t\t}\n\t}, flags);\n}\n","/** @import { TemplateNode } from '#client' */\nimport { is_runes } from '../../context.js';\nimport { block } from '../../reactivity/effects.js';\nimport { hydrate_next, hydrating } from '../hydration.js';\nimport { BranchManager } from './branches.js';\n\nconst NAN = Symbol('NaN');\n\n/**\n * @template V\n * @param {TemplateNode} node\n * @param {() => V} get_key\n * @param {(anchor: Node) => TemplateNode | void} render_fn\n * @returns {void}\n */\nexport function key(node, get_key, render_fn) {\n\tif (hydrating) {\n\t\thydrate_next();\n\t}\n\n\tvar branches = new BranchManager(node);\n\n\tvar legacy = !is_runes();\n\n\tblock(() => {\n\t\tvar key = get_key();\n\n\t\t// NaN !== NaN, hence we do this workaround to not trigger remounts unnecessarily\n\t\tif (key !== key) {\n\t\t\tkey = /** @type {any} */ (NAN);\n\t\t}\n\n\t\t// key blocks in Svelte <5 had stupid semantics\n\t\tif (legacy && key !== null && typeof key === 'object') {\n\t\t\tkey = /** @type {V} */ ({});\n\t\t}\n\n\t\tbranches.ensure(key, render_fn);\n\t});\n}\n","import { render_effect } from '../../reactivity/effects.js';\nimport { hydrating, set_hydrate_node } from '../hydration.js';\nimport { get_first_child } from '../operations.js';\n\n/**\n * @param {HTMLDivElement | SVGGElement} element\n * @param {() => Record<string, string>} get_styles\n * @returns {void}\n */\nexport function css_props(element, get_styles) {\n\tif (hydrating) {\n\t\tset_hydrate_node(get_first_child(element));\n\t}\n\n\trender_effect(() => {\n\t\tvar styles = get_styles();\n\n\t\tfor (var key in styles) {\n\t\t\tvar value = styles[key];\n\n\t\t\tif (value == null || value === '') {\n\t\t\t\telement.style.removeProperty(key);\n\t\t\t} else {\n\t\t\t\telement.style.setProperty(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} from '../operations.js';\nimport {\n\tblock,\n\tbranch,\n\tdestroy_effect,\n\tmove_effect,\n\tpause_effect,\n\tresume_effect\n} from '../../reactivity/effects.js';\nimport { source, mutable_source, internal_set } from '../../reactivity/sources.js';\nimport { array_from, is_array } from '../../../shared/utils.js';\nimport { BRANCH_EFFECT, COMMENT_NODE, DESTROYED, EFFECT_OFFSCREEN, INERT } from '#client/constants';\nimport { queue_micro_task } from '../task.js';\nimport { get } from '../../runtime.js';\nimport { DEV } from 'esm-env';\nimport { derived_safe_equal } from '../../reactivity/deriveds.js';\nimport { current_batch } from '../../reactivity/batch.js';\nimport * as e from '../../errors.js';\nimport { tag } from '../../dev/tracing.js';\n\n// When making substantive changes to this file, validate them with the each block stress test:\n// https://svelte.dev/playground/1972b2cf46564476ad8c8c6405b23b7b\n// This test also exists in this repo, as `packages/svelte/tests/manual/each-stress-test`\n\n/**\n * @param {any} _\n * @param {number} i\n */\nexport function index(_, i) {\n\treturn i;\n}\n\n/**\n * Pause multiple effects simultaneously, and coordinate their\n * subsequent destruction. Used in each blocks\n * @param {EachState} state\n * @param {Effect[]} to_destroy\n * @param {null | Node} controlled_anchor\n */\nfunction pause_effects(state, to_destroy, controlled_anchor) {\n\t/** @type {TransitionManager[]} */\n\tvar transitions = [];\n\tvar length = to_destroy.length;\n\n\t/** @type {EachOutroGroup} */\n\tvar group;\n\tvar remaining = to_destroy.length;\n\n\tfor (var i = 0; i < length; i++) {\n\t\tlet effect = to_destroy[i];\n\n\t\tpause_effect(\n\t\t\teffect,\n\t\t\t() => {\n\t\t\t\tif (group) {\n\t\t\t\t\tgroup.pending.delete(effect);\n\t\t\t\t\tgroup.done.add(effect);\n\n\t\t\t\t\tif (group.pending.size === 0) {\n\t\t\t\t\t\tvar groups = /** @type {Set<EachOutroGroup>} */ (state.outrogroups);\n\n\t\t\t\t\t\tdestroy_effects(state, array_from(group.done));\n\t\t\t\t\t\tgroups.delete(group);\n\n\t\t\t\t\t\tif (groups.size === 0) {\n\t\t\t\t\t\t\tstate.outrogroups = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tremaining -= 1;\n\t\t\t\t}\n\t\t\t},\n\t\t\tfalse\n\t\t);\n\t}\n\n\tif (remaining === 0) {\n\t\t// If we're in a controlled each block (i.e. the block is the only child of an\n\t\t// element), and we are removing all items, _and_ there are no out transitions,\n\t\t// we can use the fast path — emptying the element and replacing the anchor.\n\t\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} */ (anchor.parentNode);\n\n\t\t\tclear_text_content(parent_node);\n\t\t\tparent_node.append(anchor);\n\n\t\t\tstate.items.clear();\n\t\t}\n\n\t\tdestroy_effects(state, to_destroy, !fast_path);\n\t} else {\n\t\tgroup = {\n\t\t\tpending: new Set(to_destroy),\n\t\t\tdone: new Set()\n\t\t};\n\n\t\t(state.outrogroups ??= new Set()).add(group);\n\t}\n}\n\n/**\n * @param {EachState} state\n * @param {Effect[]} to_destroy\n * @param {boolean} remove_dom\n */\nfunction destroy_effects(state, to_destroy, remove_dom = true) {\n\t/** @type {Set<Effect> | undefined} */\n\tvar preserved_effects;\n\n\t// The loop-in-a-loop isn't ideal, but we should only hit this in relatively rare cases\n\tif (state.pending.size > 0) {\n\t\tpreserved_effects = new Set();\n\n\t\tfor (const keys of state.pending.values()) {\n\t\t\tfor (const key of keys) {\n\t\t\t\tpreserved_effects.add(/** @type {EachItem} */ (state.items.get(key)).e);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (var i = 0; i < to_destroy.length; i++) {\n\t\tvar e = to_destroy[i];\n\n\t\tif (preserved_effects?.has(e)) {\n\t\t\te.f |= EFFECT_OFFSCREEN;\n\n\t\t\tconst fragment = document.createDocumentFragment();\n\t\t\tmove_effect(e, fragment);\n\t\t} else {\n\t\t\tdestroy_effect(to_destroy[i], remove_dom);\n\t\t}\n\t}\n}\n\n/** @type {TemplateNode} */\nvar offscreen_anchor;\n\n/**\n * @template V\n * @param {Element | Comment} node The next sibling node, or the parent node if this is a 'controlled' block\n * @param {number} flags\n * @param {() => V[]} get_collection\n * @param {(value: V, index: number) => any} get_key\n * @param {(anchor: Node, item: MaybeSource<V>, index: MaybeSource<number>) => void} render_fn\n * @param {null | ((anchor: Node) => void)} fallback_fn\n * @returns {void}\n */\nexport function each(node, flags, get_collection, get_key, render_fn, fallback_fn = null) {\n\tvar anchor = node;\n\n\t/** @type {Map<any, EachItem>} */\n\tvar items = new Map();\n\n\tvar is_controlled = (flags & EACH_IS_CONTROLLED) !== 0;\n\n\tif (is_controlled) {\n\t\tvar parent_node = /** @type {Element} */ (node);\n\n\t\tanchor = hydrating\n\t\t\t? set_hydrate_node(get_first_child(parent_node))\n\t\t\t: parent_node.appendChild(create_text());\n\t}\n\n\tif (hydrating) {\n\t\thydrate_next();\n\t}\n\n\t/** @type {Effect | null} */\n\tvar fallback = null;\n\n\t// TODO: ideally we could use derived for runes mode but because of the ability\n\t// to use a store which can be mutated, we can't do that here as mutating a store\n\t// will still result in the collection array being the same from the store\n\tvar each_array = derived_safe_equal(() => {\n\t\tvar collection = get_collection();\n\n\t\treturn /** @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\tstate.pending.delete(batch);\n\n\t\t// The effect doesn't necessarily re-run in a batch right before that batch commits\n\t\t// (its view of the collection may not have changed), so we read the collection\n\t\t// as the committing batch sees it rather than using the most recent block run's result\n\t\tvar array = get(each_array);\n\n\t\tstate.fallback = fallback;\n\t\treconcile(state, array, anchor, flags, get_key);\n\n\t\tif (fallback !== null) {\n\t\t\tif (array.length === 0) {\n\t\t\t\tif ((fallback.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\t\t\tresume_effect(fallback);\n\t\t\t\t} else {\n\t\t\t\t\tfallback.f ^= EFFECT_OFFSCREEN;\n\t\t\t\t\tmove(fallback, null, anchor);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tpause_effect(fallback, () => {\n\t\t\t\t\t// TODO only null out if no pending batch needs it,\n\t\t\t\t\t// otherwise re-add `fallback.fragment` and move the\n\t\t\t\t\t// effect into it\n\t\t\t\t\tfallback = null;\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param {Batch} batch\n\t */\n\tfunction discard(batch) {\n\t\tstate.pending.delete(batch);\n\t}\n\n\tvar effect = block(() => {\n\t\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\thydrate_node.nodeType === COMMENT_NODE &&\n\t\t\t\t/** @type {Comment} */ (hydrate_node).data === HYDRATION_END\n\t\t\t) {\n\t\t\t\t// The server rendered fewer items than expected,\n\t\t\t\t// so break out and continue appending non-hydrated items\n\t\t\t\tanchor = /** @type {Comment} */ (hydrate_node);\n\t\t\t\tmismatch = true;\n\t\t\t\tset_hydrating(false);\n\t\t\t}\n\n\t\t\tvar value = array[index];\n\t\t\tvar key = get_key(value, index);\n\n\t\t\tif (DEV) {\n\t\t\t\t// Check that the key function is idempotent (returns the same value when called twice)\n\t\t\t\tvar key_again = get_key(value, index);\n\t\t\t\tif (key !== key_again) {\n\t\t\t\t\te.each_key_volatile(String(index), String(key), String(key_again));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar item = first_run ? null : items.get(key);\n\n\t\t\tif (item) {\n\t\t\t\t// update before reconciliation, to trigger any async updates\n\t\t\t\tif (item.v) internal_set(item.v, value);\n\t\t\t\tif (item.i) internal_set(item.i, index);\n\n\t\t\t\tif (defer) {\n\t\t\t\t\tbatch.unskip_effect(item.e);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\titem = create_item(\n\t\t\t\t\titems,\n\t\t\t\t\tfirst_run ? anchor : (offscreen_anchor ??= create_text()),\n\t\t\t\t\tvalue,\n\t\t\t\t\tkey,\n\t\t\t\t\tindex,\n\t\t\t\t\trender_fn,\n\t\t\t\t\tflags,\n\t\t\t\t\tget_collection\n\t\t\t\t);\n\n\t\t\t\tif (!first_run) {\n\t\t\t\t\titem.e.f |= EFFECT_OFFSCREEN;\n\t\t\t\t}\n\n\t\t\t\titems.set(key, item);\n\t\t\t}\n\n\t\t\tkeys.add(key);\n\t\t}\n\n\t\tif (length === 0 && fallback_fn && !fallback) {\n\t\t\tif (first_run) {\n\t\t\t\tfallback = branch(() => fallback_fn(anchor));\n\t\t\t} else {\n\t\t\t\tfallback = branch(() => fallback_fn((offscreen_anchor ??= create_text())));\n\t\t\t\tfallback.f |= EFFECT_OFFSCREEN;\n\t\t\t}\n\t\t}\n\n\t\tif (length > keys.size) {\n\t\t\tif (DEV) {\n\t\t\t\tvalidate_each_keys(array, get_key);\n\t\t\t} else {\n\t\t\t\t// in prod, the additional information isn't printed, so don't bother computing it\n\t\t\t\te.each_key_duplicate('', '', '');\n\t\t\t}\n\t\t}\n\n\t\t// remove excess nodes\n\t\tif (hydrating && length > 0) {\n\t\t\tset_hydrate_node(skip_nodes());\n\t\t}\n\n\t\tif (!first_run) {\n\t\t\tpending.set(batch, keys);\n\n\t\t\tif (defer) {\n\t\t\t\tfor (const [key, item] of items) {\n\t\t\t\t\tif (!keys.has(key)) {\n\t\t\t\t\t\tbatch.skip_effect(item.e);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbatch.oncommit(commit);\n\t\t\t\tbatch.ondiscard(discard);\n\t\t\t} else {\n\t\t\t\tcommit(batch);\n\t\t\t}\n\t\t}\n\n\t\tif (mismatch) {\n\t\t\t// continue in hydration mode\n\t\t\tset_hydrating(true);\n\t\t}\n\n\t\t// When we mount the each block for the first time, the collection won't be\n\t\t// connected to this effect as the effect hasn't finished running yet and its deps\n\t\t// won't be assigned. However, it's possible that when reconciling the each block\n\t\t// that a mutation occurred and it's made the collection MAYBE_DIRTY, so reading the\n\t\t// collection again can provide consistency to the reactive graph again as the deriveds\n\t\t// will now be `CLEAN`.\n\t\tget(each_array);\n\t});\n\n\t/** @type {EachState} */\n\tvar state = { effect, flags, items, pending, outrogroups: null, fallback };\n\n\tfirst_run = false;\n\n\tif (hydrating) {\n\t\tanchor = hydrate_node;\n\t}\n}\n\n/**\n * Skip past any non-branch effects (which could be created with `createSubscriber`, for example) to find the next branch effect\n * @param {Effect | null} effect\n * @returns {Effect | null}\n */\nfunction skip_to_branch(effect) {\n\twhile (effect !== null && (effect.f & BRANCH_EFFECT) === 0) {\n\t\teffect = effect.next;\n\t}\n\treturn effect;\n}\n\n/**\n * Add, remove, or reorder items output by an each block as its input changes\n * @template V\n * @param {EachState} state\n * @param {Array<V>} array\n * @param {Element | Comment | Text} anchor\n * @param {number} flags\n * @param {(value: V, index: number) => any} get_key\n * @returns {void}\n */\nfunction reconcile(state, array, anchor, flags, get_key) {\n\tvar is_animated = (flags & EACH_IS_ANIMATED) !== 0;\n\n\tvar length = array.length;\n\tvar items = state.items;\n\tvar current = skip_to_branch(state.effect.first);\n\n\t/** @type {undefined | Set<Effect>} */\n\tvar seen;\n\n\t/** @type {Effect | null} */\n\tvar prev = null;\n\n\t/** @type {undefined | Set<Effect>} */\n\tvar to_animate;\n\n\t/** @type {Effect[]} */\n\tvar matched = [];\n\n\t/** @type {Effect[]} */\n\tvar stashed = [];\n\n\t/** @type {V} */\n\tvar value;\n\n\t/** @type {any} */\n\tvar key;\n\n\t/** @type {Effect | undefined} */\n\tvar effect;\n\n\t/** @type {number} */\n\tvar i;\n\n\tif (is_animated) {\n\t\tfor (i = 0; i < length; i += 1) {\n\t\t\tvalue = array[i];\n\t\t\tkey = get_key(value, i);\n\t\t\teffect = /** @type {EachItem} */ (items.get(key)).e;\n\n\t\t\t// offscreen == coming in now, no animation in that case,\n\t\t\t// else this would happen https://github.com/sveltejs/svelte/issues/17181\n\t\t\tif ((effect.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\t\teffect.nodes?.a?.measure();\n\t\t\t\t(to_animate ??= new Set()).add(effect);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (i = 0; i < length; i += 1) {\n\t\tvalue = array[i];\n\t\tkey = get_key(value, i);\n\n\t\teffect = /** @type {EachItem} */ (items.get(key)).e;\n\n\t\tif (state.outrogroups !== null) {\n\t\t\tfor (const group of state.outrogroups) {\n\t\t\t\tgroup.pending.delete(effect);\n\t\t\t\tgroup.done.delete(effect);\n\t\t\t}\n\t\t}\n\n\t\tif ((effect.f & INERT) !== 0) {\n\t\t\tresume_effect(effect);\n\t\t\tif (is_animated) {\n\t\t\t\teffect.nodes?.a?.unfix();\n\t\t\t\t(to_animate ??= new Set()).delete(effect);\n\t\t\t}\n\t\t}\n\n\t\tif ((effect.f & EFFECT_OFFSCREEN) !== 0) {\n\t\t\teffect.f ^= EFFECT_OFFSCREEN;\n\n\t\t\tif (effect === current) {\n\t\t\t\tmove(effect, null, anchor);\n\t\t\t} else {\n\t\t\t\tvar next = prev ? prev.next : current;\n\n\t\t\t\tif (effect === state.effect.last) {\n\t\t\t\t\tstate.effect.last = effect.prev;\n\t\t\t\t}\n\n\t\t\t\tif (effect.prev) effect.prev.next = effect.next;\n\t\t\t\tif (effect.next) effect.next.prev = effect.prev;\n\t\t\t\tlink(state, prev, effect);\n\t\t\t\tlink(state, effect, next);\n\n\t\t\t\tmove(effect, next, anchor);\n\t\t\t\tprev = effect;\n\n\t\t\t\tmatched = [];\n\t\t\t\tstashed = [];\n\n\t\t\t\tcurrent = skip_to_branch(prev.next);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif (effect !== current) {\n\t\t\tif (seen !== undefined && seen.has(effect)) {\n\t\t\t\tif (matched.length < stashed.length) {\n\t\t\t\t\t// more efficient to move later items to the front\n\t\t\t\t\tvar start = stashed[0];\n\t\t\t\t\tvar j;\n\n\t\t\t\t\tprev = start.prev;\n\n\t\t\t\t\tvar a = matched[0];\n\t\t\t\t\tvar b = matched[matched.length - 1];\n\n\t\t\t\t\tfor (j = 0; j < matched.length; j += 1) {\n\t\t\t\t\t\tmove(matched[j], start, anchor);\n\t\t\t\t\t}\n\n\t\t\t\t\tfor (j = 0; j < stashed.length; j += 1) {\n\t\t\t\t\t\tseen.delete(stashed[j]);\n\t\t\t\t\t}\n\n\t\t\t\t\tlink(state, a.prev, b.next);\n\t\t\t\t\tlink(state, prev, a);\n\t\t\t\t\tlink(state, b, start);\n\n\t\t\t\t\tcurrent = start;\n\t\t\t\t\tprev = b;\n\t\t\t\t\ti -= 1;\n\n\t\t\t\t\tmatched = [];\n\t\t\t\t\tstashed = [];\n\t\t\t\t} else {\n\t\t\t\t\t// more efficient to move earlier items to the back\n\t\t\t\t\tseen.delete(effect);\n\t\t\t\t\tmove(effect, current, anchor);\n\n\t\t\t\t\tlink(state, effect.prev, effect.next);\n\t\t\t\t\tlink(state, effect, prev === null ? state.effect.first : prev.next);\n\t\t\t\t\tlink(state, prev, effect);\n\n\t\t\t\t\tprev = effect;\n\t\t\t\t}\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tmatched = [];\n\t\t\tstashed = [];\n\n\t\t\twhile (current !== null && current !== effect) {\n\t\t\t\t(seen ??= new Set()).add(current);\n\t\t\t\tstashed.push(current);\n\t\t\t\tcurrent = skip_to_branch(current.next);\n\t\t\t}\n\n\t\t\tif (current === null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\tif ((effect.f & EFFECT_OFFSCREEN) === 0) {\n\t\t\tmatched.push(effect);\n\t\t}\n\n\t\tprev = effect;\n\t\tcurrent = skip_to_branch(effect.next);\n\t}\n\n\tif (state.outrogroups !== null) {\n\t\tfor (const group of state.outrogroups) {\n\t\t\tif (group.pending.size === 0) {\n\t\t\t\tdestroy_effects(state, array_from(group.done));\n\t\t\t\tstate.outrogroups?.delete(group);\n\t\t\t}\n\t\t}\n\n\t\tif (state.outrogroups.size === 0) {\n\t\t\tstate.outrogroups = null;\n\t\t}\n\t}\n\n\tif (current !== null || seen !== undefined) {\n\t\t/** @type {Effect[]} */\n\t\tvar to_destroy = [];\n\n\t\tif (seen !== undefined) {\n\t\t\tfor (effect of seen) {\n\t\t\t\tif ((effect.f & INERT) === 0) {\n\t\t\t\t\tto_destroy.push(effect);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\twhile (current !== null) {\n\t\t\t// If the each block isn't inert, then inert effects are currently outroing and will be removed once the transition is finished\n\t\t\tif ((current.f & INERT) === 0 && current !== state.fallback) {\n\t\t\t\tto_destroy.push(current);\n\t\t\t}\n\n\t\t\tcurrent = skip_to_branch(current.next);\n\t\t}\n\n\t\tvar destroy_length = to_destroy.length;\n\n\t\tif (destroy_length > 0) {\n\t\t\tvar controlled_anchor = (flags & EACH_IS_CONTROLLED) !== 0 && length === 0 ? anchor : null;\n\n\t\t\tif (is_animated) {\n\t\t\t\tfor (i = 0; i < destroy_length; i += 1) {\n\t\t\t\t\tto_destroy[i].nodes?.a?.measure();\n\t\t\t\t}\n\n\t\t\t\tfor (i = 0; i < destroy_length; i += 1) {\n\t\t\t\t\tto_destroy[i].nodes?.a?.fix();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpause_effects(state, to_destroy, controlled_anchor);\n\t\t}\n\t}\n\n\tif (is_animated) {\n\t\tqueue_micro_task(() => {\n\t\t\tif (to_animate === undefined) return;\n\t\t\tfor (effect of to_animate) {\n\t\t\t\teffect.nodes?.a?.apply();\n\t\t\t}\n\t\t});\n\t}\n}\n\n/**\n * @template V\n * @param {Map<any, EachItem>} items\n * @param {Node} anchor\n * @param {V} value\n * @param {unknown} key\n * @param {number} index\n * @param {(anchor: Node, item: 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\tdest.before(node);\n\n\t\tif (node === end) {\n\t\t\treturn;\n\t\t}\n\n\t\tnode = next_node;\n\t}\n}\n\n/**\n * @param {EachState} state\n * @param {Effect | null} prev\n * @param {Effect | null} next\n */\nfunction link(state, prev, next) {\n\tif (prev === null) {\n\t\tstate.effect.first = next;\n\t} else {\n\t\tprev.next = next;\n\t}\n\n\tif (next === null) {\n\t\tstate.effect.last = prev;\n\t} else {\n\t\tnext.prev = prev;\n\t}\n}\n\n/**\n * @param {Array<any>} array\n * @param {(item: any, index: number) => string} key_fn\n * @returns {void}\n */\nfunction validate_each_keys(array, key_fn) {\n\tconst keys = new Map();\n\tconst length = array.length;\n\n\tfor (let i = 0; i < length; i++) {\n\t\tconst key = key_fn(array[i], i);\n\n\t\tif (keys.has(key)) {\n\t\t\tconst a = String(keys.get(key));\n\t\t\tconst b = String(i);\n\n\t\t\t/** @type {string | null} */\n\t\t\tlet k = String(key);\n\t\t\tif (k.startsWith('[object ')) k = null;\n\n\t\t\te.each_key_duplicate(a, b, k);\n\t\t}\n\n\t\tkeys.set(key, i);\n\t}\n}\n","/** @import { Effect, TemplateNode } from '#client' */\n/** @import {} from 'trusted-types' */\nimport {\n\tFILENAME,\n\tHYDRATION_ERROR,\n\tNAMESPACE_SVG,\n\tNAMESPACE_MATHML\n} from '../../../../constants.js';\nimport { remove_effect_dom, template_effect } from '../../reactivity/effects.js';\nimport { hydrate_next, hydrate_node, hydrating, set_hydrate_node } from '../hydration.js';\n\nimport { assign_nodes } from '../template.js';\nimport * as w from '../../warnings.js';\nimport { hash, sanitize_location } from '../../../../utils.js';\nimport { DEV } from 'esm-env';\nimport { dev_current_component_function } from '../../context.js';\nimport { create_element, get_first_child, get_next_sibling } from '../operations.js';\nimport { active_effect } from '../../runtime.js';\nimport { COMMENT_NODE } from '#client/constants';\n\n/**\n * @param {Element} element\n * @param {string | null} server_hash\n * @param {string | TrustedHTML} value\n */\nfunction check_hash(element, server_hash, value) {\n\tif (!server_hash || server_hash === hash(String(value ?? ''))) return;\n\n\tlet location;\n\n\t// @ts-expect-error\n\tconst loc = element.__svelte_meta?.loc;\n\tif (loc) {\n\t\tlocation = `near ${loc.file}:${loc.line}:${loc.column}`;\n\t} else if (dev_current_component_function?.[FILENAME]) {\n\t\tlocation = `in ${dev_current_component_function[FILENAME]}`;\n\t}\n\n\tw.hydration_html_changed(sanitize_location(location));\n}\n\n/**\n * @param {Element | Text | Comment} node\n * @param {() => string | TrustedHTML} get_value\n * @param {boolean} [is_controlled]\n * @param {boolean} [svg]\n * @param {boolean} [mathml]\n * @param {boolean} [skip_warning]\n * @returns {void}\n */\nexport function html(\n\tnode,\n\tget_value,\n\tis_controlled = false,\n\tsvg = false,\n\tmathml = false,\n\tskip_warning = false\n) {\n\tvar anchor = node;\n\n\t/** @type {string | TrustedHTML} */\n\tvar value = '';\n\n\tif (is_controlled) {\n\t\tvar parent_node = /** @type {Element} */ (node);\n\n\t\tif (hydrating) {\n\t\t\tanchor = set_hydrate_node(get_first_child(parent_node));\n\t\t}\n\t}\n\n\ttemplate_effect(() => {\n\t\tvar effect = /** @type {Effect} */ (active_effect);\n\n\t\tif (value === (value = get_value() ?? '')) {\n\t\t\tif (hydrating) hydrate_next();\n\t\t\treturn;\n\t\t}\n\n\t\tif (is_controlled && !hydrating) {\n\t\t\t// When @html is the only child, use innerHTML directly.\n\t\t\t// This also handles contenteditable, where the user may delete the anchor comment.\n\t\t\teffect.nodes = null;\n\t\t\tparent_node.innerHTML = /** @type {string} */ (value);\n\n\t\t\tif (value !== '') {\n\t\t\t\tassign_nodes(\n\t\t\t\t\t/** @type {TemplateNode} */ (get_first_child(parent_node)),\n\t\t\t\t\t/** @type {TemplateNode} */ (parent_node.lastChild)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (effect.nodes !== null) {\n\t\t\tremove_effect_dom(effect.nodes.start, /** @type {TemplateNode} */ (effect.nodes.end));\n\t\t\teffect.nodes = null;\n\t\t}\n\n\t\tif (value === '') return;\n\n\t\tif (hydrating) {\n\t\t\t// We're deliberately not trying to repair mismatches between server and client,\n\t\t\t// as it's costly and error-prone (and it's an edge case to have a mismatch anyway)\n\t\t\tvar hash = /** @type {Comment} */ (hydrate_node).data;\n\n\t\t\t/** @type {TemplateNode | null} */\n\t\t\tvar next = hydrate_next();\n\t\t\tvar last = next;\n\n\t\t\twhile (\n\t\t\t\tnext !== null &&\n\t\t\t\t(next.nodeType !== COMMENT_NODE || /** @type {Comment} */ (next).data !== '')\n\t\t\t) {\n\t\t\t\tlast = next;\n\t\t\t\tnext = get_next_sibling(next);\n\t\t\t}\n\n\t\t\tif (next === null) {\n\t\t\t\tw.hydration_mismatch();\n\t\t\t\tthrow HYDRATION_ERROR;\n\t\t\t}\n\n\t\t\tif (DEV && !skip_warning) {\n\t\t\t\tcheck_hash(/** @type {Element} */ (next.parentNode), hash, value);\n\t\t\t}\n\n\t\t\tassign_nodes(hydrate_node, last);\n\t\t\tanchor = set_hydrate_node(next);\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't use create_fragment_with_script_from_html here because that would mean script tags are executed.\n\t\t// @html is basically `.innerHTML = ...` and that doesn't execute scripts either due to security reasons.\n\t\t// Use a <template>, <svg>, or <math> wrapper depending on context. If value is a TrustedHTML object,\n\t\t// it will be assigned directly to innerHTML without coercion — this allows {@html policy.createHTML(...)} to work.\n\t\tvar ns = svg ? NAMESPACE_SVG : mathml ? NAMESPACE_MATHML : undefined;\n\t\tvar wrapper = /** @type {HTMLTemplateElement | SVGElement | MathMLElement} */ (\n\t\t\tcreate_element(svg ? 'svg' : mathml ? 'math' : 'template', ns)\n\t\t);\n\t\twrapper.innerHTML = /** @type {any} */ (value);\n\n\t\t/** @type {DocumentFragment | Element} */\n\t\tvar node = svg || mathml ? wrapper : /** @type {HTMLTemplateElement} */ (wrapper).content;\n\n\t\tassign_nodes(\n\t\t\t/** @type {TemplateNode} */ (get_first_child(node)),\n\t\t\t/** @type {TemplateNode} */ (node.lastChild)\n\t\t);\n\n\t\tif (svg || mathml) {\n\t\t\twhile (get_first_child(node)) {\n\t\t\t\tanchor.before(/** @type {TemplateNode} */ (get_first_child(node)));\n\t\t\t}\n\t\t} else {\n\t\t\tanchor.before(node);\n\t\t}\n\t});\n}\n","/** @import { Snippet } from 'svelte' */\n/** @import { TemplateNode } from '#client' */\n/** @import { Getters } from '#shared' */\nimport { EFFECT_TRANSPARENT, ELEMENT_NODE } from '#client/constants';\nimport { block, teardown } from '../../reactivity/effects.js';\nimport {\n\tdev_current_component_function,\n\tset_dev_current_component_function\n} from '../../context.js';\nimport { hydrate_next, hydrate_node, hydrating } from '../hydration.js';\nimport { create_fragment_from_html } from '../reconciler.js';\nimport { assign_nodes } from '../template.js';\nimport * as w from '../../warnings.js';\nimport * as e from '../../errors.js';\nimport { DEV } from 'esm-env';\nimport { get_first_child, get_next_sibling } from '../operations.js';\nimport { prevent_snippet_stringification } from '../../../shared/validate.js';\nimport { BranchManager } from './branches.js';\n\n/**\n * @template {(node: TemplateNode, ...args: any[]) => void} SnippetFn\n * @param {TemplateNode} node\n * @param {() => SnippetFn | null | undefined} get_snippet\n * @param {(() => any)[]} args\n * @returns {void}\n */\nexport function snippet(node, get_snippet, ...args) {\n\tvar branches = new BranchManager(node);\n\n\tblock(() => {\n\t\tconst snippet = get_snippet() ?? null;\n\n\t\tif (DEV && snippet == null) {\n\t\t\te.invalid_snippet();\n\t\t}\n\n\t\tbranches.ensure(snippet, snippet && ((anchor) => snippet(anchor, ...args)));\n\t}, EFFECT_TRANSPARENT);\n}\n\n/**\n * In development, wrap the snippet function so that it passes validation, and so that the\n * correct component context is set for ownership checks\n * @param {any} component\n * @param {(node: TemplateNode, ...args: any[]) => void} fn\n */\nexport function wrap_snippet(component, fn) {\n\tconst snippet = (/** @type {TemplateNode} */ node, /** @type {any[]} */ ...args) => {\n\t\tvar previous_component_function = dev_current_component_function;\n\t\tset_dev_current_component_function(component);\n\n\t\ttry {\n\t\t\treturn fn(node, ...args);\n\t\t} finally {\n\t\t\tset_dev_current_component_function(previous_component_function);\n\t\t}\n\t};\n\n\tprevent_snippet_stringification(snippet);\n\n\treturn snippet;\n}\n\n/**\n * Create a snippet programmatically\n * @template {unknown[]} Params\n * @param {(...params: Getters<Params>) => {\n *   render: () => string\n *   setup?: (element: Element) => void | (() => void)\n * }} fn\n * @returns {Snippet<Params>}\n */\nexport function createRawSnippet(fn) {\n\t// @ts-expect-error the types are a lie\n\treturn (/** @type {TemplateNode} */ anchor, /** @type {Getters<Params>} */ ...params) => {\n\t\tvar snippet = fn(...params);\n\n\t\t/** @type {Element} */\n\t\tvar element;\n\n\t\tif (hydrating) {\n\t\t\telement = /** @type {Element} */ (hydrate_node);\n\t\t\thydrate_next();\n\t\t} else {\n\t\t\tvar html = snippet.render().trim();\n\t\t\tvar fragment = create_fragment_from_html(html);\n\t\t\telement = /** @type {Element} */ (get_first_child(fragment));\n\n\t\t\tif (DEV && (get_next_sibling(element) !== null || element.nodeType !== ELEMENT_NODE)) {\n\t\t\t\tw.invalid_raw_snippet_render();\n\t\t\t}\n\n\t\t\tanchor.before(element);\n\t\t}\n\n\t\tconst result = snippet.setup?.(element);\n\t\tassign_nodes(element, element);\n\n\t\tif (typeof result === 'function') {\n\t\t\tteardown(result);\n\t\t}\n\t};\n}\n","/** @import { TemplateNode, Dom } from '#client' */\nimport { EFFECT_TRANSPARENT } from '#client/constants';\nimport { block } from '../../reactivity/effects.js';\nimport {\n\thydrate_next,\n\thydrate_node,\n\thydrating,\n\tread_hydration_instruction,\n\tset_hydrate_node,\n\tset_hydrating,\n\tskip_nodes\n} from '../hydration.js';\nimport { BranchManager } from './branches.js';\nimport { HYDRATION_START, HYDRATION_START_ELSE } from '../../../../constants.js';\n\n/**\n * @template P\n * @template {(props: P) => void} C\n * @param {TemplateNode} node\n * @param {() => C} get_component\n * @param {(anchor: TemplateNode, component: C) => Dom | void} render_fn\n * @returns {void}\n */\nexport function component(node, get_component, render_fn) {\n\t/** @type {TemplateNode | undefined} */\n\tvar hydration_start_node;\n\n\tif (hydrating) {\n\t\thydration_start_node = hydrate_node;\n\t\thydrate_next();\n\t}\n\n\tvar branches = new BranchManager(node);\n\n\tblock(() => {\n\t\tvar component = get_component() ?? null;\n\n\t\tif (hydrating) {\n\t\t\tvar data = read_hydration_instruction(/** @type {TemplateNode} */ (hydration_start_node));\n\n\t\t\tvar server_had_component = data === HYDRATION_START;\n\t\t\tvar client_has_component = component !== null;\n\n\t\t\tif (server_had_component !== client_has_component) {\n\t\t\t\t// Hydration mismatch: skip the server-rendered nodes and render fresh\n\t\t\t\tvar anchor = skip_nodes();\n\n\t\t\t\tset_hydrate_node(anchor);\n\t\t\t\tbranches.anchor = anchor;\n\n\t\t\t\tset_hydrating(false);\n\t\t\t\tbranches.ensure(component, component && ((target) => render_fn(target, component)));\n\t\t\t\tset_hydrating(true);\n\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tbranches.ensure(component, component && ((target) => render_fn(target, component)));\n\t}, EFFECT_TRANSPARENT);\n}\n","/** @import { Raf } from '#client' */\nimport { noop } from '../shared/utils.js';\n\nimport { BROWSER } from 'esm-env';\n\nconst now = BROWSER ? () => performance.now() : () => Date.now();\n\n/** @type {Raf} */\nexport const raf = {\n\t// don't access requestAnimationFrame eagerly outside method\n\t// this allows basic testing of user code without JSDOM\n\t// bunder will eval and remove ternary when the user's app is built\n\ttick: /** @param {any} _ */ (_) => (BROWSER ? requestAnimationFrame : noop)(_),\n\tnow: () => now(),\n\ttasks: new Set()\n};\n","/** @import { TaskCallback, Task, TaskEntry } from '#client' */\nimport { raf } from './timing.js';\n\n// TODO move this into timing.js where it probably belongs\n\n/**\n * @returns {void}\n */\nfunction run_tasks() {\n\t// use `raf.now()` instead of the `requestAnimationFrame` callback argument, because\n\t// otherwise things can get wonky https://github.com/sveltejs/svelte/pull/14541\n\tconst now = raf.now();\n\n\traf.tasks.forEach((task) => {\n\t\tif (!task.c(now)) {\n\t\t\traf.tasks.delete(task);\n\t\t\ttask.f();\n\t\t}\n\t});\n\n\tif (raf.tasks.size !== 0) {\n\t\traf.tick(run_tasks);\n\t}\n}\n\n/**\n * Creates a new task that runs on each raf frame\n * until it returns a falsy value or is aborted\n * @param {TaskCallback} callback\n * @returns {Task}\n */\nexport function loop(callback) {\n\t/** @type {TaskEntry} */\n\tlet task;\n\n\tif (raf.tasks.size === 0) {\n\t\traf.tick(run_tasks);\n\t}\n\n\treturn {\n\t\tpromise: new Promise((fulfill) => {\n\t\t\traf.tasks.add((task = { c: callback, f: fulfill }));\n\t\t}),\n\t\tabort() {\n\t\t\traf.tasks.delete(task);\n\t\t}\n\t};\n}\n","/** @import { AnimateFn, Animation, AnimationConfig, EachItem, Effect, EffectNodes, TransitionFn, TransitionManager } from '#client' */\nimport { noop, is_function } from '../../../shared/utils.js';\nimport { effect } from '../../reactivity/effects.js';\nimport { active_effect, untrack } from '../../runtime.js';\nimport { loop } from '../../loop.js';\nimport { should_intro } from '../../render.js';\nimport { TRANSITION_GLOBAL, TRANSITION_IN, TRANSITION_OUT } from '../../../../constants.js';\nimport { BLOCK_EFFECT, REACTION_RAN, EFFECT_TRANSPARENT } from '#client/constants';\nimport { queue_micro_task } from '../task.js';\nimport { without_reactive_context } from './bindings/shared.js';\n\n/**\n * @param {Element} element\n * @param {'introstart' | 'introend' | 'outrostart' | 'outroend'} type\n * @returns {void}\n */\nfunction dispatch_event(element, type) {\n\twithout_reactive_context(() => {\n\t\telement.dispatchEvent(new CustomEvent(type));\n\t});\n}\n\n/**\n * Converts a property to the camel-case format expected by Element.animate(), KeyframeEffect(), and KeyframeEffect.setKeyframes().\n * @param {string} style\n * @returns {string}\n */\nfunction css_property_to_camelcase(style) {\n\t// in compliance with spec\n\tif (style === 'float') return 'cssFloat';\n\tif (style === 'offset') return 'cssOffset';\n\n\t// do not rename custom @properties\n\tif (style.startsWith('--')) return style;\n\n\tconst parts = style.split('-');\n\tif (parts.length === 1) return parts[0];\n\treturn (\n\t\tparts[0] +\n\t\tparts\n\t\t\t.slice(1)\n\t\t\t.map(/** @param {any} word */ (word) => word[0].toUpperCase() + word.slice(1))\n\t\t\t.join('')\n\t);\n}\n\n/**\n * @param {string} css\n * @returns {Keyframe}\n */\nfunction css_to_keyframe(css) {\n\t/** @type {Keyframe} */\n\tconst keyframe = {};\n\tconst parts = css.split(';');\n\tfor (const part of parts) {\n\t\tconst [property, value] = part.split(':');\n\t\tif (!property || value === undefined) break;\n\n\t\tconst formatted_property = css_property_to_camelcase(property.trim());\n\t\tkeyframe[formatted_property] = value.trim();\n\t}\n\treturn keyframe;\n}\n\n/** @param {number} t */\nconst linear = (t) => t;\n\n/** @type {Effect | null} */\nlet animation_effect_override = null;\n\n/** @param {Effect | null} v */\nexport function set_animation_effect_override(v) {\n\tanimation_effect_override = v;\n}\n\n/**\n * Called inside keyed `{#each ...}` blocks (as `$.animation(...)`). This creates an animation manager\n * and attaches it to the block, so that moves can be animated following reconciliation.\n * @template P\n * @param {Element} element\n * @param {() => AnimateFn<P | undefined>} get_fn\n * @param {(() => P) | null} get_params\n */\nexport function animation(element, get_fn, get_params) {\n\tvar effect = animation_effect_override ?? /** @type {Effect} */ (active_effect);\n\tvar nodes = /** @type {EffectNodes} */ (effect.nodes);\n\n\t/** @type {DOMRect} */\n\tvar from;\n\n\t/** @type {DOMRect} */\n\tvar to;\n\n\t/** @type {Animation | undefined} */\n\tvar animation;\n\n\t/** @type {null | { position: string, width: string, height: string, transform: string }} */\n\tvar original_styles = null;\n\n\tnodes.a ??= {\n\t\telement,\n\t\tmeasure() {\n\t\t\tfrom = this.element.getBoundingClientRect();\n\t\t},\n\t\tapply() {\n\t\t\tanimation?.abort();\n\n\t\t\tto = this.element.getBoundingClientRect();\n\n\t\t\tif (\n\t\t\t\tfrom.left !== to.left ||\n\t\t\t\tfrom.right !== to.right ||\n\t\t\t\tfrom.top !== to.top ||\n\t\t\t\tfrom.bottom !== to.bottom\n\t\t\t) {\n\t\t\t\tconst options = get_fn()(this.element, { from, to }, get_params?.());\n\n\t\t\t\tanimation = animate(\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 { create_element, create_text, get_first_child } from '../operations.js';\nimport { block, teardown } from '../../reactivity/effects.js';\nimport { set_should_intro } from '../../render.js';\nimport { active_effect } from '../../runtime.js';\nimport { component_context, dev_stack } from '../../context.js';\nimport { DEV } from 'esm-env';\nimport { EFFECT_TRANSPARENT, ELEMENT_NODE } from '#client/constants';\nimport { assign_nodes } from '../template.js';\nimport { is_raw_text_element } from '../../../../utils.js';\nimport { BranchManager } from './branches.js';\nimport { set_animation_effect_override } from '../elements/transitions.js';\n\n/**\n * @param {Comment | Element} node\n * @param {() => string} get_tag\n * @param {boolean} is_svg\n * @param {undefined | ((element: Element, anchor: Node | null) => void)} render_fn,\n * @param {undefined | (() => string)} get_namespace\n * @param {undefined | [number, number]} location\n * @returns {void}\n */\nexport function element(node, get_tag, is_svg, render_fn, get_namespace, location) {\n\tlet was_hydrating = hydrating;\n\n\tif (hydrating) {\n\t\thydrate_next();\n\t}\n\n\tvar filename = DEV && location && component_context?.function[FILENAME];\n\n\t/** @type {null | Element} */\n\tvar element = null;\n\n\tif (hydrating && hydrate_node.nodeType === ELEMENT_NODE) {\n\t\telement = /** @type {Element} */ (hydrate_node);\n\t\thydrate_next();\n\t}\n\n\tvar anchor = /** @type {TemplateNode} */ (hydrating ? hydrate_node : node);\n\n\t/**\n\t * We track this so we can set it when changing the element, allowing any\n\t * `animate:` directive to bind itself to the correct block\n\t */\n\tvar parent_effect = /** @type {Effect} */ (active_effect);\n\n\tvar branches = new BranchManager(anchor, false);\n\n\tblock(() => {\n\t\tconst next_tag = get_tag() || null;\n\t\tvar ns = get_namespace\n\t\t\t? get_namespace()\n\t\t\t: is_svg || next_tag === 'svg'\n\t\t\t\t? NAMESPACE_SVG\n\t\t\t\t: undefined;\n\n\t\tif (next_tag === null) {\n\t\t\tbranches.ensure(null, null);\n\t\t\tset_should_intro(true);\n\t\t\treturn;\n\t\t}\n\n\t\tbranches.ensure(next_tag, (anchor) => {\n\t\t\tif (next_tag) {\n\t\t\t\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};\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\telement.append((tmp_comment = document.createComment('')));\n\t\t\t\t\t}\n\n\t\t\t\t\t// If hydrating, use the existing ssr comment as the anchor so that the\n\t\t\t\t\t// inner open and close methods can pick up the existing nodes correctly\n\t\t\t\t\tvar child_anchor = hydrating\n\t\t\t\t\t\t? get_first_child(element)\n\t\t\t\t\t\t: element.appendChild(create_text());\n\n\t\t\t\t\tif (hydrating) {\n\t\t\t\t\t\tif (child_anchor === null) {\n\t\t\t\t\t\t\tset_hydrating(false);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tset_hydrate_node(child_anchor);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tset_animation_effect_override(parent_effect);\n\n\t\t\t\t\t// `child_anchor` is undefined if this is a void element, but we still\n\t\t\t\t\t// need to call `render_fn` in order to run actions etc. If the element\n\t\t\t\t\t// contains children, it's a user error (which is warned on elsewhere)\n\t\t\t\t\t// and the DOM will be silently discarded\n\t\t\t\t\trender_fn(element, child_anchor);\n\t\t\t\t\ttmp_comment?.remove();\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) anchor.before(element);\n\t\t\t}\n\n\t\t\tif (hydrating) {\n\t\t\t\tset_hydrate_node(anchor);\n\t\t\t}\n\t\t});\n\n\t\t// revert to the default state after the effect has been created\n\t\tset_should_intro(true);\n\n\t\treturn () => {\n\t\t\tif (next_tag) {\n\t\t\t\t// if we're in this callback because we're re-running the effect,\n\t\t\t\t// disable intros (unless no element is currently displayed)\n\t\t\t\tset_should_intro(false);\n\t\t\t}\n\t\t};\n\t}, EFFECT_TRANSPARENT);\n\n\tteardown(() => {\n\t\tset_should_intro(true);\n\t});\n\n\tif (was_hydrating) {\n\t\tset_hydrating(true);\n\t\tset_hydrate_node(anchor);\n\t}\n}\n","/** @import { TemplateNode } from '#client' */\nimport { hydrate_node, hydrating, set_hydrate_node, set_hydrating } from '../hydration.js';\nimport { create_text, get_first_child, get_next_sibling } from '../operations.js';\nimport { block, 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(head_anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ (head_anchor).data !== hash)\n\t\t) {\n\t\t\thead_anchor = get_next_sibling(head_anchor);\n\t\t}\n\n\t\t// If we can't find an opening hydration marker, skip hydration (this can happen\n\t\t// if a framework rendered body but not head content)\n\t\tif (head_anchor === null) {\n\t\t\tset_hydrating(false);\n\t\t} else {\n\t\t\tvar start = /** @type {TemplateNode} */ (get_next_sibling(head_anchor));\n\t\t\thead_anchor.remove(); // in case this component is repeated\n\n\t\t\tset_hydrate_node(start);\n\t\t}\n\t}\n\n\tif (!hydrating) {\n\t\tanchor = document.head.appendChild(create_text());\n\t}\n\n\ttry {\n\t\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 } 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 (!target.querySelector('#' + css.hash)) {\n\t\t\tconst style = create_element('style');\n\t\t\tstyle.id = css.hash;\n\t\t\tstyle.textContent = css.code;\n\n\t\t\ttarget.appendChild(style);\n\n\t\t\tif (DEV) {\n\t\t\t\tregister_style(css.hash, style);\n\t\t\t}\n\t\t}\n\t});\n}\n","/** @import { 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","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 { to_class } from '../../../shared/attributes.js';\nimport { CLASS_CACHE } from '../../constants.js';\nimport { hydrating } from '../hydration.js';\n\n/**\n * @param {Element} dom\n * @param {boolean | number} is_html\n * @param {string | null} value\n * @param {string} [hash]\n * @param {Record<string, any>} [prev_classes]\n * @param {Record<string, any>} [next_classes]\n * @returns {Record<string, boolean> | undefined}\n */\nexport function set_class(dom, is_html, value, hash, prev_classes, next_classes) {\n\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) {\n\t\tvar next_class_name = to_class(value, hash, next_classes);\n\n\t\tif (!hydrating || next_class_name !== dom.getAttribute('class')) {\n\t\t\t// Removing the attribute when the value is only an empty string causes\n\t\t\t// performance issues vs simply making the className an empty string. So\n\t\t\t// we should only remove the class if the value is nullish\n\t\t\t// and there no hash/directives :\n\t\t\tif (next_class_name == null) {\n\t\t\t\tdom.removeAttribute('class');\n\t\t\t} else if (is_html) {\n\t\t\t\tdom.className = next_class_name;\n\t\t\t} else {\n\t\t\t\tdom.setAttribute('class', next_class_name);\n\t\t\t}\n\t\t}\n\n\t\t/** @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\tdom.classList.toggle(key, is_present);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn next_classes;\n}\n","import { to_style } from '../../../shared/attributes.js';\nimport { STYLE_CACHE } from '../../constants.js';\nimport { hydrating } from '../hydration.js';\n\n/**\n * @param {Element & ElementCSSInlineStyle} dom\n * @param {Record<string, any>} prev\n * @param {Record<string, any>} next\n * @param {string} [priority]\n */\nfunction update_styles(dom, prev = {}, next, priority) {\n\tfor (var key in next) {\n\t\tvar value = next[key];\n\n\t\tif (prev[key] !== value) {\n\t\t\tif (next[key] == null) {\n\t\t\t\tdom.style.removeProperty(key);\n\t\t\t} else {\n\t\t\t\tdom.style.setProperty(key, value, priority);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * @param {Element & ElementCSSInlineStyle} dom\n * @param {string | null} value\n * @param {Record<string, any> | [Record<string, any>, Record<string, any>]} [prev_styles]\n * @param {Record<string, any> | [Record<string, any>, Record<string, any>]} [next_styles]\n */\nexport function set_style(dom, value, prev_styles, next_styles) {\n\tvar prev = /** @type {any} */ (dom)[STYLE_CACHE];\n\n\tif (hydrating || prev !== value) {\n\t\tvar next_style_attr = to_style(value, next_styles);\n\n\t\tif (!hydrating || next_style_attr !== dom.getAttribute('style')) {\n\t\t\tif (next_style_attr == null) {\n\t\t\t\tdom.removeAttribute('style');\n\t\t\t} else {\n\t\t\t\tdom.style.cssText = next_style_attr;\n\t\t\t}\n\t\t}\n\n\t\t/** @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 { effect, teardown } from '../../../reactivity/effects.js';\nimport { listen_to_event_and_reset_event } from './shared.js';\nimport { is } from '../../../proxy.js';\nimport { is_array } from '../../../../shared/utils.js';\nimport * as w from '../../../warnings.js';\nimport { Batch, current_batch, previous_batch } from '../../../reactivity/batch.js';\nimport { async_mode_flag } from '../../../../flags/index.js';\n\n/**\n * 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\tif (!option.hasAttribute('selected')) option.setAttribute('selected', '');\n\t} else {\n\t\toption.removeAttribute('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// In sync mode render effects are executed during tree traversal -> needs current_batch\n\t\t\t// In async mode render effects are flushed once batch resolved, at which point current_batch is null -> needs previous_batch\n\t\t\tvar batch = /** @type {Batch} */ (async_mode_flag ? previous_batch : current_batch);\n\n\t\t\t// Don't update the <select> if it is focused. We can get here if, for example,\n\t\t\t// an update is deferred because of async work depending on the select:\n\t\t\t//\n\t\t\t// <select bind:value={selected}>...</select>\n\t\t\t// <p>{await find(selected)}</p>\n\t\t\tif (batches.has(batch)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tselect_option(select, value, mounting);\n\n\t\t// Mounting and value undefined -> take selection from dom\n\t\tif (mounting && value === undefined) {\n\t\t\t/** @type {HTMLOptionElement | null} */\n\t\t\tvar selected_option = select.querySelector(':checked');\n\t\t\tif (selected_option !== null) {\n\t\t\t\tvalue = get_option_value(selected_option);\n\t\t\t\tset(value);\n\t\t\t}\n\t\t}\n\n\t\t// @ts-ignore\n\t\tselect.__value = value;\n\t\tmounting = false;\n\t});\n}\n\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 { Blocker, Effect } from '#client' */\nimport { DEV } from 'esm-env';\nimport { hydrating, set_hydrating } from '../hydration.js';\nimport { get_descriptors, get_prototype_of } from '../../../shared/utils.js';\nimport { create_event, delegate, delegated, event, event_symbol } from './events.js';\nimport { add_form_reset_listener, autofocus } from './misc.js';\nimport * as w from '../../warnings.js';\nimport {\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';\n\nexport const CLASS = Symbol('class');\nexport const STYLE = Symbol('style');\n\nconst IS_CUSTOM_ELEMENT = Symbol('is custom element');\nconst IS_HTML = Symbol('is html');\n\nconst LINK_TAG = IS_XHTML ? 'link' : 'LINK';\nconst INPUT_TAG = IS_XHTML ? 'input' : 'INPUT';\nconst OPTION_TAG = IS_XHTML ? 'option' : 'OPTION';\nconst SELECT_TAG = IS_XHTML ? 'select' : 'SELECT';\nconst PROGRESS_TAG = IS_XHTML ? 'progress' : 'PROGRESS';\n\n/**\n * The value/checked attribute in the template actually corresponds to the defaultValue property, so we need\n * to remove it upon hydration to avoid a bug when someone resets the form value.\n * @param {HTMLInputElement} input\n * @returns {void}\n */\nexport function remove_input_defaults(input) {\n\tif (!hydrating) return;\n\n\tvar already_removed = false;\n\n\t// We try and remove the default attributes later, rather than sync during hydration.\n\t// Doing it sync during hydration has a negative impact on performance, but deferring the\n\t// work in an idle task alleviates this greatly. If a form reset event comes in before\n\t// the idle callback, then we ensure the input defaults are cleared just before.\n\tvar remove_defaults = () => {\n\t\tif (already_removed) return;\n\t\talready_removed = true;\n\n\t\t// Remove the attributes but preserve the values\n\t\tif (input.hasAttribute('value')) {\n\t\t\tvar value = input.value;\n\t\t\tset_attribute(input, 'value', null);\n\t\t\tinput.value = value;\n\t\t}\n\n\t\tif (input.hasAttribute('checked')) {\n\t\t\tvar checked = input.checked;\n\t\t\tset_attribute(input, 'checked', null);\n\t\t\tinput.checked = checked;\n\t\t}\n\t};\n\n\t/** @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// @ts-expect-error\n\t\t// `progress` elements always need their value set when it's `0`\n\t\t(element.value === value && (value !== 0 || element.nodeName !== PROGRESS_TAG))\n\t) {\n\t\treturn;\n\t}\n\n\t// @ts-expect-error\n\telement.value = value ?? '';\n}\n\n/**\n * @param {Element} element\n * @param {boolean} checked\n */\nexport function set_checked(element, checked) {\n\tvar attributes = get_attributes(element);\n\n\tif (\n\t\tattributes.checked ===\n\t\t(attributes.checked =\n\t\t\t// treat null and undefined the same for the initial value\n\t\t\tchecked ?? undefined)\n\t) {\n\t\treturn;\n\t}\n\n\t// @ts-expect-error\n\telement.checked = checked;\n}\n\n/**\n * Applies the default checked property without influencing the current checked property.\n * @param {HTMLInputElement} element\n * @param {boolean} checked\n */\nexport function set_default_checked(element, checked) {\n\tconst existing_value = element.checked;\n\telement.defaultChecked = checked;\n\telement.checked = existing_value;\n}\n\n/**\n * Applies the default value property without influencing the current value property.\n * @param {HTMLInputElement | HTMLTextAreaElement} element\n * @param {string} value\n */\nexport function set_default_value(element, value) {\n\tconst existing_value = element.value;\n\telement.defaultValue = value;\n\telement.value = existing_value;\n}\n\n/**\n * @param {Element} element\n * @param {string} attribute\n * @param {string | null} value\n * @param {boolean} [skip_warning]\n */\nexport function set_attribute(element, attribute, value, skip_warning) {\n\tvar attributes = get_attributes(element);\n\n\tif (hydrating) {\n\t\tattributes[attribute] = element.getAttribute(attribute);\n\n\t\tif (\n\t\t\tattribute === 'src' ||\n\t\t\tattribute === 'srcset' ||\n\t\t\t(attribute === 'href' && element.nodeName === LINK_TAG)\n\t\t) {\n\t\t\tif (!skip_warning) {\n\t\t\t\tcheck_src_in_dev_hydration(element, attribute, value ?? '');\n\t\t\t}\n\n\t\t\t// If we reset these attributes, they would result in another network request, which we want to avoid.\n\t\t\t// We assume they are the same between client and server as checking if they are equal is expensive\n\t\t\t// (we can't just compare the strings as they can be different between client and server but result in the\n\t\t\t// same url, so we would need to create hidden anchor elements to compare them)\n\t\t\treturn;\n\t\t}\n\t}\n\n\tif (attributes[attribute] === (attributes[attribute] = value)) return;\n\n\tif (attribute === 'loading') {\n\t\t// @ts-expect-error\n\t\telement[LOADING_ATTR_SYMBOL] = value;\n\t}\n\n\tif (value == null) {\n\t\telement.removeAttribute(attribute);\n\t} else if (typeof value !== 'string' && get_setters(element).has(attribute)) {\n\t\t// @ts-ignore\n\t\telement[attribute] = value;\n\t} else {\n\t\telement.setAttribute(attribute, value);\n\t}\n}\n\n/**\n * @param {Element} dom\n * @param {string} attribute\n * @param {string} value\n */\nexport function set_xlink_attribute(dom, attribute, value) {\n\tdom.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);\n}\n\n/**\n * @param {HTMLElement} node\n * @param {string} prop\n * @param {any} value\n */\nexport function set_custom_element_data(node, prop, value) {\n\t// We need to ensure that setting custom element props, which can\n\t// invoke lifecycle methods on other custom elements, does not also\n\t// associate those lifecycle methods with the current active reaction\n\t// or effect\n\tvar previous_reaction = active_reaction;\n\tvar previous_effect = active_effect;\n\n\t// If we're hydrating but the custom element is from Svelte, and it already scaffolded,\n\t// then it might run block logic in hydration mode, which we have to prevent.\n\tlet was_hydrating = hydrating;\n\tif (hydrating) {\n\t\tset_hydrating(false);\n\t}\n\n\tset_active_reaction(null);\n\tset_active_effect(null);\n\n\ttry {\n\t\tif (\n\t\t\t// `style` should use `set_attribute` rather than the setter\n\t\t\tprop !== 'style' &&\n\t\t\t// Don't compute setters for custom elements while they aren't registered yet,\n\t\t\t// because during their upgrade/instantiation they might add more setters.\n\t\t\t// Instead, fall back to a simple \"an object, then set as property\" heuristic.\n\t\t\t(setters_cache.has(node.getAttribute('is') || node.nodeName) ||\n\t\t\t// customElements may not be available in browser extension contexts\n\t\t\t!customElements ||\n\t\t\tcustomElements.get(node.getAttribute('is') || node.nodeName.toLowerCase())\n\t\t\t\t? get_setters(node).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 && element.nodeName === 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 = element.nodeName === OPTION_TAG;\n\tvar is_select_element = element.nodeName === 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\telement.nodeName === 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 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 = element.namespaceURI === 'http://www.w3.org/1999/xhtml';\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 && element.hasAttribute(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 = 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\telement.removeEventListener(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 {Event} evt\n\t\t\t\t\t */\n\t\t\t\t\tfunction handle(evt) {\n\t\t\t\t\t\tcurrent[key].call(this, evt);\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\tautofocus(/** @type {HTMLElement} */ (element), Boolean(value));\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\t// @ts-ignore\n\t\t\t\t\telement.value = 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\n\t\t\t\t\tif (name === 'value' || name === 'checked') {\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\tinput.removeAttribute(name);\n\t\t\t\t\t\t\tinput.defaultValue = previous;\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\tinput.value = 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\tinput.removeAttribute(name);\n\t\t\t\t\t\t\tinput.defaultChecked = previous;\n\t\t\t\t\t\t\tinput.checked = use_default ? previous : false;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\telement.removeAttribute(key);\n\t\t\t\t\t}\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 = element.nodeName === SELECT_TAG;\n\t\tvar inited = false;\n\n\t\tmanaged(() => {\n\t\t\tvar next = fn(...values.map(get));\n\t\t\t/** @type {Record<string | symbol, any>} */\n\t\t\tvar current = set_attributes(\n\t\t\t\telement,\n\t\t\t\tprev,\n\t\t\t\tnext,\n\t\t\t\tcss_hash,\n\t\t\t\tshould_remove_defaults,\n\t\t\t\tskip_warning\n\t\t\t);\n\n\t\t\tif (inited && is_select) {\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]: element.nodeName.includes('-'),\n\t\t\t[IS_HTML]: element.namespaceURI === NAMESPACE_HTML\n\t\t}\n\t);\n}\n\n/** @type {Map<string, Set<string>>} */\nvar setters_cache = new Map();\n\n/** @param {Element} element */\nfunction get_setters(element) {\n\tvar cache_key = element.getAttribute('is') || element.nodeName;\n\tvar setters = setters_cache.get(cache_key);\n\tif (setters) return setters;\n\tsetters_cache.set(cache_key, (setters = 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) return;\n\tif (attribute === 'srcset' && srcset_url_equal(element, value)) return;\n\tif (src_url_equal(element.getAttribute(attribute) ?? '', value)) return;\n\n\tw.hydration_attribute_changed(\n\t\tattribute,\n\t\telement.outerHTML.replace(element.innerHTML, element.innerHTML && '...'),\n\t\tString(value)\n\t);\n}\n\n/**\n * @param {string} element_src\n * @param {string} url\n * @returns {boolean}\n */\nfunction src_url_equal(element_src, url) {\n\tif (element_src === url) return true;\n\treturn new URL(element_src, document.baseURI).href === new URL(url, document.baseURI).href;\n}\n\n/** @param {string} srcset */\nfunction split_srcset(srcset) {\n\treturn srcset.split(',').map((src) => src.trim().split(' ').filter(Boolean));\n}\n\n/**\n * @param {HTMLSourceElement | HTMLImageElement} element\n * @param {string} srcset\n * @returns {boolean}\n */\nfunction srcset_url_equal(element, srcset) {\n\tvar element_urls = split_srcset(element.srcset);\n\tvar urls = split_srcset(srcset);\n\n\treturn (\n\t\turls.length === element_urls.length &&\n\t\turls.every(\n\t\t\t([url, width], i) =>\n\t\t\t\twidth === element_urls[i][1] &&\n\t\t\t\t// We need to test both ways because Vite will create an a full URL with\n\t\t\t\t// `new URL(asset, import.meta.url).href` for the client when `base: './'`, and the\n\t\t\t\t// relative URLs inside srcset are not automatically resolved to absolute URLs by\n\t\t\t\t// browsers (in contrast to img.src). This means both SSR and DOM code could\n\t\t\t\t// contain relative or absolute URLs.\n\t\t\t\t(src_url_equal(element_urls[i][0], url) || src_url_equal(url, element_urls[i][0]))\n\t\t)\n\t);\n}\n","/** @import { 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, previous_batch } from '../../../reactivity/batch.js';\nimport { async_mode_flag } from '../../../../flags/index.js';\n\n/**\n * @param {HTMLInputElement} input\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_value(input, get, set = get) {\n\tvar batches = new WeakSet();\n\n\tlisten_to_event_and_reset_event(input, 'input', async (is_reset) => {\n\t\tif (DEV && input.type === 'checkbox') {\n\t\t\t// TODO should this happen in prod too?\n\t\t\te.bind_invalid_checkbox_value();\n\t\t}\n\n\t\t/** @type {any} */\n\t\tvar value = is_reset ? input.defaultValue : input.value;\n\t\tvalue = is_numberlike_input(input) ? to_number(value) : value;\n\t\tset(value);\n\n\t\tif (current_batch !== null) {\n\t\t\tbatches.add(current_batch);\n\t\t}\n\n\t\t// Because `{#each ...}` blocks work by updating sources inside the flush,\n\t\t// we need to wait a tick before checking to see if we should forcibly\n\t\t// update the input and reset the selection state\n\t\tawait tick();\n\n\t\t// Respect any validation in accessors\n\t\tif (value !== (value = get())) {\n\t\t\tvar start = input.selectionStart;\n\t\t\tvar end = input.selectionEnd;\n\t\t\tvar length = input.value.length;\n\n\t\t\t// the value is coerced on assignment\n\t\t\tinput.value = value ?? '';\n\n\t\t\t// Restore selection\n\t\t\tif (end !== null) {\n\t\t\t\tvar new_length = input.value.length;\n\t\t\t\t// If cursor was at end and new input is longer, move cursor to new end\n\t\t\t\tif (start === end && end === length && new_length > length) {\n\t\t\t\t\tinput.selectionStart = new_length;\n\t\t\t\t\tinput.selectionEnd = new_length;\n\t\t\t\t} else {\n\t\t\t\t\tinput.selectionStart = start;\n\t\t\t\t\tinput.selectionEnd = Math.min(end, new_length);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t});\n\n\tif (\n\t\t// If we are hydrating and the value has since changed,\n\t\t// then use the updated value from the input instead.\n\t\t(hydrating && input.defaultValue !== input.value) ||\n\t\t// If defaultValue is set, then value == defaultValue\n\t\t// TODO Svelte 6: remove input.value check and set to empty string?\n\t\t(untrack(get) == null && input.value)\n\t) {\n\t\tset(is_numberlike_input(input) ? to_number(input.value) : input.value);\n\n\t\tif (current_batch !== null) {\n\t\t\tbatches.add(current_batch);\n\t\t}\n\t}\n\n\trender_effect(() => {\n\t\tif (DEV && input.type === 'checkbox') {\n\t\t\t// TODO should this happen in prod too?\n\t\t\te.bind_invalid_checkbox_value();\n\t\t}\n\n\t\tvar value = get();\n\n\t\tif (input === document.activeElement) {\n\t\t\t// In sync mode render effects are executed during tree traversal -> needs current_batch\n\t\t\t// In async mode render effects are flushed once batch resolved, at which point current_batch is null -> needs previous_batch\n\t\t\tvar batch = /** @type {Batch} */ (async_mode_flag ? previous_batch : current_batch);\n\n\t\t\t// Never rewrite the contents of a focused input. We can get here if, for example,\n\t\t\t// an update is deferred because of async work depending on the input:\n\t\t\t//\n\t\t\t// <input bind:value={query}>\n\t\t\t// <p>{await find(query)}</p>\n\t\t\tif (batches.has(batch)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (is_numberlike_input(input) && value === to_number(input.value)) {\n\t\t\t// handles 0 vs 00 case (see https://github.com/sveltejs/svelte/issues/9959)\n\t\t\treturn;\n\t\t}\n\n\t\tif (input.type === 'date' && !value && !input.value) {\n\t\t\t// Handles the case where a temporarily invalid date is set (while typing, for example with a leading 0 for the day)\n\t\t\t// and prevents this state from clearing the other parts of the date input (see https://github.com/sveltejs/svelte/issues/7897)\n\t\t\treturn;\n\t\t}\n\n\t\t// don't set the value of the input if it's the same to allow\n\t\t// minlength to work properly\n\t\tif (value !== input.value) {\n\t\t\t// @ts-expect-error the value is coerced on assignment\n\t\t\tinput.value = value ?? '';\n\t\t}\n\t});\n}\n\n/** @type {Set<HTMLInputElement[]>} */\nconst pending = new Set();\n\n/**\n * @param {HTMLInputElement[]} inputs\n * @param {null | [number]} group_index\n * @param {HTMLInputElement} input\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_group(inputs, group_index, input, get, set = get) {\n\tvar is_checkbox = input.getAttribute('type') === 'checkbox';\n\tvar binding_group = inputs;\n\n\t// needs to be let or related code isn't treeshaken out if it's always false\n\tlet hydration_mismatch = false;\n\n\tif (group_index !== null) {\n\t\tfor (var index of group_index) {\n\t\t\t// @ts-expect-error\n\t\t\tbinding_group = binding_group[index] ??= [];\n\t\t}\n\t}\n\n\tbinding_group.push(input);\n\n\tlisten_to_event_and_reset_event(\n\t\tinput,\n\t\t'change',\n\t\t() => {\n\t\t\t// @ts-ignore\n\t\t\tvar value = input.__value;\n\n\t\t\tif (is_checkbox) {\n\t\t\t\tvalue = get_binding_group_value(binding_group, value, input.checked);\n\t\t\t}\n\n\t\t\tset(value);\n\t\t},\n\t\t// TODO better default value handling\n\t\t() => set(is_checkbox ? [] : null)\n\t);\n\n\trender_effect(() => {\n\t\tvar value = get();\n\n\t\t// If we are hydrating and the value has since changed, then use the update value\n\t\t// from the input instead.\n\t\tif (hydrating && input.defaultChecked !== input.checked) {\n\t\t\thydration_mismatch = true;\n\t\t\treturn;\n\t\t}\n\n\t\tif (is_checkbox) {\n\t\t\tvalue = value || [];\n\t\t\t// @ts-ignore\n\t\t\tinput.checked = value.includes(input.__value);\n\t\t} else {\n\t\t\t// @ts-ignore\n\t\t\tinput.checked = is(input.__value, value);\n\t\t}\n\t});\n\n\tteardown(() => {\n\t\tvar index = binding_group.indexOf(input);\n\n\t\tif (index !== -1) {\n\t\t\tbinding_group.splice(index, 1);\n\t\t}\n\t});\n\n\tif (!pending.has(binding_group)) {\n\t\tpending.add(binding_group);\n\n\t\tqueue_micro_task(() => {\n\t\t\t// necessary to maintain binding group order in all insertion scenarios\n\t\t\tbinding_group.sort((a, b) => (a.compareDocumentPosition(b) === 4 ? -1 : 1));\n\t\t\tpending.delete(binding_group);\n\t\t});\n\t}\n\n\tqueue_micro_task(() => {\n\t\tif (hydration_mismatch) {\n\t\t\tvar value;\n\n\t\t\tif (is_checkbox) {\n\t\t\t\tvalue = get_binding_group_value(binding_group, value, input.checked);\n\t\t\t} else {\n\t\t\t\tvar hydration_input = binding_group.find((input) => input.checked);\n\t\t\t\t// @ts-ignore\n\t\t\t\tvalue = hydration_input?.__value;\n\t\t\t}\n\n\t\t\tset(value);\n\t\t}\n\t});\n}\n\n/**\n * @param {HTMLInputElement} input\n * @param {() => unknown} get\n * @param {(value: unknown) => void} set\n * @returns {void}\n */\nexport function bind_checked(input, get, set = get) {\n\tlisten_to_event_and_reset_event(input, 'change', (is_reset) => {\n\t\tvar value = is_reset ? input.defaultChecked : input.checked;\n\t\tset(value);\n\t});\n\n\tif (\n\t\t// If we are hydrating and the value has since changed,\n\t\t// then use the update value from the input instead.\n\t\t(hydrating && input.defaultChecked !== input.checked) ||\n\t\t// If defaultChecked is set, then checked == defaultChecked\n\t\tuntrack(get) == null\n\t) {\n\t\tset(input.checked);\n\t}\n\n\trender_effect(() => {\n\t\tvar value = get();\n\t\tinput.checked = Boolean(value);\n\t});\n}\n\n/**\n * @template V\n * @param {Array<HTMLInputElement>} group\n * @param {V} __value\n * @param {boolean} checked\n * @returns {V[]}\n */\nfunction get_binding_group_value(group, __value, checked) {\n\t/** @type {Set<V>} */\n\tvar value = new Set();\n\n\tfor (var i = 0; i < group.length; i += 1) {\n\t\tif (group[i].checked) {\n\t\t\t// @ts-ignore\n\t\t\tvalue.add(group[i].__value);\n\t\t}\n\t}\n\n\tif (!checked) {\n\t\tvalue.delete(__value);\n\t}\n\n\treturn Array.from(value);\n}\n\n/**\n * @param {HTMLInputElement} input\n */\nfunction is_numberlike_input(input) {\n\tvar type = input.type;\n\treturn type === 'number' || type === 'range';\n}\n\n/**\n * @param {string} value\n */\nfunction to_number(value) {\n\treturn value === '' ? null : +value;\n}\n\n/**\n * @param {HTMLInputElement} input\n * @param {() => FileList | null} get\n * @param {(value: FileList | null) => void} set\n */\nexport function bind_files(input, get, set = get) {\n\tlisten_to_event_and_reset_event(input, 'change', () => {\n\t\tset(input.files);\n\t});\n\n\tif (\n\t\t// If we are hydrating and the value has since changed,\n\t\t// then use the updated value from the input instead.\n\t\thydrating &&\n\t\tinput.files\n\t) {\n\t\tset(input.files);\n\t}\n\n\trender_effect(() => {\n\t\tinput.files = get();\n\t});\n}\n","import { 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';\nimport { effect, render_effect } from './effects.js';\n\n/**\n * @param {((value?: number) => number)} fn\n * @param {1 | -1} [d]\n * @returns {number}\n */\nexport function update_prop(fn, d = 1) {\n\tconst value = fn();\n\tfn(value + d);\n\treturn value;\n}\n\n/**\n * @param {((value?: number) => number)} fn\n * @param {1 | -1} [d]\n * @returns {number}\n */\nexport function update_pre_prop(fn, d = 1) {\n\tconst value = fn() + d;\n\tfn(value);\n\treturn value;\n}\n\n/**\n * The proxy handler for rest props (i.e. `const { x, ...rest } = $props()`).\n * Is passed the full `$$props` object and excludes the named props.\n * @type {ProxyHandler<{ props: Record<string | symbol, unknown>, exclude: 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 { ComponentContext, ComponentContextLegacy } from '#client' */\n/** @import { EventDispatcher } from './index.js' */\n/** @import { NotFunction } from './internal/types.js' */\nimport { active_reaction, untrack } from './internal/client/runtime.js';\nimport { is_array } from './internal/shared/utils.js';\nimport { user_effect } from './internal/client/index.js';\nimport * as e from './internal/client/errors.js';\nimport { legacy_mode_flag } from './internal/flags/index.js';\nimport { component_context } from './internal/client/context.js';\nimport { DEV } from 'esm-env';\n\nif (DEV) {\n\t/**\n\t * @param {string} rune\n\t */\n\tfunction throw_rune_error(rune) {\n\t\tif (!(rune in globalThis)) {\n\t\t\t// TODO if people start adjusting the \"this can contain runes\" config through v-p-s more, adjust this message\n\t\t\t/** @type {any} */\n\t\t\tlet value; // let's hope 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.\n *\n * ```svelte\n * <script>\n * \timport { getAbortSignal } from 'svelte';\n *\n * \tlet { id } = $props();\n *\n * \tasync function getData(id) {\n * \t\tconst response = await fetch(`/items/${id}`, {\n * \t\t\tsignal: getAbortSignal()\n * \t\t});\n *\n * \t\treturn await response.json();\n * \t}\n *\n * \tconst data = $derived(await getData(id));\n * </script>\n * ```\n */\nexport function getAbortSignal() {\n\tif (active_reaction === null) {\n\t\te.get_abort_signal_outside_reaction();\n\t}\n\n\treturn (active_reaction.ac ??= new AbortController()).signal;\n}\n\n/**\n * `onMount`, like [`$effect`](https://svelte.dev/docs/svelte/$effect), schedules a function to run as soon as the component has been mounted to the DOM.\n * Unlike `$effect`, the provided function only runs once.\n *\n * It must be called during the component's initialisation (but doesn't need to live _inside_ the component;\n * it can be called from an external module). If a function is returned _synchronously_ from `onMount`,\n * it will be called when the component is unmounted.\n *\n * `onMount` functions do not run during [server-side rendering](https://svelte.dev/docs/svelte/svelte-server#render).\n *\n * @template T\n * @param {() => NotFunction<T> | Promise<NotFunction<T>> | (() => any)} fn\n * @returns {void}\n */\nexport function onMount(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('onMount');\n\t}\n\n\tif (legacy_mode_flag && component_context.l !== null) {\n\t\tinit_update_callbacks(component_context).m.push(fn);\n\t} else {\n\t\tuser_effect(() => {\n\t\t\tconst cleanup = untrack(fn);\n\t\t\tif (typeof cleanup === 'function') return /** @type {() => void} */ (cleanup);\n\t\t});\n\t}\n}\n\n/**\n * Schedules a callback to run immediately before the component is unmounted.\n *\n * Out of `onMount`, `beforeUpdate`, `afterUpdate` and `onDestroy`, this is the\n * only one that runs inside a server-side component.\n *\n * @param {() => any} fn\n * @returns {void}\n */\nexport function onDestroy(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('onDestroy');\n\t}\n\n\tonMount(() => () => untrack(fn));\n}\n\n/**\n * @template [T=any]\n * @param {string} type\n * @param {T} [detail]\n * @param {any}params_0\n * @returns {CustomEvent<T>}\n */\nfunction create_custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {\n\treturn new CustomEvent(type, { detail, bubbles, cancelable });\n}\n\n/**\n * Creates an event dispatcher that can be used to dispatch [component events](https://svelte.dev/docs/svelte/legacy-on#Component-events).\n * Event dispatchers are functions that can take two arguments: `name` and `detail`.\n *\n * Component events created with `createEventDispatcher` create a\n * [CustomEvent](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent).\n * These events do not [bubble](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture).\n * The `detail` argument corresponds to the [CustomEvent.detail](https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail)\n * property and can contain any type of data.\n *\n * The event dispatcher can be typed to narrow the allowed event names and the type of the `detail` argument:\n * ```ts\n * const dispatch = createEventDispatcher<{\n *  loaded: null; // does not take a detail argument\n *  change: string; // takes a detail argument of type string, which is required\n *  optional: number | null; // takes an optional detail argument of type number\n * }>();\n * ```\n *\n * @deprecated Use callback props and/or the `$host()` rune instead — see [migration guide](https://svelte.dev/docs/svelte/v5-migration-guide#Event-changes-Component-events)\n * @template {Record<string, any>} [EventMap = any]\n * @returns {EventDispatcher<EventMap>}\n */\nexport function createEventDispatcher() {\n\tconst active_component_context = component_context;\n\tif (active_component_context === null) {\n\t\te.lifecycle_outside_component('createEventDispatcher');\n\t}\n\n\t/**\n\t * @param [detail]\n\t * @param [options]\n\t */\n\treturn (type, detail, options) => {\n\t\tconst events = /** @type {Record<string, Function | Function[]>} */ (\n\t\t\tactive_component_context.s.$$events\n\t\t)?.[/** @type {string} */ (type)];\n\n\t\tif (events) {\n\t\t\tconst callbacks = is_array(events) ? events.slice() : [events];\n\t\t\t// TODO are there situations where events could be dispatched\n\t\t\t// in a server (non-DOM) environment?\n\t\t\tconst event = create_custom_event(/** @type {string} */ (type), detail, options);\n\t\t\tfor (const fn of callbacks) {\n\t\t\t\tfn.call(active_component_context.x, event);\n\t\t\t}\n\t\t\treturn !event.defaultPrevented;\n\t\t}\n\n\t\treturn true;\n\t};\n}\n\n// TODO mark beforeUpdate and afterUpdate as deprecated in Svelte 6\n\n/**\n * Schedules a callback to run immediately before the component is updated after any state change.\n *\n * The first time the callback runs will be before the initial `onMount`.\n *\n * In runes mode use `$effect.pre` instead.\n *\n * @deprecated Use [`$effect.pre`](https://svelte.dev/docs/svelte/$effect#$effect.pre) instead\n * @param {() => void} fn\n * @returns {void}\n */\nexport function beforeUpdate(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('beforeUpdate');\n\t}\n\n\tif (component_context.l === null) {\n\t\te.lifecycle_legacy_only('beforeUpdate');\n\t}\n\n\tinit_update_callbacks(component_context).b.push(fn);\n}\n\n/**\n * Schedules a callback to run immediately after the component has been updated.\n *\n * The first time the callback runs will be after the initial `onMount`.\n *\n * In runes mode use `$effect` instead.\n *\n * @deprecated Use [`$effect`](https://svelte.dev/docs/svelte/$effect) instead\n * @param {() => void} fn\n * @returns {void}\n */\nexport function afterUpdate(fn) {\n\tif (component_context === null) {\n\t\te.lifecycle_outside_component('afterUpdate');\n\t}\n\n\tif (component_context.l === null) {\n\t\te.lifecycle_legacy_only('afterUpdate');\n\t}\n\n\tinit_update_callbacks(component_context).a.push(fn);\n}\n\n/**\n * Legacy-mode: Init callbacks object for onMount/beforeUpdate/afterUpdate\n * @param {ComponentContext} context\n */\nfunction init_update_callbacks(context) {\n\tvar l = /** @type {ComponentContextLegacy} */ (context).l;\n\treturn (l.u ??= { a: [], b: [], m: [] });\n}\n\nexport { flushSync, fork } from './internal/client/reactivity/batch.js';\nexport {\n\tcreateContext,\n\tgetContext,\n\tgetAllContexts,\n\thasContext,\n\tsetContext\n} from './internal/client/context.js';\nexport { hydratable } from './internal/client/hydratable.js';\nexport { hydrate, mount, unmount } from './internal/client/render.js';\nexport { tick, untrack, settled } from './internal/client/runtime.js';\nexport { createRawSnippet } from './internal/client/dom/blocks/snippet.js';\n","import { PUBLIC_VERSION } from '../version.js';\n\nif (typeof window !== 'undefined') {\n\t// @ts-expect-error\n\t((window.__svelte ??= {}).v ??= new Set()).add(PUBLIC_VERSION);\n}\n","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-76/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48 MessageFormat specification}.\n */\nexport let DefaultFunctions = {\n    /**\n     * Supports formatting and selection as defined in LDML 48 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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 and selection as defined in LDML 48 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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-76/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48 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 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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 as defined in LDML 48 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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 as defined in LDML 48 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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 for the\n     * {@link https://www.unicode.org/reports/tr35/tr35-76/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-76/tr35-messageFormat.html#contents-of-part-9-messageformat | LDML 48 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","<!--\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). Named keys, function keys, and bare digits are compared against `event.code` (layout- and\n * modifier-stable, so `Shift+1` matches even though `event.key` becomes `'!'`). Other characters\n * fall back to `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`.\n  if (PHYSICAL_TOKENS.has(token)) {\n    return ({ code }) => code === token;\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  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        !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        const keys = shortcut.split('+');\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  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 * Elements with active shortcuts, mapped to their pre-parsed shortcuts. A single shared `keydown`\n * listener serves every registered element, instead of adding one global listener per element.\n * @type {Map<HTMLInputElement | HTMLButtonElement, ParsedShortcut[]>}\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 * 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  shortcutTargets.forEach((parsedShortcuts, element) => {\n    if (matchesParsedShortcuts(event, parsedShortcuts)) {\n      activateElement(element, event);\n    }\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  const platformKeyShortcuts = resolveAccel(shortcuts).trim().replace(/\\s+/g, ' ');\n\n  if (!platformKeyShortcuts) {\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    shortcutTargets.set(element, parsedShortcuts);\n    element.setAttribute('aria-keyshortcuts', platformKeyShortcuts);\n\n    return () => {\n      shortcutTargets.delete(element);\n      element.removeAttribute('aria-keyshortcuts');\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 * 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 the\n * `element` is not available yet, `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 { generateElementId, isVisible, removeVisibilityResolver, waitForVisibility };\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 * 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 flip} vertically, keeping any height limit already set if the content fits.\n   * @param {string} from Current side.\n   * @param {string} to Opposite side.\n   * @param {number} room Room on the current side.\n   * @param {number} otherRoom Room on the opposite side.\n   */\n  const flipVertically = (from, to, room, otherRoom) => {\n    const result = flip({ position, from, to, size: contentHeight, room, otherRoom });\n\n    position = result.position;\n    height = result.cap ?? height;\n  };\n\n  // Alter the position if the space is limited\n  if (position.startsWith('bottom-')) {\n    flipVertically('bottom-', 'top-', bottomMargin, topMargin);\n  } else if (position.startsWith('top-')) {\n    flipVertically('top-', 'bottom-', topMargin, bottomMargin);\n  }\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  if (position.endsWith('-top')) {\n    flipVertically('-top', '-bottom', downwardMargin, upwardMargin);\n  } else if (position.endsWith('-bottom')) {\n    flipVertically('-bottom', '-top', upwardMargin, downwardMargin);\n  }\n\n  // If the popup overflows the viewport, change the position\n  if (position.endsWith('-left')) {\n    if (rect.left + contentWidth > viewport.width - 8) {\n      position = /** @type {PopupPosition} */ (position.replace('-left', '-right'));\n    }\n  }\n\n  if (position.endsWith('-right')) {\n    if (rect.right - contentWidth < 8) {\n      position = /** @type {PopupPosition} */ (position.replace('-right', '-left'));\n    }\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  if (position.startsWith('right-')) {\n    ({ position } = flip({\n      position,\n      from: 'right-',\n      to: 'left-',\n      size: contentWidth,\n      room: rightMargin,\n      otherRoom: leftMargin,\n    }));\n  } else if (position.startsWith('left-')) {\n    ({ position } = flip({\n      position,\n      from: 'left-',\n      to: 'right-',\n      size: contentWidth,\n      room: leftMargin,\n      otherRoom: rightMargin,\n    }));\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 { 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        const { activeElement } = document;\n\n        // Only take focus back if it’s still inside the popup, or nowhere because the popup took it\n        // down with itself. If it has already moved on — the user tabbed out of the menu, say —\n        // pulling it back would undo what they just did.\n        if (\n          !activeElement ||\n          activeElement === document.body ||\n          this.popupElement?.contains(activeElement)\n        ) {\n          this.anchorElement.focus();\n        }\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   * Function that removes the event listeners added to the current {@link popupElement}.\n   * @type {(() => void) | undefined}\n   */\n  #removeEventListeners = undefined;\n\n  /**\n   * Functions that remove the event listeners added to the {@link anchorElement}, which may outlive\n   * this instance.\n   * @type {(() => void)[]}\n   */\n  #removeAnchorListeners = [];\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    const removeClickListener = on(anchorElement, 'click', () => {\n      if (!this.isDisabled && !this.isReadOnly) {\n        this.open = !this.open;\n      }\n    });\n\n    const removeKeyDownListener = on(anchorElement, 'keydown', (event) => {\n      const { key, ctrlKey, metaKey, shiftKey, altKey } = event;\n      const hasModifier = shiftKey || altKey || ctrlKey || metaKey;\n\n      if (this.isDisabled || this.isReadOnly) {\n        return;\n      }\n\n      if (['Enter', ' '].includes(key) && !hasModifier) {\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\n      // the popup they belong to the list. A menu item that opens a submenu is left alone: there\n      // the 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    const removeTransitionStartListener = on(anchorElement, 'transitionstart', () => {\n      if (this.anchorElement.closest('.hiding, .hidden, [hidden]')) {\n        this.hideImmediately();\n      }\n    });\n\n    this.#removeAnchorListeners = [\n      removeClickListener,\n      removeKeyDownListener,\n      removeTransitionStartListener,\n    ];\n\n    this.intersectionObserver = new IntersectionObserver(([entry]) => {\n      if (!entry.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   */\n  attachPopupElement(popupElement, contentElement) {\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.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    // Close the popup when the backdrop, a menu item or an option is clicked\n    const removeClickListener = on(popupElement, 'click', (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    const removeKeyDownListener = on(popupElement, 'keydown', (event) => {\n      const { key, ctrlKey, metaKey, shiftKey, altKey } = event;\n      const hasModifier = shiftKey || altKey || ctrlKey || metaKey;\n\n      if (key === 'Escape' && !hasModifier) {\n        event.preventDefault();\n        event.stopPropagation();\n        this.open = false;\n      }\n    });\n\n    /**\n     * Remove the listeners added above.\n     */\n    this.#removeEventListeners = () => {\n      removeClickListener();\n      removeKeyDownListener();\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.#removeEventListeners?.();\n    this.#removeEventListeners = 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    if (this.popupElement) {\n      this.popupElement.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 (this.popupElement) {\n      this.popupElement.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.#removeAnchorListeners.forEach((removeListener) => removeListener());\n    this.#removeAnchorListeners = [];\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  @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  import { getTransitionTimeout } 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 = $bindable(),\n    class: className,\n    role = 'dialog',\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   * 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   * 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      const { activeElement } = document;\n\n      if (!element.isConnected) {\n        return;\n      }\n\n      // Only take the focus back if it’s still inside the modal, or nowhere because the modal took\n      // it down with itself. If it has already moved on, pulling it back would undo what happened.\n      if (!activeElement || activeElement === document.body || dialog?.contains(activeElement)) {\n        element.focus();\n      }\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    dialog.showModal();\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      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={dialog}\n      tabindex=\"-1\"\n      {...restProps}\n      inert={!setOpenClass}\n      {role}\n      class=\"sui modal {className}\"\n      class:backdrop={showBackdrop}\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 (\n          dialog &&\n          lightDismiss &&\n          /** @type {HTMLElement | undefined} */ (target)?.matches('dialog')\n        ) {\n          dialog.returnValue = 'cancel';\n          open = false;\n        }\n      }}\n      oncancel={(event) => {\n        event.preventDefault();\n\n        // Escape key is pressed\n        if (dialog && escapeDismiss) {\n          dialog.returnValue = 'cancel';\n          open = false;\n        }\n      }}\n      onclose={() => {\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          dialog.showModal();\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.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 = $bindable(undefined),\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 `<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);\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={content}\n    hidden={!open}\n    role=\"none\"\n    class=\"content {className} {contentType}\"\n    class:touch\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  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  transition-property: opacity, transform;\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}</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\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 = $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    children,\n    startIcon,\n    endIcon,\n    popup,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\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={element}\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 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 { Snippet } from 'svelte';\n   */\n\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 {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\n   * @property {string} [title] Text label displayed above the group items.\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    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-color, 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","<script>\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\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] Primary slot content.\n   */\n\n  /**\n   * @type {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","<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","/**\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","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 * 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 * 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 * Type-ahead support shared by the composite widgets: the collapsed select-only combobox, and the\n * listbox and menu groups.\n */\n\nimport { fold } 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 * 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   * Drop the prefix.\n   */\n  reset() {\n    globalThis.clearTimeout(this.#timer);\n    this.#prefix = '';\n  }\n}\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 * 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","import { isRTL } from '@sveltia/i18n';\nimport { generateElementId } from '@sveltia/utils/element';\nimport { sleep } from '@sveltia/utils/misc';\nimport { untrack } from 'svelte';\nimport { scrollIntoViewIfNeeded } from './scroll.js';\nimport { getSelectedItemDetail } from './select.svelte.js';\nimport { normalize } from './text.js';\nimport { getArrowKeys, getGridTargetIndex, getLinearTargetIndex } from './navigation.js';\nimport { findTypeAheadMatch, TypeAhead } from './type-ahead.js';\nimport { activateBefore, activateLater } from './widget.js';\n\n/**\n * @import { Attachment } from 'svelte/attachments';\n */\n\n/**\n * CSS selector matching the members that are disabled or hidden, which are left out of navigation.\n */\nconst INACTIVE_MEMBER_SELECTOR = '[aria-disabled=\"true\"], [aria-hidden=\"true\"]';\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 * 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 */\nconst 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 * 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 */\nconst 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 * 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 * Implement keyboard and mouse interactions for a grouping composite widget.\n */\nexport class Group {\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   * 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   * Whether {@link destroy} has run, so a pending {@link activate} must not run.\n   * @type {boolean}\n   */\n  #destroyed = false;\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   * Keystroke buffer for type-ahead.\n   * @type {TypeAhead}\n   */\n  #typeAhead = new TypeAhead();\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 =\n      member.dataset.searchValue ??\n      member.dataset.label ??\n      member.querySelector('.label')?.textContent ??\n      /** @type {string} */ (member.textContent);\n\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    parent.dispatchEvent(new CustomEvent('Initializing'));\n\n    this.parent = parent;\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    /** @type {(event: MouseEvent) => void} */\n    this._onClick = activateBefore(this, (event) => this.onClick(event));\n    /** @type {(event: KeyboardEvent) => void} */\n    this._onKeyDown = activateBefore(this, (event) => this.onKeyDown(event));\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      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    parent.addEventListener('click', this._onClick);\n    parent.addEventListener('keydown', this._onKeyDown);\n\n    // Wait a bit before the relevant components, including the `aria-controls` target are mounted\n    activateLater(this, () => this.#destroyed);\n  }\n\n  /**\n   * Activate the members, unless they already are.\n   */\n  activate() {\n    if (this.activated) {\n      return;\n    }\n\n    const { parent, allMembers, selected: defaultSelected } = this;\n\n    this.activated = true;\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    parent.dispatchEvent(new CustomEvent('Initialized'));\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) ?? 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.observer.takeRecords().length) {\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   * 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   * The element that opens this menu, either a menu button or a menu item in the menu above.\n   * @type {HTMLElement | null}\n   */\n  get opener() {\n    return getMenuOpener(this.parent);\n  }\n\n  /**\n   * The menu item that opens this menu, when this menu is 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   * @type {HTMLElement | null}\n   */\n  get parentMenuItem() {\n    const { opener } = this;\n\n    return opener?.matches('[role^=\"menuitem\"]') ? opener : null;\n  }\n\n  /**\n   * Close this menu along with every menu above it.\n   * @returns {HTMLElement | null} The element that opens the outermost menu, so the caller can\n   * hand focus back to it.\n   */\n  closeMenuChain() {\n    const { opener: innermost } = this;\n    /** @type {HTMLElement | null} */\n    let opener = innermost;\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 menu = /** @type {HTMLElement | null} */ (\n        opener.closest('[role=\"menu\"], [role=\"menubar\"]')\n      );\n\n      opener = menu ? getMenuOpener(menu) : 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\n   * a modal `<dialog>` confines Tab to its own contents.\n   * @param {boolean} backwards Whether to move to the previous tab stop instead, as Shift+Tab.\n   */\n  async leaveMenu(backwards) {\n    const opener = this.closeMenuChain();\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   * @param {HTMLElement} item Menu item with `aria-haspopup=\"menu\"`.\n   */\n  async enterSubmenu(item) {\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\n    // or 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(this.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 this submenu and move focus back onto the menu item that opens it.\n   * @param {HTMLElement} item Menu item with `aria-haspopup=\"menu\"`.\n   */\n  leaveSubmenu(item) {\n    if (item.getAttribute('aria-expanded') === 'true') {\n      item.click();\n    }\n\n    item.focus();\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 parent is disabled.\n   * @type {boolean}\n   */\n  get isDisabled() {\n    return this.parent.matches('[aria-disabled=\"true\"]');\n  }\n\n  /**\n   * Whether the parent is read-only.\n   * @type {boolean}\n   */\n  get isReadOnly() {\n    return this.parent.matches('[aria-readonly=\"true\"]');\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 (!this.focusChild) {\n      element.classList.toggle('focused', isTarget);\n\n      if (isTarget) {\n        element.dispatchEvent(new CustomEvent('Focus'));\n      }\n    }\n\n    if (controlTarget) {\n      this.#setPanelShown(controlTarget, isTarget);\n\n      if (isTarget) {\n        scrollTargets.push(controlTarget);\n      }\n    }\n\n    if (isTarget) {\n      this.parent.setAttribute('aria-activedescendant', element.id);\n      scrollTargets.push(element);\n    }\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.parent.dispatchEvent(\n        new CustomEvent('Change', { detail: getSelectedItemDetail(newTarget) }),\n      );\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, ctrlKey, metaKey, shiftKey, altKey } = event;\n    const hasModifier = shiftKey || altKey || ctrlKey || metaKey;\n    const isMenu = this.childRoles.includes('menuitem');\n\n    // Tab leaves the menu entirely rather than stepping through it. Shift is allowed through here,\n    // unlike the keys below, because Shift+Tab leaves the menu just the same.\n    if (key === 'Tab' && isMenu && !ctrlKey && !metaKey && !altKey) {\n      event.preventDefault();\n      this.leaveMenu(shiftKey);\n\n      return;\n    }\n\n    if (hasModifier) {\n      return;\n    }\n\n    // eslint-disable-next-line prefer-destructuring\n    const target = /** @type {HTMLElement} */ (event.target);\n    const { activeMembers } = this;\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 (['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 (key.length === 1 && key !== ' ' && 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    // Escape in a submenu dismisses just that submenu. Propagation is stopped so the popup, whose\n    // own Escape handler sits on the `<dialog>` this submenu shares with its parent, doesn’t go on\n    // to close the whole stack.\n    if (key === 'Escape' && isMenu) {\n      const { parentMenuItem } = this;\n\n      if (parentMenuItem) {\n        event.preventDefault();\n        event.stopPropagation();\n        this.leaveSubmenu(parentMenuItem);\n\n        return;\n      }\n    }\n\n    const rtl = isRTL();\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 (this.orientation === 'vertical' && isMenu) {\n      const { prevKey: outOfSubmenuKey, nextKey: intoSubmenuKey } = getArrowKeys('horizontal', rtl);\n\n      if (key === intoSubmenuKey && currentTarget?.getAttribute('aria-haspopup') === 'menu') {\n        this.enterSubmenu(currentTarget);\n\n        return;\n      }\n\n      if (key === outOfSubmenuKey) {\n        const { parentMenuItem } = this;\n\n        if (parentMenuItem) {\n          this.leaveSubmenu(parentMenuItem);\n\n          return;\n        }\n      }\n    }\n\n    const newTarget = this.#getArrowTarget(key, currentTarget, rtl);\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 labels = activeMembers.map((member) =>\n      normalize(\n        member.dataset.label ??\n          member.querySelector('.label')?.textContent ??\n          member.textContent ??\n          '',\n      ),\n    );\n\n    const index = findTypeAheadMatch(\n      labels,\n      this.#typeAhead.push(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 keys = getArrowKeys(this.orientation, rtl);\n\n      return activeMembers[\n        getLinearTargetIndex({ key, index, count: activeMembers.length, ...keys })\n      ];\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\n    const newTarget =\n      list[getGridTargetIndex({ key, index, count: list.length, columnCount, ...keys })];\n\n    return newTarget?.matches('[aria-disabled=\"true\"]') ? undefined : newTarget;\n  }\n\n  /**\n   * Clean up event listeners.\n   */\n  destroy() {\n    this.#destroyed = true;\n    globalThis.clearTimeout(this.#scrollTimer);\n    this.#typeAhead.reset();\n    this.observer.disconnect();\n    this.selectionObserver?.disconnect();\n    this.parent.removeEventListener('click', this._onClick);\n    this.parent.removeEventListener('keydown', this._onKeyDown);\n  }\n\n  /**\n   * Called whenever the params are updated. Filter the items based on the search terms.\n   * @param {{ searchTerms: string }} params Updated params.\n   */\n  onUpdate({ searchTerms }) {\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.\n * @param {object | (() => object)} [paramsOrGetter] Params object or a getter function for reactive\n * params.\n * @returns {Attachment} Attachment.\n */\nexport const activateGroup = (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 group 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 group = new Group(/** @type {HTMLElement} */ (parent), initialParams);\n\n  /* v8 ignore next 4 */\n  if (isGetter) {\n    $effect(() => {\n      group.onUpdate(paramsOrGetter());\n    });\n  }\n\n  return () => {\n    group.destroy();\n  };\n};\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 { Snippet } from 'svelte';\n   */\n\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.\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   * @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] The `aria-label` attribute on the wrapper element.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {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  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  @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 layout container of `<Checkbox>`es.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\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 {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\n   * @property {'horizontal'|'vertical'} [orientation] Orientation of the widget.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\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    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  @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 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  /**\n   * Accessible name given as a prop or as a plain `aria-label` attribute. It takes the place of the\n   * visible label, which the button otherwise points at — but only when there is one to point at.\n   * @type {string | undefined}\n   */\n  const accessibleLabel = $derived(ariaLabel ?? restProps['aria-label']);\n  const hasVisibleLabel = $derived(!!(children || label));\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      aria-label={accessibleLabel || undefined}\n      aria-labelledby={!accessibleLabel && hasVisibleLabel ? `${id}-label` : undefined}\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  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>\n  import { _ } from '@sveltia/i18n';\n  import { sleep } from '@sveltia/utils/misc';\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    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    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   * Accessible name for the `<dialog>`. The built-in header renders the title in an element the\n   * dialog can point at; with a custom header the title is only text, so it becomes `aria-label`\n   * unless the consumer names the labelling element.\n   */\n  const labelledby = $derived(ariaLabelledby ?? (!header && title ? `${id}-title` : undefined));\n  const label = $derived(labelledby ? undefined : title || undefined);\n  /**\n   * A reference to the modal component.\n   * @type {Modal | undefined}\n   */\n  let modal = $state();\n  /**\n   * @type {HTMLElement | undefined}\n   */\n  let content = $state();\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        const target = focusInput\n          ? /** @type {HTMLInputElement | HTMLButtonElement | null} */ (\n              content?.querySelector('input, button.primary')\n            )\n          : null;\n\n        if (target) {\n          target.focus();\n\n          if (target instanceof HTMLInputElement) {\n            target.select();\n          }\n        } else {\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          modal?.focus();\n        }\n      })();\n\n      return () => {\n        cancelled = true;\n      };\n    }\n\n    return undefined;\n  });\n</script>\n\n<Modal\n  bind:this={modal}\n  {...restProps}\n  {role}\n  {id}\n  class=\"dialog\"\n  aria-label={label}\n  aria-labelledby={labelledby}\n  aria-describedby=\"{id}-body\"\n  bind:open\n  showBackdrop\n>\n  <div bind:this={content} role=\"none\" class={['content', className, size]}>\n    {#if title || showClose || header || headerExtra}\n      <div role=\"none\" class=\"header\">\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                modal?.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}\n              onclick={() => {\n                modal?.close('ok');\n              }}\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                modal?.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.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 .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  margin: 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    margin: 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 * @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","// Generated by `scripts/generate-emoji-data.js`. DO NOT EDIT.\n\n/**\n * Emoji list from `emoji-data` v16.0.0, in the Unicode order the dataset publishes.\n *\n * One line per emoji, made up of tab-separated fields: the emoji character, its shortcodes, and any\n * further searchable words taken from its Unicode name. Multiple shortcodes or keywords within a\n * field are separated by a space, and the last field is left out when there are no extra keywords.\n * The first shortcode is the canonical one, the one shown alongside the emoji in the suggestions.\n *\n * It’s a single string rather than an object so that it costs one line per emoji in the bundle\n * instead of a few hundred bytes of punctuation, and so that nothing is parsed until the first\n * shortcode is actually typed.\n * @see https://github.com/iamcal/emoji-data\n */\nexport const EMOJI_DATA = `😀\tgrinning\tface\n😃\tsmiley\tsmiling face open mouth\n😄\tsmile\tsmiling face open mouth eyes\n😁\tgrin\tgrinning face smiling eyes\n😆\tlaughing satisfied\tsmiling face open mouth tightly-closed eyes\n😅\tsweat_smile\tsmiling face open mouth cold\n🤣\trolling_on_the_floor_laughing\n😂\tjoy\tface tears\n🙂\tslightly_smiling_face\n🙃\tupside_down_face\tupside-down\n🫠\tmelting_face\n😉\twink\twinking face\n😊\tblush\tsmiling face eyes\n😇\tinnocent\tsmiling face halo\n🥰\tsmiling_face_with_3_hearts\teyes three\n😍\theart_eyes\tsmiling face heart-shaped\n🤩\tstar-struck grinning_face_with_star_eyes\n😘\tkissing_heart\tface throwing kiss\n😗\tkissing\tface\n☺️\trelaxed\twhite smiling face\n😚\tkissing_closed_eyes\tface\n😙\tkissing_smiling_eyes\tface\n🥲\tsmiling_face_with_tear\n😋\tyum\tface savouring delicious food\n😛\tstuck_out_tongue\tface stuck-out\n😜\tstuck_out_tongue_winking_eye\tface stuck-out\n🤪\tzany_face grinning_face_with_one_large_and_one_small_eye\n😝\tstuck_out_tongue_closed_eyes\tface stuck-out tightly-closed\n🤑\tmoney_mouth_face\tmoney-mouth\n🤗\thugging_face\n🤭\tface_with_hand_over_mouth smiling_face_with_smiling_eyes_and_hand_covering_mouth\n🫢\tface_with_open_eyes_and_hand_over_mouth\n🫣\tface_with_peeking_eye\n🤫\tshushing_face face_with_finger_covering_closed_lips\n🤔\tthinking_face\n🫡\tsaluting_face\n🤐\tzipper_mouth_face\tzipper-mouth\n🤨\tface_with_raised_eyebrow face_with_one_eyebrow_raised\n😐\tneutral_face\n😑\texpressionless\tface\n😶\tno_mouth\tface without\n🫥\tdotted_line_face\n😶‍🌫️\tface_in_clouds\n😏\tsmirk\tsmirking face\n😒\tunamused\tface\n🙄\tface_with_rolling_eyes\n😬\tgrimacing\tface\n😮‍💨\tface_exhaling\n🤥\tlying_face\n🫨\tshaking_face\n🙂‍↔️\thead_shaking_horizontally\n🙂‍↕️\thead_shaking_vertically\n😌\trelieved\tface\n😔\tpensive\tface\n😪\tsleepy\tface\n🤤\tdrooling_face\n😴\tsleeping\tface\n🫩\tface_with_bags_under_eyes\n😷\tmask\tface medical\n🤒\tface_with_thermometer\n🤕\tface_with_head_bandage\thead-bandage\n🤢\tnauseated_face\n🤮\tface_vomiting face_with_open_mouth_vomiting\n🤧\tsneezing_face\n🥵\thot_face\toverheated\n🥶\tcold_face\tfreezing\n🥴\twoozy_face\tuneven eyes wavy mouth\n😵\tdizzy_face\n😵‍💫\tface_with_spiral_eyes\n🤯\texploding_head shocked_face_with_exploding_head\n🤠\tface_with_cowboy_hat\n🥳\tpartying_face\tparty horn hat\n🥸\tdisguised_face\n😎\tsunglasses\tsmiling face\n🤓\tnerd_face\n🧐\tface_with_monocle\n😕\tconfused\tface\n🫤\tface_with_diagonal_mouth\n😟\tworried\tface\n🙁\tslightly_frowning_face\n☹️\twhite_frowning_face\n😮\topen_mouth\tface\n😯\thushed\tface\n😲\tastonished\tface\n😳\tflushed\tface\n🥺\tpleading_face\teyes\n🥹\tface_holding_back_tears\n😦\tfrowning\tface open mouth\n😧\tanguished\tface\n😨\tfearful\tface\n😰\tcold_sweat\tface open mouth\n😥\tdisappointed_relieved\tbut face\n😢\tcry\tcrying face\n😭\tsob\tloudly crying face\n😱\tscream\tface screaming fear\n😖\tconfounded\tface\n😣\tpersevere\tpersevering face\n😞\tdisappointed\tface\n😓\tsweat\tface cold\n😩\tweary\tface\n😫\ttired_face\n🥱\tyawning_face\n😤\ttriumph\tface look\n😡\trage\tpouting face\n😠\tangry\tface\n🤬\tface_with_symbols_on_mouth serious_face_with_symbols_covering_mouth\n😈\tsmiling_imp\tface horns\n👿\timp\n💀\tskull\n☠️\tskull_and_crossbones\n💩\thankey poop shit\tpile poo\n🤡\tclown_face\n👹\tjapanese_ogre\n👺\tjapanese_goblin\n👻\tghost\n👽\talien\textraterrestrial\n👾\tspace_invader\talien monster\n🤖\trobot_face\n😺\tsmiley_cat\tsmiling face open mouth\n😸\tsmile_cat\tgrinning face smiling eyes\n😹\tjoy_cat\tface tears\n😻\theart_eyes_cat\tsmiling face heart-shaped\n😼\tsmirk_cat\tface wry smile\n😽\tkissing_cat\tface closed eyes\n🙀\tscream_cat\tweary face\n😿\tcrying_cat_face\n😾\tpouting_cat\tface\n🙈\tsee_no_evil\tsee-no-evil monkey\n🙉\thear_no_evil\thear-no-evil monkey\n🙊\tspeak_no_evil\tspeak-no-evil monkey\n💌\tlove_letter\n💘\tcupid\theart arrow\n💝\tgift_heart\tribbon\n💖\tsparkling_heart\n💗\theartpulse\tgrowing heart\n💓\theartbeat\tbeating heart\n💞\trevolving_hearts\n💕\ttwo_hearts\n💟\theart_decoration\n❣️\theavy_heart_exclamation_mark_ornament\n💔\tbroken_heart\n❤️‍🔥\theart_on_fire\n❤️‍🩹\tmending_heart\n❤️\theart\theavy black\n🩷\tpink_heart\n🧡\torange_heart\n💛\tyellow_heart\n💚\tgreen_heart\n💙\tblue_heart\n🩵\tlight_blue_heart\n💜\tpurple_heart\n🤎\tbrown_heart\n🖤\tblack_heart\n🩶\tgrey_heart\n🤍\twhite_heart\n💋\tkiss\tmark\n💯\t100\thundred points symbol\n💢\tanger\tsymbol\n💥\tboom collision\tsymbol\n💫\tdizzy\tsymbol\n💦\tsweat_drops\tsplashing symbol\n💨\tdash\tsymbol\n🕳️\thole\n💬\tspeech_balloon\n👁️‍🗨️\teye-in-speech-bubble\n🗨️\tleft_speech_bubble\n🗯️\tright_anger_bubble\n💭\tthought_balloon\n💤\tzzz\tsleeping symbol\n👋\twave\twaving hand sign\n🤚\traised_back_of_hand\n🖐️\traised_hand_with_fingers_splayed\n✋\thand raised_hand\n🖖\tspock-hand\traised part between middle ring fingers\n🫱\trightwards_hand\n🫲\tleftwards_hand\n🫳\tpalm_down_hand\n🫴\tpalm_up_hand\n🫷\tleftwards_pushing_hand\n🫸\trightwards_pushing_hand\n👌\tok_hand\tsign\n🤌\tpinched_fingers\n🤏\tpinching_hand\n✌️\tv\tvictory hand\n🤞\tcrossed_fingers hand_with_index_and_middle_fingers_crossed\n🫰\thand_with_index_finger_and_thumb_crossed\n🤟\ti_love_you_hand_sign\n🤘\tthe_horns sign_of_the_horns\n🤙\tcall_me_hand\n👈\tpoint_left\twhite pointing backhand index\n👉\tpoint_right\twhite pointing backhand index\n👆\tpoint_up_2\twhite pointing backhand index\n🖕\tmiddle_finger reversed_hand_with_middle_finger_extended\n👇\tpoint_down\twhite pointing backhand index\n☝️\tpoint_up\twhite pointing index\n🫵\tindex_pointing_at_the_viewer\n👍\t+1 thumbsup\tthumbs up sign\n👎\t-1 thumbsdown\tthumbs down sign\n✊\tfist\traised\n👊\tfacepunch punch\tfisted hand sign\n🤛\tleft-facing_fist\tleft-facing\n🤜\tright-facing_fist\tright-facing\n👏\tclap\tclapping hands sign\n🙌\traised_hands\tperson raising both celebration\n🫶\theart_hands\n👐\topen_hands\tsign\n🤲\tpalms_up_together\n🤝\thandshake\n🙏\tpray\tperson folded hands\n✍️\twriting_hand\n💅\tnail_care\tpolish\n🤳\tselfie\n💪\tmuscle\tflexed biceps\n🦾\tmechanical_arm\n🦿\tmechanical_leg\n🦵\tleg\n🦶\tfoot\n👂\tear\n🦻\tear_with_hearing_aid\n👃\tnose\n🧠\tbrain\n🫀\tanatomical_heart\n🫁\tlungs\n🦷\ttooth\n🦴\tbone\n👀\teyes\n👁️\teye\n👅\ttongue\n👄\tlips\tmouth\n🫦\tbiting_lip\n👶\tbaby\n🧒\tchild\n👦\tboy\n👧\tgirl\n🧑\tadult\n👱\tperson_with_blond_hair\n👨\tman\n🧔\tbearded_person\n🧔‍♂️\tman_with_beard\n🧔‍♀️\twoman_with_beard\n👨‍🦰\tred_haired_man\thair\n👨‍🦱\tcurly_haired_man\thair\n👨‍🦳\twhite_haired_man\thair\n👨‍🦲\tbald_man\n👩\twoman\n👩‍🦰\tred_haired_woman\thair\n🧑‍🦰\tred_haired_person\thair\n👩‍🦱\tcurly_haired_woman\thair\n🧑‍🦱\tcurly_haired_person\thair\n👩‍🦳\twhite_haired_woman\thair\n🧑‍🦳\twhite_haired_person\thair\n👩‍🦲\tbald_woman\n🧑‍🦲\tbald_person\n👱‍♀️\tblond-haired-woman\thair\n👱‍♂️\tblond-haired-man\thair\n🧓\tolder_adult\n👴\tolder_man\n👵\tolder_woman\n🙍\tperson_frowning\n🙍‍♂️\tman-frowning\n🙍‍♀️\twoman-frowning\n🙎\tperson_with_pouting_face\n🙎‍♂️\tman-pouting\n🙎‍♀️\twoman-pouting\n🙅\tno_good\tface gesture\n🙅‍♂️\tman-gesturing-no\n🙅‍♀️\twoman-gesturing-no\n🙆\tok_woman\tface gesture\n🙆‍♂️\tman-gesturing-ok\n🙆‍♀️\twoman-gesturing-ok\n💁\tinformation_desk_person\n💁‍♂️\tman-tipping-hand\n💁‍♀️\twoman-tipping-hand\n🙋\traising_hand\thappy person one\n🙋‍♂️\tman-raising-hand\n🙋‍♀️\twoman-raising-hand\n🧏\tdeaf_person\n🧏‍♂️\tdeaf_man\n🧏‍♀️\tdeaf_woman\n🙇\tbow\tperson bowing deeply\n🙇‍♂️\tman-bowing\n🙇‍♀️\twoman-bowing\n🤦\tface_palm\n🤦‍♂️\tman-facepalming\n🤦‍♀️\twoman-facepalming\n🤷\tshrug\n🤷‍♂️\tman-shrugging\n🤷‍♀️\twoman-shrugging\n🧑‍⚕️\thealth_worker\n👨‍⚕️\tmale-doctor\tman health worker\n👩‍⚕️\tfemale-doctor\twoman health worker\n🧑‍🎓\tstudent\n👨‍🎓\tmale-student\tman\n👩‍🎓\tfemale-student\twoman\n🧑‍🏫\tteacher\n👨‍🏫\tmale-teacher\tman\n👩‍🏫\tfemale-teacher\twoman\n🧑‍⚖️\tjudge\n👨‍⚖️\tmale-judge\tman\n👩‍⚖️\tfemale-judge\twoman\n🧑‍🌾\tfarmer\n👨‍🌾\tmale-farmer\tman\n👩‍🌾\tfemale-farmer\twoman\n🧑‍🍳\tcook\n👨‍🍳\tmale-cook\tman\n👩‍🍳\tfemale-cook\twoman\n🧑‍🔧\tmechanic\n👨‍🔧\tmale-mechanic\tman\n👩‍🔧\tfemale-mechanic\twoman\n🧑‍🏭\tfactory_worker\n👨‍🏭\tmale-factory-worker\tman\n👩‍🏭\tfemale-factory-worker\twoman\n🧑‍💼\toffice_worker\n👨‍💼\tmale-office-worker\tman\n👩‍💼\tfemale-office-worker\twoman\n🧑‍🔬\tscientist\n👨‍🔬\tmale-scientist\tman\n👩‍🔬\tfemale-scientist\twoman\n🧑‍💻\ttechnologist\n👨‍💻\tmale-technologist\tman\n👩‍💻\tfemale-technologist\twoman\n🧑‍🎤\tsinger\n👨‍🎤\tmale-singer\tman\n👩‍🎤\tfemale-singer\twoman\n🧑‍🎨\tartist\n👨‍🎨\tmale-artist\tman\n👩‍🎨\tfemale-artist\twoman\n🧑‍✈️\tpilot\n👨‍✈️\tmale-pilot\tman\n👩‍✈️\tfemale-pilot\twoman\n🧑‍🚀\tastronaut\n👨‍🚀\tmale-astronaut\tman\n👩‍🚀\tfemale-astronaut\twoman\n🧑‍🚒\tfirefighter\n👨‍🚒\tmale-firefighter\tman\n👩‍🚒\tfemale-firefighter\twoman\n👮\tcop\tpolice officer\n👮‍♂️\tmale-police-officer\tman\n👮‍♀️\tfemale-police-officer\twoman\n🕵️\tsleuth_or_spy\tdetective\n🕵️‍♂️\tmale-detective\tman\n🕵️‍♀️\tfemale-detective\twoman\n💂\tguardsman\n💂‍♂️\tmale-guard\tman\n💂‍♀️\tfemale-guard\twoman\n🥷\tninja\n👷\tconstruction_worker\n👷‍♂️\tmale-construction-worker\tman\n👷‍♀️\tfemale-construction-worker\twoman\n🫅\tperson_with_crown\n🤴\tprince\n👸\tprincess\n👳\tman_with_turban\n👳‍♂️\tman-wearing-turban\n👳‍♀️\twoman-wearing-turban\n👲\tman_with_gua_pi_mao\n🧕\tperson_with_headscarf\n🤵\tperson_in_tuxedo\tman\n🤵‍♂️\tman_in_tuxedo\n🤵‍♀️\twoman_in_tuxedo\n👰\tbride_with_veil\n👰‍♂️\tman_with_veil\n👰‍♀️\twoman_with_veil\n🤰\tpregnant_woman\n🫃\tpregnant_man\n🫄\tpregnant_person\n🤱\tbreast-feeding\n👩‍🍼\twoman_feeding_baby\n👨‍🍼\tman_feeding_baby\n🧑‍🍼\tperson_feeding_baby\n👼\tangel\tbaby\n🎅\tsanta\tfather christmas\n🤶\tmrs_claus mother_christmas\n🧑‍🎄\tmx_claus\n🦸\tsuperhero\n🦸‍♂️\tmale_superhero\tman\n🦸‍♀️\tfemale_superhero\twoman\n🦹\tsupervillain\n🦹‍♂️\tmale_supervillain\tman\n🦹‍♀️\tfemale_supervillain\twoman\n🧙\tmage\n🧙‍♂️\tmale_mage\tman\n🧙‍♀️\tfemale_mage\twoman\n🧚\tfairy\n🧚‍♂️\tmale_fairy\tman\n🧚‍♀️\tfemale_fairy\twoman\n🧛\tvampire\n🧛‍♂️\tmale_vampire\tman\n🧛‍♀️\tfemale_vampire\twoman\n🧜\tmerperson\n🧜‍♂️\tmerman\n🧜‍♀️\tmermaid\n🧝\telf\n🧝‍♂️\tmale_elf\tman\n🧝‍♀️\tfemale_elf\twoman\n🧞\tgenie\n🧞‍♂️\tmale_genie\tman\n🧞‍♀️\tfemale_genie\twoman\n🧟\tzombie\n🧟‍♂️\tmale_zombie\tman\n🧟‍♀️\tfemale_zombie\twoman\n🧌\ttroll\n💆\tmassage\tface\n💆‍♂️\tman-getting-massage\n💆‍♀️\twoman-getting-massage\n💇\thaircut\n💇‍♂️\tman-getting-haircut\n💇‍♀️\twoman-getting-haircut\n🚶\twalking\tpedestrian\n🚶‍♂️\tman-walking\n🚶‍♀️\twoman-walking\n🚶‍➡️\tperson_walking_facing_right\n🚶‍♀️‍➡️\twoman_walking_facing_right\n🚶‍♂️‍➡️\tman_walking_facing_right\n🧍\tstanding_person\n🧍‍♂️\tman_standing\n🧍‍♀️\twoman_standing\n🧎\tkneeling_person\n🧎‍♂️\tman_kneeling\n🧎‍♀️\twoman_kneeling\n🧎‍➡️\tperson_kneeling_facing_right\n🧎‍♀️‍➡️\twoman_kneeling_facing_right\n🧎‍♂️‍➡️\tman_kneeling_facing_right\n🧑‍🦯\tperson_with_probing_cane\twhite\n🧑‍🦯‍➡️\tperson_with_white_cane_facing_right\n👨‍🦯\tman_with_probing_cane\twhite\n👨‍🦯‍➡️\tman_with_white_cane_facing_right\n👩‍🦯\twoman_with_probing_cane\twhite\n👩‍🦯‍➡️\twoman_with_white_cane_facing_right\n🧑‍🦼\tperson_in_motorized_wheelchair\n🧑‍🦼‍➡️\tperson_in_motorized_wheelchair_facing_right\n👨‍🦼\tman_in_motorized_wheelchair\n👨‍🦼‍➡️\tman_in_motorized_wheelchair_facing_right\n👩‍🦼\twoman_in_motorized_wheelchair\n👩‍🦼‍➡️\twoman_in_motorized_wheelchair_facing_right\n🧑‍🦽\tperson_in_manual_wheelchair\n🧑‍🦽‍➡️\tperson_in_manual_wheelchair_facing_right\n👨‍🦽\tman_in_manual_wheelchair\n👨‍🦽‍➡️\tman_in_manual_wheelchair_facing_right\n👩‍🦽\twoman_in_manual_wheelchair\n👩‍🦽‍➡️\twoman_in_manual_wheelchair_facing_right\n🏃\trunner running\n🏃‍♂️\tman-running\n🏃‍♀️\twoman-running\n🏃‍➡️\tperson_running_facing_right\n🏃‍♀️‍➡️\twoman_running_facing_right\n🏃‍♂️‍➡️\tman_running_facing_right\n💃\tdancer\n🕺\tman_dancing\n🕴️\tman_in_business_suit_levitating\tperson\n👯\tdancers\twoman bunny ears\n👯‍♂️\tmen-with-bunny-ears-partying man-with-bunny-ears-partying\n👯‍♀️\twomen-with-bunny-ears-partying woman-with-bunny-ears-partying\n🧖\tperson_in_steamy_room\n🧖‍♂️\tman_in_steamy_room\n🧖‍♀️\twoman_in_steamy_room\n🧗\tperson_climbing\n🧗‍♂️\tman_climbing\n🧗‍♀️\twoman_climbing\n🤺\tfencer\n🏇\thorse_racing\n⛷️\tskier\n🏂\tsnowboarder\n🏌️\tgolfer\tperson golfing\n🏌️‍♂️\tman-golfing\n🏌️‍♀️\twoman-golfing\n🏄\tsurfer\n🏄‍♂️\tman-surfing\n🏄‍♀️\twoman-surfing\n🚣\trowboat\n🚣‍♂️\tman-rowing-boat\n🚣‍♀️\twoman-rowing-boat\n🏊\tswimmer\n🏊‍♂️\tman-swimming\n🏊‍♀️\twoman-swimming\n⛹️\tperson_with_ball\tbouncing\n⛹️‍♂️\tman-bouncing-ball\n⛹️‍♀️\twoman-bouncing-ball\n🏋️\tweight_lifter\tperson lifting weights\n🏋️‍♂️\tman-lifting-weights\n🏋️‍♀️\twoman-lifting-weights\n🚴\tbicyclist\n🚴‍♂️\tman-biking\n🚴‍♀️\twoman-biking\n🚵\tmountain_bicyclist\n🚵‍♂️\tman-mountain-biking\n🚵‍♀️\twoman-mountain-biking\n🤸\tperson_doing_cartwheel\n🤸‍♂️\tman-cartwheeling\n🤸‍♀️\twoman-cartwheeling\n🤼\twrestlers\n🤼‍♂️\tman-wrestling\tmen\n🤼‍♀️\twoman-wrestling\twomen\n🤽\twater_polo\n🤽‍♂️\tman-playing-water-polo\n🤽‍♀️\twoman-playing-water-polo\n🤾\thandball\n🤾‍♂️\tman-playing-handball\n🤾‍♀️\twoman-playing-handball\n🤹\tjuggling\n🤹‍♂️\tman-juggling\n🤹‍♀️\twoman-juggling\n🧘\tperson_in_lotus_position\n🧘‍♂️\tman_in_lotus_position\n🧘‍♀️\twoman_in_lotus_position\n🛀\tbath\n🛌\tsleeping_accommodation\n🧑‍🤝‍🧑\tpeople_holding_hands\n👭\ttwo_women_holding_hands women_holding_hands\n👫\tman_and_woman_holding_hands woman_and_man_holding_hands couple\n👬\ttwo_men_holding_hands men_holding_hands\n💏\tcouplekiss\tkiss\n👩‍❤️‍💋‍👨\twoman-kiss-man\n👨‍❤️‍💋‍👨\tman-kiss-man\n👩‍❤️‍💋‍👩\twoman-kiss-woman\n💑\tcouple_with_heart\n👩‍❤️‍👨\twoman-heart-man\tcouple\n👨‍❤️‍👨\tman-heart-man\tcouple\n👩‍❤️‍👩\twoman-heart-woman\tcouple\n👨‍👩‍👦\tman-woman-boy\tfamily\n👨‍👩‍👧\tman-woman-girl\tfamily\n👨‍👩‍👧‍👦\tman-woman-girl-boy\tfamily\n👨‍👩‍👦‍👦\tman-woman-boy-boy\tfamily\n👨‍👩‍👧‍👧\tman-woman-girl-girl\tfamily\n👨‍👨‍👦\tman-man-boy\tfamily\n👨‍👨‍👧\tman-man-girl\tfamily\n👨‍👨‍👧‍👦\tman-man-girl-boy\tfamily\n👨‍👨‍👦‍👦\tman-man-boy-boy\tfamily\n👨‍👨‍👧‍👧\tman-man-girl-girl\tfamily\n👩‍👩‍👦\twoman-woman-boy\tfamily\n👩‍👩‍👧\twoman-woman-girl\tfamily\n👩‍👩‍👧‍👦\twoman-woman-girl-boy\tfamily\n👩‍👩‍👦‍👦\twoman-woman-boy-boy\tfamily\n👩‍👩‍👧‍👧\twoman-woman-girl-girl\tfamily\n👨‍👦\tman-boy\tfamily\n👨‍👦‍👦\tman-boy-boy\tfamily\n👨‍👧\tman-girl\tfamily\n👨‍👧‍👦\tman-girl-boy\tfamily\n👨‍👧‍👧\tman-girl-girl\tfamily\n👩‍👦\twoman-boy\tfamily\n👩‍👦‍👦\twoman-boy-boy\tfamily\n👩‍👧\twoman-girl\tfamily\n👩‍👧‍👦\twoman-girl-boy\tfamily\n👩‍👧‍👧\twoman-girl-girl\tfamily\n🗣️\tspeaking_head_in_silhouette\n👤\tbust_in_silhouette\n👥\tbusts_in_silhouette\n🫂\tpeople_hugging\n👪\tfamily\n🧑‍🧑‍🧒\tfamily_adult_adult_child\n🧑‍🧑‍🧒‍🧒\tfamily_adult_adult_child_child\n🧑‍🧒\tfamily_adult_child\n🧑‍🧒‍🧒\tfamily_adult_child_child\n👣\tfootprints\n🫆\tfingerprint\n🐵\tmonkey_face\n🐒\tmonkey\n🦍\tgorilla\n🦧\torangutan\n🐶\tdog\tface\n🐕\tdog2\tdog\n🦮\tguide_dog\n🐕‍🦺\tservice_dog\n🐩\tpoodle\n🐺\twolf\tface\n🦊\tfox_face\n🦝\traccoon\n🐱\tcat\tface\n🐈\tcat2\tcat\n🐈‍⬛\tblack_cat\n🦁\tlion_face\n🐯\ttiger\tface\n🐅\ttiger2\ttiger\n🐆\tleopard\n🐴\thorse\tface\n🫎\tmoose\n🫏\tdonkey\n🐎\tracehorse\thorse\n🦄\tunicorn_face\n🦓\tzebra_face\n🦌\tdeer\n🦬\tbison\n🐮\tcow\tface\n🐂\tox\n🐃\twater_buffalo\n🐄\tcow2\tcow\n🐷\tpig\tface\n🐖\tpig2\tpig\n🐗\tboar\n🐽\tpig_nose\n🐏\tram\n🐑\tsheep\n🐐\tgoat\n🐪\tdromedary_camel\n🐫\tcamel\tbactrian\n🦙\tllama\n🦒\tgiraffe_face\n🐘\telephant\n🦣\tmammoth\n🦏\trhinoceros\n🦛\thippopotamus\n🐭\tmouse\tface\n🐁\tmouse2\tmouse\n🐀\trat\n🐹\thamster\tface\n🐰\trabbit\tface\n🐇\trabbit2\trabbit\n🐿️\tchipmunk\n🦫\tbeaver\n🦔\thedgehog\n🦇\tbat\n🐻\tbear\tface\n🐻‍❄️\tpolar_bear\n🐨\tkoala\n🐼\tpanda_face\n🦥\tsloth\n🦦\totter\n🦨\tskunk\n🦘\tkangaroo\n🦡\tbadger\n🐾\tfeet paw_prints\n🦃\tturkey\n🐔\tchicken\n🐓\trooster\n🐣\thatching_chick\n🐤\tbaby_chick\n🐥\thatched_chick\tfront-facing baby\n🐦\tbird\n🐧\tpenguin\n🕊️\tdove_of_peace\n🦅\teagle\n🦆\tduck\n🦢\tswan\n🦉\towl\n🦤\tdodo\n🪶\tfeather\n🦩\tflamingo\n🦚\tpeacock\n🦜\tparrot\n🪽\twing\n🐦‍⬛\tblack_bird\n🪿\tgoose\n🐦‍🔥\tphoenix\n🐸\tfrog\tface\n🐊\tcrocodile\n🐢\tturtle\n🦎\tlizard\n🐍\tsnake\n🐲\tdragon_face\n🐉\tdragon\n🦕\tsauropod\n🦖\tt-rex\n🐳\twhale\tspouting\n🐋\twhale2\twhale\n🐬\tdolphin flipper\n🦭\tseal\n🐟\tfish\n🐠\ttropical_fish\n🐡\tblowfish\n🦈\tshark\n🐙\toctopus\n🐚\tshell\tspiral\n🪸\tcoral\n🪼\tjellyfish\n🦀\tcrab\n🦞\tlobster\n🦐\tshrimp\n🦑\tsquid\n🦪\toyster\n🐌\tsnail\n🦋\tbutterfly\n🐛\tbug\n🐜\tant\n🐝\tbee honeybee\n🪲\tbeetle\n🐞\tladybug lady_beetle\n🦗\tcricket\n🪳\tcockroach\n🕷️\tspider\n🕸️\tspider_web\n🦂\tscorpion\n🦟\tmosquito\n🪰\tfly\n🪱\tworm\n🦠\tmicrobe\n💐\tbouquet\n🌸\tcherry_blossom\n💮\twhite_flower\n🪷\tlotus\n🏵️\trosette\n🌹\trose\n🥀\twilted_flower\n🌺\thibiscus\n🌻\tsunflower\n🌼\tblossom\n🌷\ttulip\n🪻\thyacinth\n🌱\tseedling\n🪴\tpotted_plant\n🌲\tevergreen_tree\n🌳\tdeciduous_tree\n🌴\tpalm_tree\n🌵\tcactus\n🌾\tear_of_rice\n🌿\therb\n☘️\tshamrock\n🍀\tfour_leaf_clover\n🍁\tmaple_leaf\n🍂\tfallen_leaf\n🍃\tleaves\tleaf fluttering wind\n🪹\tempty_nest\n🪺\tnest_with_eggs\n🍄\tmushroom\n🪾\tleafless_tree\n🍇\tgrapes\n🍈\tmelon\n🍉\twatermelon\n🍊\ttangerine\n🍋\tlemon\n🍋‍🟩\tlime\n🍌\tbanana\n🍍\tpineapple\n🥭\tmango\n🍎\tapple\tred\n🍏\tgreen_apple\n🍐\tpear\n🍑\tpeach\n🍒\tcherries\n🍓\tstrawberry\n🫐\tblueberries\n🥝\tkiwifruit\n🍅\ttomato\n🫒\tolive\n🥥\tcoconut\n🥑\tavocado\n🍆\teggplant\taubergine\n🥔\tpotato\n🥕\tcarrot\n🌽\tcorn\tear maize\n🌶️\thot_pepper\n🫑\tbell_pepper\n🥒\tcucumber\n🥬\tleafy_green\n🥦\tbroccoli\n🧄\tgarlic\n🧅\tonion\n🥜\tpeanuts\n🫘\tbeans\n🌰\tchestnut\n🫚\tginger_root\n🫛\tpea_pod\n🍄‍🟫\tbrown_mushroom\n🫜\troot_vegetable\n🍞\tbread\n🥐\tcroissant\n🥖\tbaguette_bread\n🫓\tflatbread\n🥨\tpretzel\n🥯\tbagel\n🥞\tpancakes\n🧇\twaffle\n🧀\tcheese_wedge\n🍖\tmeat_on_bone\n🍗\tpoultry_leg\n🥩\tcut_of_meat\n🥓\tbacon\n🍔\thamburger\n🍟\tfries\tfrench\n🍕\tpizza\tslice\n🌭\thotdog\thot dog\n🥪\tsandwich\n🌮\ttaco\n🌯\tburrito\n🫔\ttamale\n🥙\tstuffed_flatbread\n🧆\tfalafel\n🥚\tegg\n🍳\tfried_egg cooking\n🥘\tshallow_pan_of_food\n🍲\tstew\tpot food\n🫕\tfondue\n🥣\tbowl_with_spoon\n🥗\tgreen_salad\n🍿\tpopcorn\n🧈\tbutter\n🧂\tsalt\tshaker\n🥫\tcanned_food\n🍱\tbento\tbox\n🍘\trice_cracker\n🍙\trice_ball\n🍚\trice\tcooked\n🍛\tcurry\trice\n🍜\tramen\tsteaming bowl\n🍝\tspaghetti\n🍠\tsweet_potato\troasted\n🍢\toden\n🍣\tsushi\n🍤\tfried_shrimp\n🍥\tfish_cake\tswirl design\n🥮\tmoon_cake\n🍡\tdango\n🥟\tdumpling\n🥠\tfortune_cookie\n🥡\ttakeout_box\n🍦\ticecream\tsoft ice cream\n🍧\tshaved_ice\n🍨\tice_cream\n🍩\tdoughnut\n🍪\tcookie\n🎂\tbirthday\tcake\n🍰\tcake\tshortcake\n🧁\tcupcake\n🥧\tpie\n🍫\tchocolate_bar\n🍬\tcandy\n🍭\tlollipop\n🍮\tcustard\n🍯\thoney_pot\n🍼\tbaby_bottle\n🥛\tglass_of_milk\n☕\tcoffee\thot beverage\n🫖\tteapot\n🍵\ttea\tteacup without handle\n🍶\tsake\tbottle cup\n🍾\tchampagne\tbottle popping cork\n🍷\twine_glass\n🍸\tcocktail\tglass\n🍹\ttropical_drink\n🍺\tbeer\tmug\n🍻\tbeers\tclinking beer mugs\n🥂\tclinking_glasses\n🥃\ttumbler_glass\n🫗\tpouring_liquid\n🥤\tcup_with_straw\n🧋\tbubble_tea\n🧃\tbeverage_box\n🧉\tmate_drink\n🧊\tice_cube\n🥢\tchopsticks\n🍽️\tknife_fork_plate\n🍴\tfork_and_knife\n🥄\tspoon\n🔪\thocho knife\n🫙\tjar\n🏺\tamphora\n🌍\tearth_africa\tglobe europe-africa\n🌎\tearth_americas\tglobe\n🌏\tearth_asia\tglobe asia-australia\n🌐\tglobe_with_meridians\n🗺️\tworld_map\n🗾\tjapan\tsilhouette\n🧭\tcompass\n🏔️\tsnow_capped_mountain\tsnow-capped\n⛰️\tmountain\n🌋\tvolcano\n🗻\tmount_fuji\n🏕️\tcamping\n🏖️\tbeach_with_umbrella\n🏜️\tdesert\n🏝️\tdesert_island\n🏞️\tnational_park\n🏟️\tstadium\n🏛️\tclassical_building\n🏗️\tbuilding_construction\n🧱\tbricks\tbrick\n🪨\trock\n🪵\twood\n🛖\thut\n🏘️\thouse_buildings\thouses\n🏚️\tderelict_house_building\n🏠\thouse\tbuilding\n🏡\thouse_with_garden\n🏢\toffice\tbuilding\n🏣\tpost_office\tjapanese\n🏤\teuropean_post_office\n🏥\thospital\n🏦\tbank\n🏨\thotel\n🏩\tlove_hotel\n🏪\tconvenience_store\n🏫\tschool\n🏬\tdepartment_store\n🏭\tfactory\n🏯\tjapanese_castle\n🏰\teuropean_castle\n💒\twedding\n🗼\ttokyo_tower\n🗽\tstatue_of_liberty\n⛪\tchurch\n🕌\tmosque\n🛕\thindu_temple\n🕍\tsynagogue\n⛩️\tshinto_shrine\n🕋\tkaaba\n⛲\tfountain\n⛺\ttent\n🌁\tfoggy\n🌃\tnight_with_stars\n🏙️\tcityscape\n🌄\tsunrise_over_mountains\n🌅\tsunrise\n🌆\tcity_sunset\tcityscape at dusk\n🌇\tcity_sunrise\tsunset over buildings\n🌉\tbridge_at_night\n♨️\thotsprings\thot springs\n🎠\tcarousel_horse\n🛝\tplayground_slide\n🎡\tferris_wheel\n🎢\troller_coaster\n💈\tbarber\tpole\n🎪\tcircus_tent\n🚂\tsteam_locomotive\n🚃\trailway_car\n🚄\tbullettrain_side\thigh-speed train\n🚅\tbullettrain_front\thigh-speed train bullet nose\n🚆\ttrain2\ttrain\n🚇\tmetro\n🚈\tlight_rail\n🚉\tstation\n🚊\ttram\n🚝\tmonorail\n🚞\tmountain_railway\n🚋\ttrain\ttram car\n🚌\tbus\n🚍\toncoming_bus\n🚎\ttrolleybus\n🚐\tminibus\n🚑\tambulance\n🚒\tfire_engine\n🚓\tpolice_car\n🚔\toncoming_police_car\n🚕\ttaxi\n🚖\toncoming_taxi\n🚗\tcar red_car\tautomobile\n🚘\toncoming_automobile\n🚙\tblue_car\trecreational vehicle\n🛻\tpickup_truck\n🚚\ttruck\tdelivery\n🚛\tarticulated_lorry\n🚜\ttractor\n🏎️\tracing_car\n🏍️\tracing_motorcycle\n🛵\tmotor_scooter\n🦽\tmanual_wheelchair\n🦼\tmotorized_wheelchair\n🛺\tauto_rickshaw\n🚲\tbike\tbicycle\n🛴\tscooter\n🛹\tskateboard\n🛼\troller_skate\n🚏\tbusstop\tbus stop\n🛣️\tmotorway\n🛤️\trailway_track\n🛢️\toil_drum\n⛽\tfuelpump\tfuel pump\n🛞\twheel\n🚨\trotating_light\tpolice cars revolving\n🚥\ttraffic_light\thorizontal\n🚦\tvertical_traffic_light\n🛑\toctagonal_sign\n🚧\tconstruction\tsign\n⚓\tanchor\n🛟\tring_buoy\n⛵\tboat sailboat\n🛶\tcanoe\n🚤\tspeedboat\n🛳️\tpassenger_ship\n⛴️\tferry\n🛥️\tmotor_boat\n🚢\tship\n✈️\tairplane\n🛩️\tsmall_airplane\n🛫\tairplane_departure\n🛬\tairplane_arriving\n🪂\tparachute\n💺\tseat\n🚁\thelicopter\n🚟\tsuspension_railway\n🚠\tmountain_cableway\n🚡\taerial_tramway\n🛰️\tsatellite\n🚀\trocket\n🛸\tflying_saucer\n🛎️\tbellhop_bell\n🧳\tluggage\n⌛\thourglass\n⏳\thourglass_flowing_sand\n⌚\twatch\n⏰\talarm_clock\n⏱️\tstopwatch\n⏲️\ttimer_clock\n🕰️\tmantelpiece_clock\n🕛\tclock12\tclock face twelve oclock\n🕧\tclock1230\tclock face twelve-thirty\n🕐\tclock1\tclock face one oclock\n🕜\tclock130\tclock face one-thirty\n🕑\tclock2\tclock face two oclock\n🕝\tclock230\tclock face two-thirty\n🕒\tclock3\tclock face three oclock\n🕞\tclock330\tclock face three-thirty\n🕓\tclock4\tclock face four oclock\n🕟\tclock430\tclock face four-thirty\n🕔\tclock5\tclock face five oclock\n🕠\tclock530\tclock face five-thirty\n🕕\tclock6\tclock face six oclock\n🕡\tclock630\tclock face six-thirty\n🕖\tclock7\tclock face seven oclock\n🕢\tclock730\tclock face seven-thirty\n🕗\tclock8\tclock face eight oclock\n🕣\tclock830\tclock face eight-thirty\n🕘\tclock9\tclock face nine oclock\n🕤\tclock930\tclock face nine-thirty\n🕙\tclock10\tclock face ten oclock\n🕥\tclock1030\tclock face ten-thirty\n🕚\tclock11\tclock face eleven oclock\n🕦\tclock1130\tclock face eleven-thirty\n🌑\tnew_moon\tsymbol\n🌒\twaxing_crescent_moon\tsymbol\n🌓\tfirst_quarter_moon\tsymbol\n🌔\tmoon waxing_gibbous_moon\tsymbol\n🌕\tfull_moon\tsymbol\n🌖\twaning_gibbous_moon\tsymbol\n🌗\tlast_quarter_moon\tsymbol\n🌘\twaning_crescent_moon\tsymbol\n🌙\tcrescent_moon\n🌚\tnew_moon_with_face\n🌛\tfirst_quarter_moon_with_face\n🌜\tlast_quarter_moon_with_face\n🌡️\tthermometer\n☀️\tsunny\tblack sun rays\n🌝\tfull_moon_with_face\n🌞\tsun_with_face\n🪐\tringed_planet\n⭐\tstar\twhite medium\n🌟\tstar2\tglowing star\n🌠\tstars\tshooting star\n🌌\tmilky_way\n☁️\tcloud\n⛅\tpartly_sunny\tsun behind cloud\n⛈️\tthunder_cloud_and_rain\tlightning\n🌤️\tmostly_sunny sun_small_cloud\tbehind\n🌥️\tbarely_sunny sun_behind_cloud\tlarge\n🌦️\tpartly_sunny_rain sun_behind_rain_cloud\n🌧️\train_cloud\n🌨️\tsnow_cloud\n🌩️\tlightning lightning_cloud\n🌪️\ttornado tornado_cloud\n🌫️\tfog\n🌬️\twind_blowing_face\n🌀\tcyclone\n🌈\trainbow\n🌂\tclosed_umbrella\n☂️\tumbrella\n☔\tumbrella_with_rain_drops\n⛱️\tumbrella_on_ground\n⚡\tzap\thigh voltage sign\n❄️\tsnowflake\n☃️\tsnowman\n⛄\tsnowman_without_snow\n☄️\tcomet\n🔥\tfire\n💧\tdroplet\n🌊\tocean\twater wave\n🎃\tjack_o_lantern\tjack-o-lantern\n🎄\tchristmas_tree\n🎆\tfireworks\n🎇\tsparkler\tfirework\n🧨\tfirecracker\n✨\tsparkles\n🎈\tballoon\n🎉\ttada\tparty popper\n🎊\tconfetti_ball\n🎋\ttanabata_tree\n🎍\tbamboo\tpine decoration\n🎎\tdolls\tjapanese\n🎏\tflags\tcarp streamer\n🎐\twind_chime\n🎑\trice_scene\tmoon viewing ceremony\n🧧\tred_envelope\tgift\n🎀\tribbon\n🎁\tgift\twrapped present\n🎗️\treminder_ribbon\n🎟️\tadmission_tickets\n🎫\tticket\n🎖️\tmedal\tmilitary\n🏆\ttrophy\n🏅\tsports_medal\n🥇\tfirst_place_medal\n🥈\tsecond_place_medal\n🥉\tthird_place_medal\n⚽\tsoccer\tball\n⚾\tbaseball\n🥎\tsoftball\n🏀\tbasketball\thoop\n🏐\tvolleyball\n🏈\tfootball\tamerican\n🏉\trugby_football\n🎾\ttennis\tracquet ball\n🥏\tflying_disc\n🎳\tbowling\n🏏\tcricket_bat_and_ball\n🏑\tfield_hockey_stick_and_ball\n🏒\tice_hockey_stick_and_puck\n🥍\tlacrosse\tstick ball\n🏓\ttable_tennis_paddle_and_ball\n🏸\tbadminton_racquet_and_shuttlecock\n🥊\tboxing_glove\n🥋\tmartial_arts_uniform\n🥅\tgoal_net\n⛳\tgolf\tflag hole\n⛸️\tice_skate\n🎣\tfishing_pole_and_fish\n🤿\tdiving_mask\n🎽\trunning_shirt_with_sash\n🎿\tski\tboot\n🛷\tsled\n🥌\tcurling_stone\n🎯\tdart\tdirect hit\n🪀\tyo-yo\n🪁\tkite\n🔫\tgun\tpistol\n🎱\t8ball\tbilliards\n🔮\tcrystal_ball\n🪄\tmagic_wand\n🎮\tvideo_game\n🕹️\tjoystick\n🎰\tslot_machine\n🎲\tgame_die\n🧩\tjigsaw\tpuzzle piece\n🧸\tteddy_bear\n🪅\tpinata\n🪩\tmirror_ball\n🪆\tnesting_dolls\n♠️\tspades\tblack spade suit\n♥️\thearts\tblack heart suit\n♦️\tdiamonds\tblack diamond suit\n♣️\tclubs\tblack club suit\n♟️\tchess_pawn\n🃏\tblack_joker\tplaying card\n🀄\tmahjong\ttile red dragon\n🎴\tflower_playing_cards\n🎭\tperforming_arts\n🖼️\tframe_with_picture\tframed\n🎨\tart\tartist palette\n🧵\tthread\tspool\n🪡\tsewing_needle\n🧶\tyarn\tball\n🪢\tknot\n👓\teyeglasses\n🕶️\tdark_sunglasses\n🥽\tgoggles\n🥼\tlab_coat\n🦺\tsafety_vest\n👔\tnecktie\n👕\tshirt tshirt\tt-shirt\n👖\tjeans\n🧣\tscarf\n🧤\tgloves\n🧥\tcoat\n🧦\tsocks\n👗\tdress\n👘\tkimono\n🥻\tsari\n🩱\tone-piece_swimsuit\tone-piece\n🩲\tbriefs\n🩳\tshorts\n👙\tbikini\n👚\twomans_clothes\n🪭\tfolding_hand_fan\n👛\tpurse\n👜\thandbag\n👝\tpouch\n🛍️\tshopping_bags\n🎒\tschool_satchel\n🩴\tthong_sandal\n👞\tmans_shoe shoe\n👟\tathletic_shoe\n🥾\thiking_boot\n🥿\twomans_flat_shoe\n👠\thigh_heel\thigh-heeled shoe\n👡\tsandal\twomans\n🩰\tballet_shoes\n👢\tboot\twomans boots\n🪮\thair_pick\n👑\tcrown\n👒\twomans_hat\n🎩\ttophat\ttop hat\n🎓\tmortar_board\tgraduation cap\n🧢\tbilled_cap\n🪖\tmilitary_helmet\n⛑️\thelmet_with_white_cross\trescue worker s\n📿\tprayer_beads\n💄\tlipstick\n💍\tring\n💎\tgem\tstone\n🔇\tmute\tspeaker cancellation stroke\n🔈\tspeaker\n🔉\tsound\tspeaker one wave\n🔊\tloud_sound\tspeaker three waves\n📢\tloudspeaker\tpublic address\n📣\tmega\tcheering megaphone\n📯\tpostal_horn\n🔔\tbell\n🔕\tno_bell\tcancellation stroke\n🎼\tmusical_score\n🎵\tmusical_note\n🎶\tnotes\tmultiple musical\n🎙️\tstudio_microphone\n🎚️\tlevel_slider\n🎛️\tcontrol_knobs\n🎤\tmicrophone\n🎧\theadphones\theadphone\n📻\tradio\n🎷\tsaxophone\n🪗\taccordion\n🎸\tguitar\n🎹\tmusical_keyboard\n🎺\ttrumpet\n🎻\tviolin\n🪕\tbanjo\n🥁\tdrum_with_drumsticks\n🪘\tlong_drum\n🪇\tmaracas\n🪈\tflute\n🪉\tharp\n📱\tiphone\tmobile phone\n📲\tcalling\tmobile phone rightwards arrow at left\n☎️\tphone telephone\tblack\n📞\ttelephone_receiver\n📟\tpager\n📠\tfax\tmachine\n🔋\tbattery\n🪫\tlow_battery\n🔌\telectric_plug\n💻\tcomputer\tpersonal\n🖥️\tdesktop_computer\n🖨️\tprinter\n⌨️\tkeyboard\n🖱️\tthree_button_mouse\tcomputer\n🖲️\ttrackball\n💽\tminidisc\n💾\tfloppy_disk\n💿\tcd\toptical disc\n📀\tdvd\n🧮\tabacus\n🎥\tmovie_camera\n🎞️\tfilm_frames\n📽️\tfilm_projector\n🎬\tclapper\tboard\n📺\ttv\ttelevision\n📷\tcamera\n📸\tcamera_with_flash\n📹\tvideo_camera\n📼\tvhs\tvideocassette\n🔍\tmag\tleft-pointing magnifying glass\n🔎\tmag_right\tright-pointing magnifying glass\n🕯️\tcandle\n💡\tbulb\telectric light\n🔦\tflashlight\telectric torch\n🏮\tizakaya_lantern lantern\n🪔\tdiya_lamp\n📔\tnotebook_with_decorative_cover\n📕\tclosed_book\n📖\tbook open_book\n📗\tgreen_book\n📘\tblue_book\n📙\torange_book\n📚\tbooks\n📓\tnotebook\n📒\tledger\n📃\tpage_with_curl\n📜\tscroll\n📄\tpage_facing_up\n📰\tnewspaper\n🗞️\trolled_up_newspaper\trolled-up\n📑\tbookmark_tabs\n🔖\tbookmark\n🏷️\tlabel\n💰\tmoneybag\tmoney bag\n🪙\tcoin\n💴\tyen\tbanknote sign\n💵\tdollar\tbanknote sign\n💶\teuro\tbanknote sign\n💷\tpound\tbanknote sign\n💸\tmoney_with_wings\n💳\tcredit_card\n🧾\treceipt\n💹\tchart\tupwards trend yen sign\n✉️\temail envelope\n📧\te-mail\tsymbol\n📨\tincoming_envelope\n📩\tenvelope_with_arrow\tdownwards above\n📤\toutbox_tray\n📥\tinbox_tray\n📦\tpackage\n📫\tmailbox\tclosed raised flag\n📪\tmailbox_closed\tlowered flag\n📬\tmailbox_with_mail\topen raised flag\n📭\tmailbox_with_no_mail\topen lowered flag\n📮\tpostbox\n🗳️\tballot_box_with_ballot\n✏️\tpencil2\tpencil\n✒️\tblack_nib\n🖋️\tlower_left_fountain_pen\n🖊️\tlower_left_ballpoint_pen\n🖌️\tlower_left_paintbrush\n🖍️\tlower_left_crayon\n📝\tmemo pencil\n💼\tbriefcase\n📁\tfile_folder\n📂\topen_file_folder\n🗂️\tcard_index_dividers\n📅\tdate\tcalendar\n📆\tcalendar\ttear-off\n🗒️\tspiral_note_pad\tnotepad\n🗓️\tspiral_calendar_pad\n📇\tcard_index\n📈\tchart_with_upwards_trend\n📉\tchart_with_downwards_trend\n📊\tbar_chart\n📋\tclipboard\n📌\tpushpin\n📍\tround_pushpin\n📎\tpaperclip\n🖇️\tlinked_paperclips\n📏\tstraight_ruler\n📐\ttriangular_ruler\n✂️\tscissors\tblack\n🗃️\tcard_file_box\n🗄️\tfile_cabinet\n🗑️\twastebasket\n🔒\tlock\n🔓\tunlock\topen lock\n🔏\tlock_with_ink_pen\n🔐\tclosed_lock_with_key\n🔑\tkey\n🗝️\told_key\n🔨\thammer\n🪓\taxe\n⛏️\tpick\n⚒️\thammer_and_pick\n🛠️\thammer_and_wrench\n🗡️\tdagger_knife\n⚔️\tcrossed_swords\n💣\tbomb\n🪃\tboomerang\n🏹\tbow_and_arrow\n🛡️\tshield\n🪚\tcarpentry_saw\n🔧\twrench\n🪛\tscrewdriver\n🔩\tnut_and_bolt\n⚙️\tgear\n🗜️\tcompression\tclamp\n⚖️\tscales\tbalance scale\n🦯\tprobing_cane\n🔗\tlink\tsymbol\n⛓️‍💥\tbroken_chain\n⛓️\tchains\n🪝\thook\n🧰\ttoolbox\n🧲\tmagnet\n🪜\tladder\n🪏\tshovel\n⚗️\talembic\n🧪\ttest_tube\n🧫\tpetri_dish\n🧬\tdna\tdouble helix\n🔬\tmicroscope\n🔭\ttelescope\n📡\tsatellite_antenna\n💉\tsyringe\n🩸\tdrop_of_blood\n💊\tpill\n🩹\tadhesive_bandage\n🩼\tcrutch\n🩺\tstethoscope\n🩻\tx-ray\n🚪\tdoor\n🛗\televator\n🪞\tmirror\n🪟\twindow\n🛏️\tbed\n🛋️\tcouch_and_lamp\n🪑\tchair\n🚽\ttoilet\n🪠\tplunger\n🚿\tshower\n🛁\tbathtub\n🪤\tmouse_trap\n🪒\trazor\n🧴\tlotion_bottle\n🧷\tsafety_pin\n🧹\tbroom\n🧺\tbasket\n🧻\troll_of_paper\n🪣\tbucket\n🧼\tsoap\tbar\n🫧\tbubbles\n🪥\ttoothbrush\n🧽\tsponge\n🧯\tfire_extinguisher\n🛒\tshopping_trolley\n🚬\tsmoking\tsymbol\n⚰️\tcoffin\n🪦\theadstone\n⚱️\tfuneral_urn\n🧿\tnazar_amulet\n🪬\thamsa\n🗿\tmoyai\n🪧\tplacard\n🪪\tidentification_card\n🏧\tatm\tautomated teller machine\n🚮\tput_litter_in_its_place\tsymbol\n🚰\tpotable_water\tsymbol\n♿\twheelchair\tsymbol\n🚹\tmens\tsymbol\n🚺\twomens\tsymbol\n🚻\trestroom\n🚼\tbaby_symbol\n🚾\twc\twater closet\n🛂\tpassport_control\n🛃\tcustoms\n🛄\tbaggage_claim\n🛅\tleft_luggage\n⚠️\twarning\tsign\n🚸\tchildren_crossing\n⛔\tno_entry\n🚫\tno_entry_sign\n🚳\tno_bicycles\n🚭\tno_smoking\tsymbol\n🚯\tdo_not_litter\tsymbol\n🚱\tnon-potable_water\tnon-potable symbol\n🚷\tno_pedestrians\n📵\tno_mobile_phones\n🔞\tunderage\tno one under eighteen symbol\n☢️\tradioactive_sign\n☣️\tbiohazard_sign\n⬆️\tarrow_up\tupwards black\n↗️\tarrow_upper_right\tnorth east\n➡️\tarrow_right\tblack rightwards\n↘️\tarrow_lower_right\tsouth east\n⬇️\tarrow_down\tdownwards black\n↙️\tarrow_lower_left\tsouth west\n⬅️\tarrow_left\tleftwards black\n↖️\tarrow_upper_left\tnorth west\n↕️\tarrow_up_down\n↔️\tleft_right_arrow\n↩️\tleftwards_arrow_with_hook\n↪️\tarrow_right_hook\trightwards\n⤴️\tarrow_heading_up\tpointing rightwards then curving upwards\n⤵️\tarrow_heading_down\tpointing rightwards then curving downwards\n🔃\tarrows_clockwise\tdownwards upwards open circle\n🔄\tarrows_counterclockwise\tanticlockwise downwards upwards open circle\n🔙\tback\tleftwards arrow above\n🔚\tend\tleftwards arrow above\n🔛\ton\texclamation mark left right arrow above\n🔜\tsoon\trightwards arrow above\n🔝\ttop\tupwards arrow above\n🛐\tplace_of_worship\n⚛️\tatom_symbol\n🕉️\tom_symbol\n✡️\tstar_of_david\n☸️\twheel_of_dharma\n☯️\tyin_yang\n✝️\tlatin_cross\n☦️\torthodox_cross\n☪️\tstar_and_crescent\n☮️\tpeace_symbol\n🕎\tmenorah_with_nine_branches\n🔯\tsix_pointed_star\tmiddle dot\n🪯\tkhanda\n♈\taries\n♉\ttaurus\n♊\tgemini\n♋\tcancer\n♌\tleo\n♍\tvirgo\n♎\tlibra\n♏\tscorpius\n♐\tsagittarius\n♑\tcapricorn\n♒\taquarius\n♓\tpisces\n⛎\tophiuchus\n🔀\ttwisted_rightwards_arrows\n🔁\trepeat\tclockwise rightwards leftwards open circle arrows\n🔂\trepeat_one\tclockwise rightwards leftwards open circle arrows circled overlay\n▶️\tarrow_forward\tblack right-pointing triangle\n⏩\tfast_forward\tblack right-pointing double triangle\n⏭️\tblack_right_pointing_double_triangle_with_vertical_bar\tnext track button\n⏯️\tblack_right_pointing_triangle_with_double_vertical_bar\tplay pause button\n◀️\tarrow_backward\tblack left-pointing triangle\n⏪\trewind\tblack left-pointing double triangle\n⏮️\tblack_left_pointing_double_triangle_with_vertical_bar\tlast track button\n🔼\tarrow_up_small\tup-pointing red triangle\n⏫\tarrow_double_up\tblack up-pointing triangle\n🔽\tarrow_down_small\tdown-pointing red triangle\n⏬\tarrow_double_down\tblack down-pointing triangle\n⏸️\tdouble_vertical_bar\tpause button\n⏹️\tblack_square_for_stop\tbutton\n⏺️\tblack_circle_for_record\tbutton\n⏏️\teject\tbutton\n🎦\tcinema\n🔅\tlow_brightness\tsymbol\n🔆\thigh_brightness\tsymbol\n📶\tsignal_strength\tantenna bars\n🛜\twireless\n📳\tvibration_mode\n📴\tmobile_phone_off\n♀️\tfemale_sign\n♂️\tmale_sign\n⚧️\ttransgender_symbol\n✖️\theavy_multiplication_x\n➕\theavy_plus_sign\n➖\theavy_minus_sign\n➗\theavy_division_sign\n🟰\theavy_equals_sign\n♾️\tinfinity\n‼️\tbangbang\tdouble exclamation mark\n⁉️\tinterrobang\texclamation question mark\n❓\tquestion\tblack mark ornament\n❔\tgrey_question\twhite mark ornament\n❕\tgrey_exclamation\twhite mark ornament\n❗\texclamation heavy_exclamation_mark\tsymbol\n〰️\twavy_dash\n💱\tcurrency_exchange\n💲\theavy_dollar_sign\n⚕️\tmedical_symbol staff_of_aesculapius\n♻️\trecycle\tblack universal recycling symbol\n⚜️\tfleur_de_lis\tfleur-de-lis\n🔱\ttrident\temblem\n📛\tname_badge\n🔰\tbeginner\tjapanese symbol\n⭕\to\theavy large circle\n✅\twhite_check_mark\theavy\n☑️\tballot_box_with_check\n✔️\theavy_check_mark\n❌\tx\tcross mark\n❎\tnegative_squared_cross_mark\n➰\tcurly_loop\n➿\tloop\tdouble curly\n〽️\tpart_alternation_mark\n✳️\teight_spoked_asterisk\n✴️\teight_pointed_black_star\n❇️\tsparkle\n©️\tcopyright\tsign\n®️\tregistered\tsign\n™️\ttm\ttrade mark sign\n🫟\tsplatter\n#️⃣\thash\tkey\n*️⃣\tkeycap_star\n0️⃣\tzero\tkeycap 0\n1️⃣\tone\tkeycap 1\n2️⃣\ttwo\tkeycap 2\n3️⃣\tthree\tkeycap 3\n4️⃣\tfour\tkeycap 4\n5️⃣\tfive\tkeycap 5\n6️⃣\tsix\tkeycap 6\n7️⃣\tseven\tkeycap 7\n8️⃣\teight\tkeycap 8\n9️⃣\tnine\tkeycap 9\n🔟\tkeycap_ten\n🔠\tcapital_abcd\tinput symbol latin letters\n🔡\tabcd\tinput symbol latin small letters\n🔢\t1234\tinput symbol numbers\n🔣\tsymbols\tinput symbol\n🔤\tabc\tinput symbol latin letters\n🅰️\ta\tnegative squared latin capital letter\n🆎\tab\tnegative squared\n🅱️\tb\tnegative squared latin capital letter\n🆑\tcl\tsquared\n🆒\tcool\tsquared\n🆓\tfree\tsquared\nℹ️\tinformation_source\n🆔\tid\tsquared\nⓂ️\tm\tcircled latin capital letter\n🆕\tnew\tsquared\n🆖\tng\tsquared\n🅾️\to2\tnegative squared latin capital letter o\n🆗\tok\tsquared\n🅿️\tparking\tnegative squared latin capital letter p\n🆘\tsos\tsquared\n🆙\tup\tsquared exclamation mark\n🆚\tvs\tsquared\n🈁\tkoko\tsquared katakana\n🈂️\tsa\tsquared katakana\n🈷️\tu6708\tsquared cjk unified ideograph-6708\n🈶\tu6709\tsquared cjk unified ideograph-6709\n🈯\tu6307\tsquared cjk unified ideograph-6307\n🉐\tideograph_advantage\tcircled\n🈹\tu5272\tsquared cjk unified ideograph-5272\n🈚\tu7121\tsquared cjk unified ideograph-7121\n🈲\tu7981\tsquared cjk unified ideograph-7981\n🉑\taccept\tcircled ideograph\n🈸\tu7533\tsquared cjk unified ideograph-7533\n🈴\tu5408\tsquared cjk unified ideograph-5408\n🈳\tu7a7a\tsquared cjk unified ideograph-7a7a\n㊗️\tcongratulations\tcircled ideograph congratulation\n㊙️\tsecret\tcircled ideograph\n🈺\tu55b6\tsquared cjk unified ideograph-55b6\n🈵\tu6e80\tsquared cjk unified ideograph-6e80\n🔴\tred_circle\tlarge\n🟠\tlarge_orange_circle\n🟡\tlarge_yellow_circle\n🟢\tlarge_green_circle\n🔵\tlarge_blue_circle\n🟣\tlarge_purple_circle\n🟤\tlarge_brown_circle\n⚫\tblack_circle\tmedium\n⚪\twhite_circle\tmedium\n🟥\tlarge_red_square\n🟧\tlarge_orange_square\n🟨\tlarge_yellow_square\n🟩\tlarge_green_square\n🟦\tlarge_blue_square\n🟪\tlarge_purple_square\n🟫\tlarge_brown_square\n⬛\tblack_large_square\n⬜\twhite_large_square\n◼️\tblack_medium_square\n◻️\twhite_medium_square\n◾\tblack_medium_small_square\n◽\twhite_medium_small_square\n▪️\tblack_small_square\n▫️\twhite_small_square\n🔶\tlarge_orange_diamond\n🔷\tlarge_blue_diamond\n🔸\tsmall_orange_diamond\n🔹\tsmall_blue_diamond\n🔺\tsmall_red_triangle\tup-pointing\n🔻\tsmall_red_triangle_down\tdown-pointing\n💠\tdiamond_shape_with_a_dot_inside\n🔘\tradio_button\n🔳\twhite_square_button\n🔲\tblack_square_button\n🏁\tcheckered_flag\tchequered\n🚩\ttriangular_flag_on_post\n🎌\tcrossed_flags\n🏴\twaving_black_flag\n🏳️\twaving_white_flag\n🏳️‍🌈\trainbow-flag\n🏳️‍⚧️\ttransgender_flag\n🏴‍☠️\tpirate_flag\n🇦🇨\tflag-ac\tascension island\n🇦🇩\tflag-ad\tandorra\n🇦🇪\tflag-ae\tunited arab emirates\n🇦🇫\tflag-af\tafghanistan\n🇦🇬\tflag-ag\tantigua barbuda\n🇦🇮\tflag-ai\tanguilla\n🇦🇱\tflag-al\talbania\n🇦🇲\tflag-am\tarmenia\n🇦🇴\tflag-ao\tangola\n🇦🇶\tflag-aq\tantarctica\n🇦🇷\tflag-ar\targentina\n🇦🇸\tflag-as\tamerican samoa\n🇦🇹\tflag-at\taustria\n🇦🇺\tflag-au\taustralia\n🇦🇼\tflag-aw\taruba\n🇦🇽\tflag-ax\tland islands\n🇦🇿\tflag-az\tazerbaijan\n🇧🇦\tflag-ba\tbosnia herzegovina\n🇧🇧\tflag-bb\tbarbados\n🇧🇩\tflag-bd\tbangladesh\n🇧🇪\tflag-be\tbelgium\n🇧🇫\tflag-bf\tburkina faso\n🇧🇬\tflag-bg\tbulgaria\n🇧🇭\tflag-bh\tbahrain\n🇧🇮\tflag-bi\tburundi\n🇧🇯\tflag-bj\tbenin\n🇧🇱\tflag-bl\tst barth lemy\n🇧🇲\tflag-bm\tbermuda\n🇧🇳\tflag-bn\tbrunei\n🇧🇴\tflag-bo\tbolivia\n🇧🇶\tflag-bq\tcaribbean netherlands\n🇧🇷\tflag-br\tbrazil\n🇧🇸\tflag-bs\tbahamas\n🇧🇹\tflag-bt\tbhutan\n🇧🇻\tflag-bv\tbouvet island\n🇧🇼\tflag-bw\tbotswana\n🇧🇾\tflag-by\tbelarus\n🇧🇿\tflag-bz\tbelize\n🇨🇦\tflag-ca\tcanada\n🇨🇨\tflag-cc\tcocos keeling islands\n🇨🇩\tflag-cd\tcongo - kinshasa\n🇨🇫\tflag-cf\tcentral african republic\n🇨🇬\tflag-cg\tcongo - brazzaville\n🇨🇭\tflag-ch\tswitzerland\n🇨🇮\tflag-ci\tc te d ivoire\n🇨🇰\tflag-ck\tcook islands\n🇨🇱\tflag-cl\tchile\n🇨🇲\tflag-cm\tcameroon\n🇨🇳\tcn flag-cn\tchina\n🇨🇴\tflag-co\tcolombia\n🇨🇵\tflag-cp\tclipperton island\n🇨🇶\tflag-sark\n🇨🇷\tflag-cr\tcosta rica\n🇨🇺\tflag-cu\tcuba\n🇨🇻\tflag-cv\tcape verde\n🇨🇼\tflag-cw\tcura ao\n🇨🇽\tflag-cx\tchristmas island\n🇨🇾\tflag-cy\tcyprus\n🇨🇿\tflag-cz\tczechia\n🇩🇪\tde flag-de\tgermany\n🇩🇬\tflag-dg\tdiego garcia\n🇩🇯\tflag-dj\tdjibouti\n🇩🇰\tflag-dk\tdenmark\n🇩🇲\tflag-dm\tdominica\n🇩🇴\tflag-do\tdominican republic\n🇩🇿\tflag-dz\talgeria\n🇪🇦\tflag-ea\tceuta melilla\n🇪🇨\tflag-ec\tecuador\n🇪🇪\tflag-ee\testonia\n🇪🇬\tflag-eg\tegypt\n🇪🇭\tflag-eh\twestern sahara\n🇪🇷\tflag-er\teritrea\n🇪🇸\tes flag-es\tspain\n🇪🇹\tflag-et\tethiopia\n🇪🇺\tflag-eu\teuropean union\n🇫🇮\tflag-fi\tfinland\n🇫🇯\tflag-fj\tfiji\n🇫🇰\tflag-fk\tfalkland islands\n🇫🇲\tflag-fm\tmicronesia\n🇫🇴\tflag-fo\tfaroe islands\n🇫🇷\tfr flag-fr\tfrance\n🇬🇦\tflag-ga\tgabon\n🇬🇧\tgb uk flag-gb\tunited kingdom\n🇬🇩\tflag-gd\tgrenada\n🇬🇪\tflag-ge\tgeorgia\n🇬🇫\tflag-gf\tfrench guiana\n🇬🇬\tflag-gg\tguernsey\n🇬🇭\tflag-gh\tghana\n🇬🇮\tflag-gi\tgibraltar\n🇬🇱\tflag-gl\tgreenland\n🇬🇲\tflag-gm\tgambia\n🇬🇳\tflag-gn\tguinea\n🇬🇵\tflag-gp\tguadeloupe\n🇬🇶\tflag-gq\tequatorial guinea\n🇬🇷\tflag-gr\tgreece\n🇬🇸\tflag-gs\tsouth georgia sandwich islands\n🇬🇹\tflag-gt\tguatemala\n🇬🇺\tflag-gu\tguam\n🇬🇼\tflag-gw\tguinea-bissau\n🇬🇾\tflag-gy\tguyana\n🇭🇰\tflag-hk\thong kong sar china\n🇭🇲\tflag-hm\theard mcdonald islands\n🇭🇳\tflag-hn\thonduras\n🇭🇷\tflag-hr\tcroatia\n🇭🇹\tflag-ht\thaiti\n🇭🇺\tflag-hu\thungary\n🇮🇨\tflag-ic\tcanary islands\n🇮🇩\tflag-id\tindonesia\n🇮🇪\tflag-ie\tireland\n🇮🇱\tflag-il\tisrael\n🇮🇲\tflag-im\tisle man\n🇮🇳\tflag-in\tindia\n🇮🇴\tflag-io\tbritish indian ocean territory\n🇮🇶\tflag-iq\tiraq\n🇮🇷\tflag-ir\tiran\n🇮🇸\tflag-is\ticeland\n🇮🇹\tit flag-it\titaly\n🇯🇪\tflag-je\tjersey\n🇯🇲\tflag-jm\tjamaica\n🇯🇴\tflag-jo\tjordan\n🇯🇵\tjp flag-jp\tjapan\n🇰🇪\tflag-ke\tkenya\n🇰🇬\tflag-kg\tkyrgyzstan\n🇰🇭\tflag-kh\tcambodia\n🇰🇮\tflag-ki\tkiribati\n🇰🇲\tflag-km\tcomoros\n🇰🇳\tflag-kn\tst kitts nevis\n🇰🇵\tflag-kp\tnorth korea\n🇰🇷\tkr flag-kr\tsouth korea\n🇰🇼\tflag-kw\tkuwait\n🇰🇾\tflag-ky\tcayman islands\n🇰🇿\tflag-kz\tkazakhstan\n🇱🇦\tflag-la\tlaos\n🇱🇧\tflag-lb\tlebanon\n🇱🇨\tflag-lc\tst lucia\n🇱🇮\tflag-li\tliechtenstein\n🇱🇰\tflag-lk\tsri lanka\n🇱🇷\tflag-lr\tliberia\n🇱🇸\tflag-ls\tlesotho\n🇱🇹\tflag-lt\tlithuania\n🇱🇺\tflag-lu\tluxembourg\n🇱🇻\tflag-lv\tlatvia\n🇱🇾\tflag-ly\tlibya\n🇲🇦\tflag-ma\tmorocco\n🇲🇨\tflag-mc\tmonaco\n🇲🇩\tflag-md\tmoldova\n🇲🇪\tflag-me\tmontenegro\n🇲🇫\tflag-mf\tst martin\n🇲🇬\tflag-mg\tmadagascar\n🇲🇭\tflag-mh\tmarshall islands\n🇲🇰\tflag-mk\tnorth macedonia\n🇲🇱\tflag-ml\tmali\n🇲🇲\tflag-mm\tmyanmar burma\n🇲🇳\tflag-mn\tmongolia\n🇲🇴\tflag-mo\tmacao sar china\n🇲🇵\tflag-mp\tnorthern mariana islands\n🇲🇶\tflag-mq\tmartinique\n🇲🇷\tflag-mr\tmauritania\n🇲🇸\tflag-ms\tmontserrat\n🇲🇹\tflag-mt\tmalta\n🇲🇺\tflag-mu\tmauritius\n🇲🇻\tflag-mv\tmaldives\n🇲🇼\tflag-mw\tmalawi\n🇲🇽\tflag-mx\tmexico\n🇲🇾\tflag-my\tmalaysia\n🇲🇿\tflag-mz\tmozambique\n🇳🇦\tflag-na\tnamibia\n🇳🇨\tflag-nc\tnew caledonia\n🇳🇪\tflag-ne\tniger\n🇳🇫\tflag-nf\tnorfolk island\n🇳🇬\tflag-ng\tnigeria\n🇳🇮\tflag-ni\tnicaragua\n🇳🇱\tflag-nl\tnetherlands\n🇳🇴\tflag-no\tnorway\n🇳🇵\tflag-np\tnepal\n🇳🇷\tflag-nr\tnauru\n🇳🇺\tflag-nu\tniue\n🇳🇿\tflag-nz\tnew zealand\n🇴🇲\tflag-om\toman\n🇵🇦\tflag-pa\tpanama\n🇵🇪\tflag-pe\tperu\n🇵🇫\tflag-pf\tfrench polynesia\n🇵🇬\tflag-pg\tpapua new guinea\n🇵🇭\tflag-ph\tphilippines\n🇵🇰\tflag-pk\tpakistan\n🇵🇱\tflag-pl\tpoland\n🇵🇲\tflag-pm\tst pierre miquelon\n🇵🇳\tflag-pn\tpitcairn islands\n🇵🇷\tflag-pr\tpuerto rico\n🇵🇸\tflag-ps\tpalestinian territories\n🇵🇹\tflag-pt\tportugal\n🇵🇼\tflag-pw\tpalau\n🇵🇾\tflag-py\tparaguay\n🇶🇦\tflag-qa\tqatar\n🇷🇪\tflag-re\tr union\n🇷🇴\tflag-ro\tromania\n🇷🇸\tflag-rs\tserbia\n🇷🇺\tru flag-ru\trussia\n🇷🇼\tflag-rw\trwanda\n🇸🇦\tflag-sa\tsaudi arabia\n🇸🇧\tflag-sb\tsolomon islands\n🇸🇨\tflag-sc\tseychelles\n🇸🇩\tflag-sd\tsudan\n🇸🇪\tflag-se\tsweden\n🇸🇬\tflag-sg\tsingapore\n🇸🇭\tflag-sh\tst helena\n🇸🇮\tflag-si\tslovenia\n🇸🇯\tflag-sj\tsvalbard jan mayen\n🇸🇰\tflag-sk\tslovakia\n🇸🇱\tflag-sl\tsierra leone\n🇸🇲\tflag-sm\tsan marino\n🇸🇳\tflag-sn\tsenegal\n🇸🇴\tflag-so\tsomalia\n🇸🇷\tflag-sr\tsuriname\n🇸🇸\tflag-ss\tsouth sudan\n🇸🇹\tflag-st\ts o tom pr ncipe\n🇸🇻\tflag-sv\tel salvador\n🇸🇽\tflag-sx\tsint maarten\n🇸🇾\tflag-sy\tsyria\n🇸🇿\tflag-sz\teswatini\n🇹🇦\tflag-ta\ttristan da cunha\n🇹🇨\tflag-tc\tturks caicos islands\n🇹🇩\tflag-td\tchad\n🇹🇫\tflag-tf\tfrench southern territories\n🇹🇬\tflag-tg\ttogo\n🇹🇭\tflag-th\tthailand\n🇹🇯\tflag-tj\ttajikistan\n🇹🇰\tflag-tk\ttokelau\n🇹🇱\tflag-tl\ttimor-leste\n🇹🇲\tflag-tm\tturkmenistan\n🇹🇳\tflag-tn\ttunisia\n🇹🇴\tflag-to\ttonga\n🇹🇷\tflag-tr\tt rkiye\n🇹🇹\tflag-tt\ttrinidad tobago\n🇹🇻\tflag-tv\ttuvalu\n🇹🇼\tflag-tw\ttaiwan\n🇹🇿\tflag-tz\ttanzania\n🇺🇦\tflag-ua\tukraine\n🇺🇬\tflag-ug\tuganda\n🇺🇲\tflag-um\tu s outlying islands\n🇺🇳\tflag-un\tunited nations\n🇺🇸\tus flag-us\tunited states\n🇺🇾\tflag-uy\turuguay\n🇺🇿\tflag-uz\tuzbekistan\n🇻🇦\tflag-va\tvatican city\n🇻🇨\tflag-vc\tst vincent grenadines\n🇻🇪\tflag-ve\tvenezuela\n🇻🇬\tflag-vg\tbritish virgin islands\n🇻🇮\tflag-vi\tu s virgin islands\n🇻🇳\tflag-vn\tvietnam\n🇻🇺\tflag-vu\tvanuatu\n🇼🇫\tflag-wf\twallis futuna\n🇼🇸\tflag-ws\tsamoa\n🇽🇰\tflag-xk\tkosovo\n🇾🇪\tflag-ye\tyemen\n🇾🇹\tflag-yt\tmayotte\n🇿🇦\tflag-za\tsouth africa\n🇿🇲\tflag-zm\tzambia\n🇿🇼\tflag-zw\tzimbabwe\n🏴󠁧󠁢󠁥󠁮󠁧󠁿\tflag-england\n🏴󠁧󠁢󠁳󠁣󠁴󠁿\tflag-scotland\n🏴󠁧󠁢󠁷󠁬󠁳󠁿\tflag-wales`;\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  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  width: 280px;\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  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}\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  $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     * 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    /**\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 TruncatedText from '../typography/truncated-text.svelte';\n  import EmojiAutocomplete from './emoji-autocomplete.svelte';\n\n  /**\n   * @import { CommonEventHandlers, InputEventHandlers, TextInputProps } 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 {TextInputProps & CommonEventHandlers & InputEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    element = $bindable(),\n    role = 'textbox',\n    keyShortcuts = undefined,\n    dir = undefined,\n    name = undefined,\n    showInlineLabel = 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  const id = $props.id();\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(ariaLabel ?? restProps['aria-label']);\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  {hidden}\n>\n  <input\n    bind:this={element}\n    {...restProps}\n    {value}\n    type=\"text\"\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}\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.monospace {\n  --sui-textbox-font-family: var(--sui-font-family-monospace, monospace);\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  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  min-width: 0;\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  line-height: var(--sui-textbox-singleline-line-height);\n  font-weight: var(--sui-textbox-font-weight, var(--sui-font-weight-normal, normal));\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  letter-spacing: var(--sui-textbox-letter-spacing, normal);\n  word-spacing: var(--sui-word-spacing-normal, normal);\n  transition: all 200ms;\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: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[aria-invalid=true] {\n  border-color: var(--sui-error-border-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 & Props &\n   * 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 * 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 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 { 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 {string} [title] Title text displayed on the header. With a custom `header` snippet,\n   * it’s used as the drawer’s `aria-label` instead.\n   * @property {string} [ariaLabelledby] ID of the element that labels the drawer, typically a\n   * heading inside a custom `header` snippet. Takes precedence over `title` for the accessible\n   * name.\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 & 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 {any}\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   * Accessible name for the `<dialog>`, resolved the same way as `<Dialog>`: the built-in header\n   * renders the title in an element the dialog can point at; with a custom header the title is\n   * only text, so it becomes `aria-label` unless the consumer names the labelling element.\n   */\n  const labelledby = $derived(ariaLabelledby ?? (!header && title ? `${id}-title` : undefined));\n  const label = $derived(labelledby ? undefined : title || undefined);\n</script>\n\n<Modal\n  bind:this={modal}\n  {...restProps}\n  bind:open\n  {id}\n  class=\"drawer\"\n  aria-label={label}\n  aria-labelledby={labelledby}\n  showBackdrop\n>\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        <ModalCloseButton\n          class=\"close\"\n          controls={id}\n          {closeIcon}\n          onClose={() => {\n            modal?.close('close');\n          }}\n        />\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            <ModalCloseButton\n              class=\"close\"\n              controls={id}\n              {closeIcon}\n              onClose={() => {\n                modal?.close('close');\n              }}\n            />\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   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\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} [children] Primary slot content.\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 {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 { Snippet } from 'svelte';\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   * @property {string} [class] The `class` attribute on the wrapper element.\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    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 { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\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    ...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 `<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 TablePart from '../table/table-part.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\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 {Snippet} [children] Primary 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 {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</script>\n\n<TablePart {...restProps} role=\"row\" kind=\"grid-row\" tabindex=\"0\" aria-selected={selected} />\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 { activateGroup } from '../../services/group.svelte.js';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [selected] 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 {Snippet} [children] Primary slot content.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {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</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 { 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} [hidden] Whether to hide the widget. An alias of the `aria-hidden`\n   * attribute.\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   * @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} [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 {Snippet} [children] Primary slot content.\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 & 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    multiple = false,\n    searchTerms = '',\n    ariaLabel = undefined,\n    children,\n    onFilter,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * @type {boolean}\n   */\n  let filtered = $state(false);\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  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@media (pointer: coarse) {\n  [role=listbox] {\n    gap: 8px 0;\n  }\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 { Snippet } from 'svelte';\n   */\n\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 {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\n   * @property {string} [label] The group’s label to be displayed above the child `<Option>`s.\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    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    // svelte-ignore state_referenced_locally\n    value = label,\n    // svelte-ignore state_referenced_locally\n    searchValue = label,\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  /**\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        hidden = event.detail.hidden;\n        if (hidden) selected = false;\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 { Snippet } from 'svelte';\n   */\n\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 {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {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@media (pointer: coarse) {\n  .menu {\n    gap: 8px 0;\n  }\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        isPopupOpen = !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  {#if hasItems && buttonElement && dialogElement}\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 { Snippet } from 'svelte';\n   */\n\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.\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   * @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 {'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 {Snippet} [children] Primary slot content.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {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    onChange,\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  onChange={(/** @type {CustomEvent} */ event) => {\n    onChange?.(event);\n  }}\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 Button from '../button/button.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\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.\n   * @property {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\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 {string} [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.\n   * @property {Snippet} [children] Primary slot content.\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 {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  /**\n   * Accessible name given as a prop or as a plain `aria-label` attribute. It takes the place of the\n   * visible label, which the button otherwise points at — but only when there is one to point at.\n   * @type {string | undefined}\n   */\n  const accessibleLabel = $derived(ariaLabel ?? restProps['aria-label']);\n  const hasVisibleLabel = $derived(!!(children || label));\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`\n  $effect(() => {\n    if (typeof group === 'string') {\n      if (group === value) {\n        if (!checked) {\n          checked = true;\n        }\n      } else if (checked) {\n        checked = false;\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    aria-label={accessibleLabel || undefined}\n    aria-labelledby={!accessibleLabel && hasVisibleLabel ? `${id}-label` : undefined}\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\n      if (typeof group === 'string') {\n        group = value;\n      }\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 && typeof group === 'string') {\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 * 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 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 * 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 * 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 } from 'svelte';\n  import { getHandleKeyAction } 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  const handleIndex = ctx.registerHandle();\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  const currentPaneConstraints = $derived(ctx.getPaneConstraints(handleIndex));\n  const nextPaneConstraints = $derived(ctx.getPaneConstraints(handleIndex + 1));\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 pairSize = $derived(currentPaneSize + (sizes[handleIndex + 1] ?? 0));\n  const currentPaneMin = $derived(\n    Math.max(currentPaneConstraints.minSize, pairSize - nextPaneConstraints.maxSize),\n  );\n  const currentPaneMax = $derived(\n    Math.min(currentPaneConstraints.maxSize, pairSize - nextPaneConstraints.minSize),\n  );\n\n  /**\n   * A reference to the handle element.\n   * @type {HTMLElement | undefined}\n   */\n  let element = $state();\n  let dragging = $state(false);\n  let startScreenPos = $state(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  let targetPointerId = $state(0);\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 (attached to `document` while dragging).\n   * @param {PointerEvent} event `pointermove` event.\n   */\n  const onPointerMove = (event) => {\n    const { screenX, screenY, pointerId } = event;\n\n    if (disabled || !dragging || pointerId !== targetPointerId) return;\n\n    event.preventDefault();\n    event.stopPropagation();\n\n    const screenPos = isHorizontal ? screenX : screenY;\n    const pixelDelta = screenPos - startScreenPos;\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    let percentDelta = (pixelDelta / containerSize) * 100;\n\n    // In RTL with a horizontal layout, the visual direction is reversed\n    if (isHorizontal && isRTL()) {\n      percentDelta = -percentDelta;\n    }\n\n    ctx.resize(handleIndex, startPaneSize + percentDelta - (sizes[handleIndex] ?? 0));\n  };\n\n  /**\n   * Handle pointer up/cancel events (attached to `document` while dragging).\n   * @param {PointerEvent} event `pointerup` or `pointercancel` event.\n   */\n  const onPointerUp = (event) => {\n    const { pointerId } = event;\n\n    if (!dragging || pointerId !== targetPointerId) return;\n\n    element?.releasePointerCapture(pointerId);\n    dragging = false;\n    startScreenPos = 0;\n    targetPointerId = 0;\n\n    onResizeEnd?.();\n\n    document.removeEventListener('pointermove', onPointerMove);\n    document.removeEventListener('pointerup', onPointerUp);\n    document.removeEventListener('pointercancel', onPointerUp);\n  };\n\n  /**\n   * Handle pointer down events on the handle.\n   * @param {PointerEvent} event `pointerdown` event.\n   */\n  const onPointerDown = (event) => {\n    if (disabled) return;\n\n    event.preventDefault();\n    event.stopPropagation();\n\n    const { screenX, screenY, pointerId } = event;\n\n    dragging = true;\n    startScreenPos = isHorizontal ? screenX : screenY;\n    startPaneSize = sizes[handleIndex] ?? 0;\n    targetPointerId = pointerId;\n    containerSize = ctx.measurePaneSpace();\n    element?.setPointerCapture(pointerId);\n\n    onResizeStart?.();\n\n    document.addEventListener('pointermove', onPointerMove);\n    document.addEventListener('pointerup', onPointerUp);\n    document.addEventListener('pointercancel', onPointerUp);\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    document.removeEventListener('pointermove', onPointerMove);\n    document.removeEventListener('pointerup', onPointerUp);\n    document.removeEventListener('pointercancel', onPointerUp);\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={currentPaneMin}\n  aria-valuemax={currentPaneMax}\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    resolvePaneConstraints,\n    resolveToPercent,\n  } from './sizing.js';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { PaneGroupContext, ResizablePaneSize } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {'horizontal' | 'vertical'} [direction] Layout direction of the panes.\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {Snippet} [children] Primary slot content.\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 {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 registration order, populated synchronously by child\n   * `<ResizablePane>` components.\n   * @type {PaneDef[]}\n   */\n  const _paneDefs = $state([]);\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.\n   * @type {(number | undefined)[]}\n   */\n  const _savedSizes = $state([]);\n\n  let _handleCount = 0;\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   * 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\n    // Resolve each pane’s defaultSize to a percentage (NaN if unspecified or unresolvable)\n    const resolvedDefaults = _paneDefs.map((p) =>\n      p.defaultSize === undefined ? NaN : resolveToPercent(p.defaultSize, NaN, env),\n    );\n\n    const constraints = _paneDefs.map((p) => resolvePaneConstraints(p, env));\n\n    sizes.splice(0, sizes.length, ...getInitialSizes(resolvedDefaults, constraints));\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    onResize?.({ sizes: sizes.map((s) => Number(s.toFixed(1))) });\n  };\n\n  /**\n   * Toggle collapse of the primary pane (before the given handle). If the pane is above its minimum\n   * size it is collapsed to `minSize`; if already at `minSize` 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\n    if (_savedSizes[handleIndex] !== undefined) {\n      const delta = /** @type {number} */ (_savedSizes[handleIndex]) - sizes[handleIndex];\n\n      _savedSizes[handleIndex] = undefined;\n      resize(handleIndex, delta);\n    } else {\n      _savedSizes[handleIndex] = sizes[handleIndex];\n      resize(handleIndex, -(sizes[handleIndex] - minBefore));\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: ({ id, defaultSize, minSize, maxSize }) => {\n        const idx = _paneDefs.length;\n\n        _paneDefs.push({ id, defaultSize, minSize, maxSize });\n\n        return { index: idx };\n      },\n      registerHandle: () => {\n        const idx = _handleCount;\n\n        _handleCount += 1;\n\n        return idx;\n      },\n      resize,\n      toggleCollapse,\n      getPaneConstraints,\n      measurePaneSpace,\n      paneDefs: _paneDefs,\n    }),\n    /* eslint-enable jsdoc/require-jsdoc */\n  );\n\n  $effect(() => {\n    if (_paneDefs.length && !sizes.length) {\n      initSizes();\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, untrack } from 'svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { 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 {string} [class] The `class` attribute on the wrapper element.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {(detail: { size: number }) => void} [onResize] Called whenever this pane’s size (in\n   * percent) changes.\n   */\n\n  /**\n   * @type {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  // svelte-ignore state_referenced_locally\n  const { index: paneIndex } = ctx.registerPane({ id, defaultSize, minSize, maxSize });\n\n  const direction = $derived(ctx.direction);\n  const size = $derived(ctx.sizes[paneIndex]);\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    if (size !== undefined) {\n      return `${size}%`;\n    }\n\n    if (typeof defaultSize === 'number') {\n      return `${defaultSize}%`;\n    }\n\n    return defaultSize ?? '0%';\n  });\n\n  $effect(() => {\n    if (size !== undefined) {\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  // 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  $effect(() => {\n    void loadedItemSize;\n\n    if (!spinner) {\n      return undefined;\n    }\n\n    const observer = new IntersectionObserver(([{ isIntersecting }]) => {\n      if (isIntersecting && loading) {\n        loadedItemSize += itemChunkSize;\n      }\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","<!--\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    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}</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 { normalize } from '../../services/text.js';\n  import { createOptionRegistry, getSelectedItemDetail } from '../../services/select.svelte.js';\n  import { findTypeAheadMatch, 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 Popup from '../util/popup.svelte';\n\n  /**\n   * @import { ComboboxProps, OptionEntry, TextInputProps } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {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    ariaLabel = undefined,\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 {string} */\n  let label = $state('');\n  /** @type {boolean} */\n  let showFilter = $state(false);\n  /** @type {string} */\n  let searchTerms = $state('');\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  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   * Update the {@link label} and selected option when the {@link value} is changed. A value that\n   * matches no option, including `undefined`, clears both, so the previous option doesn’t stay\n   * selected.\n   */\n  const _onChange = () => {\n    const entry = registry.find(value);\n\n    label = entry?.label ?? '';\n    // With no matching entry, this deselects every option\n    registry.selectOnly(value);\n  };\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\n    _onChange();\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    _onChange();\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   * @param {KeyboardEvent} event The `keydown` event.\n   */\n  const onComboboxKeyDown = (event) => {\n    const { key, ctrlKey, metaKey, altKey } = event;\n\n    if (\n      disabled ||\n      readonly ||\n      isPopupOpen ||\n      key.length !== 1 ||\n      key === ' ' ||\n      ctrlKey ||\n      metaKey ||\n      altKey\n    ) {\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    const entries = registry.entries.filter((entry) => !entry.disabled);\n\n    const index = findTypeAheadMatch(\n      entries.map((entry) => normalize(entry.label ?? '')),\n      typeAhead.push(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    _onChange();\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    option.classList.add('focused');\n    listbox.setAttribute('aria-activedescendant', option.id);\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    label = entry.label;\n\n    // There is no element to report while the dropdown has never been expanded\n    dispatchEntryChange(entry);\n  });\n\n  $effect(() => {\n    void value;\n    _onChange();\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 role=\"none\" class=\"sui combobox {className}\" class:editable {hidden}>\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={ariaLabel}\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}\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 = '';\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 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","/*\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  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 } from '../../typedefs.js';\n   */\n\n  /**\n   * @type {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 Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import Option from '../listbox/option.svelte';\n  import Select from './select.svelte';\n  import { getDropIndex, getDropTarget, getKeyboardMoveTarget, moveItem } from './select-tags.js';\n\n  /**\n   * @import { Snippet } from 'svelte';\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 {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [hidden] Whether to hide the widget.\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   * @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 {Snippet} [children] Primary slot content.\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 {Props & 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    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   * @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  <!--\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      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","import { getArrowKeys } from '../../services/navigation.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 * Count the fraction digits of a number, including one written in exponential notation, such as\n * `1e-7`.\n * @param {number} num Number.\n * @returns {number} Number of fraction digits, `0` for an integer.\n */\nconst countFractionDigits = (num) => {\n  const [mantissa, exponent = '0'] = String(num).split('e');\n\n  return Math.min(Math.max((mantissa.split('.')[1] ?? '').length - Number(exponent), 0), 100);\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.\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, barWidth }) => {\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  // 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\n  const decimals = Math.max(countFractionDigits(min), countFractionDigits(step));\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 * Whether moving one thumb of a multi-thumb slider to the given position would make it cross, or\n * land on, the other thumb.\n * @param {object} options Options.\n * @param {number} options.valueIndex Index of the thumb being moved, `0` or `1`.\n * @param {number} options.targetPosition Position the thumb would move to, in pixels.\n * @param {number[]} options.sliderPositions Current position of each thumb, in pixels.\n * @returns {boolean} `true` if the move would cross the other thumb.\n */\nexport const wouldCrossThumbs = ({ valueIndex, targetPosition, sliderPositions }) =>\n  (valueIndex === 0 && sliderPositions[1] <= targetPosition) ||\n  (valueIndex === 1 && sliderPositions[0] >= targetPosition);\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 } from 'svelte';\n  import {\n    findNearestStepIndex,\n    getNearestThumbIndex,\n    getSliderCurrentIndex,\n    getSliderKeyDirection,\n    getSliderKeyTargetIndex,\n    getSliderSteps,\n    toLogicalX,\n    wouldCrossThumbs,\n  } from './slider.js';\n\n  /**\n   * @import { Snippet } from 'svelte';\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.\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 {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [hidden] Whether to hide the widget.\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   * @property {boolean} [invalid] Whether to mark the widget invalid. An alias of the\n   * `aria-invalid` attribute.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {(detail: { values?: number[], value?: number }) => void} [onChange] `change` event\n   * handler.\n   */\n\n  /**\n   * @type {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    children,\n    onChange,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const multiThumb = $derived(Array.isArray(values));\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 dragging = $state(false);\n  let targetPointerId = $state(0);\n  let targetValueIndex = $state(0);\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    const index = findNearestStepIndex(positionList, toLogicalX(physicalX, barWidth, isRTL()));\n\n    if (\n      multiThumb &&\n      wouldCrossThumbs({\n        valueIndex: targetValueIndex,\n        targetPosition: positionList[index],\n        sliderPositions,\n      })\n    ) {\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, ctrlKey, metaKey, shiftKey, altKey } = event;\n    const hasModifier = shiftKey || altKey || ctrlKey || metaKey;\n\n    if (disabled || readonly || hasModifier) {\n      return;\n    }\n\n    const _value = multiThumb ? /** @type {[number, number]} */ (values)[valueIndex] : value;\n    const rtl = isRTL();\n\n    const 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 (\n      multiThumb &&\n      wouldCrossThumbs({ valueIndex, targetPosition: positionList[index], sliderPositions })\n    ) {\n      return;\n    }\n\n    setValue(valueIndex, valueList[index]);\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    const { screenX, pointerId } = event;\n\n    if (disabled || readonly || !dragging || pointerId !== targetPointerId) {\n      return;\n    }\n\n    event.preventDefault();\n    event.stopPropagation();\n\n    const screenDiff = 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 `pointerup` and `pointercancel` events fired anywhere on the page.\n   * @param {PointerEvent} event `pointerup` or `pointercancel` event.\n   */\n  const onPointerUp = (event) => {\n    const { pointerId, target } = event;\n\n    if (disabled || readonly || !dragging || pointerId !== targetPointerId) {\n      return;\n    }\n\n    event.stopPropagation();\n\n    const slider = /** @type {HTMLElement} */ (target);\n\n    // Handle a click on the bars\n    if (slider.matches('.base-bar, .slider-bar')) {\n      const rect = /** @type {HTMLElement} */ (base).getBoundingClientRect();\n      // Get physical X position from left edge\n      const physicalX = /** @type {any} */ (event).clientX - rect.left;\n\n      moveThumb(physicalX);\n    }\n\n    // Reset everything\n    slider.releasePointerCapture(pointerId);\n    dragging = false;\n    startX = 0;\n    startScreenX = 0;\n    targetPointerId = 0;\n    targetValueIndex = 0;\n\n    document.removeEventListener('pointermove', onPointerMove);\n    document.removeEventListener('pointerup', onPointerUp);\n    document.removeEventListener('pointercancel', onPointerUp);\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    dragging = true;\n\n    const { clientX, screenX, pointerId, target } = event;\n    const slider = /** @type {HTMLElement} */ (target);\n    const rect = /** @type {HTMLElement} */ (base).getBoundingClientRect();\n\n    // Store physical X position from left edge (same in LTR and RTL)\n    startX = clientX - rect.left;\n    startScreenX = screenX;\n    targetPointerId = pointerId;\n    targetValueIndex =\n      valueIndex ??\n      (multiThumb\n        ? getNearestThumbIndex(sliderPositions, toLogicalX(startX, barWidth, isRTL()))\n        : 0);\n    slider.setPointerCapture(pointerId);\n\n    document.addEventListener('pointermove', onPointerMove);\n    document.addEventListener('pointerup', onPointerUp);\n    document.addEventListener('pointercancel', onPointerUp);\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      document.removeEventListener('pointermove', onPointerMove);\n      document.removeEventListener('pointerup', onPointerUp);\n      document.removeEventListener('pointercancel', onPointerUp);\n    };\n  });\n\n  $effect(() => {\n    void value;\n    void values;\n    updatePositions();\n  });\n</script>\n\n<svelte:body\n  onclick={() => {\n    dragging = false;\n  }}\n/>\n\n<div\n  {...restProps}\n  role=\"none\"\n  class=\"sui slider {className}\"\n  class:disabled\n  class:readonly\n  class:invalid\n  {hidden}\n>\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 .base-bar {\n  background-color: var(--sui-hover-background-color);\n}\n.slider: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 { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [label] Text label displayed next to the switch.\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [hidden] Whether to hide the widget.\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   * @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] The `aria-label` attribute on the wrapper element.\n   * @property {Snippet} [children] Primary slot content.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {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 { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\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    ...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 { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\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    ...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 { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\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] Primary slot content.\n   */\n\n  /**\n   * @type {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 { Snippet } from 'svelte';\n   */\n\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.\n   * @property {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\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 {Snippet} [children] Primary slot content.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {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 { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\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    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  /**\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   * 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      modals.push(...document.querySelectorAll(/** @type {'dialog'} */ ('dialog:modal')));\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` to hide it\n   * manually from the consumer. The countdown is held while the pointer is over the toast or the\n   * 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 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).\n   * @type {boolean}\n   */\n  let held = $state(false);\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  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      held = 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    popover.appendChild(toast);\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    if (!show || !duration || held) {\n      return undefined;\n    }\n\n    const timer = globalThis.setTimeout(() => {\n      show = false;\n    }, duration);\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    held = true;\n  }}\n  onpointerleave={() => {\n    held = false;\n  }}\n  onfocusin={() => {\n    held = true;\n  }}\n  onfocusout={(event) => {\n    held = !!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  display: flex;\n  flex-direction: column;\n  justify-content: flex-end;\n  align-items: flex-end;\n  gap: 8px;\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.toast {\n  position: absolute;\n  width: max-content;\n  max-width: 80dvw;\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.toast.top-left {\n  inset-block-start: 0;\n  inset-block-end: auto;\n  inset-inline-start: 0;\n  inset-inline-end: auto;\n}\n.toast.top-center {\n  inset-block-start: 0;\n  inset-block-end: auto;\n  inset-inline-start: 50%;\n  inset-inline-end: auto;\n}\n.toast.top-center:dir(ltr) {\n  transform: translateX(-50%);\n}\n.toast.top-center:dir(rtl) {\n  transform: translateX(50%);\n}\n.toast.top-right {\n  inset-block-start: 0;\n  inset-block-end: auto;\n  inset-inline-start: auto;\n  inset-inline-end: 0;\n}\n.toast.bottom-left {\n  inset-block-start: auto;\n  inset-block-end: 0;\n  inset-inline-start: 0;\n  inset-inline-end: auto;\n}\n.toast.bottom-center {\n  inset-block-start: auto;\n  inset-block-end: 0;\n  inset-inline-start: 50%;\n  inset-inline-end: auto;\n}\n.toast.bottom-center:dir(ltr) {\n  transform: translateX(-50%);\n}\n.toast.bottom-center:dir(rtl) {\n  transform: translateX(50%);\n}\n.toast.bottom-right {\n  inset-block-start: auto;\n  inset-block-end: 0;\n  inset-inline-start: auto;\n  inset-inline-end: 0;\n}\n.toast :global(.alert) {\n  box-shadow: 0 8px 16px 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\nconst BACKTICKS = '```';\n\n/**\n * Wrap code in a Markdown fenced code 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  code ? `${BACKTICKS}${lang}\\n${code}\\n${BACKTICKS}` : `${BACKTICKS}${lang}\\n${BACKTICKS}`;\n\n/**\n * Take a Markdown fenced code block apart.\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(/^```(?<lang>[^\\s`]+)?\\n(?:(?<code>.*)\\n)?```/s)?.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,S=1,C=2,v=4,k=8,b=16,T=32,N=64,w=128;function E(){return 2047}const O=/* @__PURE__ */E(),M=p||g||x?\"\\xa0\":\"\\u200b\",A=\"\\n\\n\",F=u?\"\\xa0\":M,D=\"\\u0591-\\u07ff\\ufb1d-\\ufdfd\\ufe70-\\ufefc\",P=\"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(P,D),z=/* @__PURE__ */I(D,P),K={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 $=/* @__PURE__ */W(R),j={normal:0,segmented:2,token:1},U=/* @__PURE__ */W(j),V=\"$\",J=Symbol.for(\"@lexical/ctrlOrOtherKey\"),H=\"$config\";function q(){return Eu()._blockCursorElement}function Y(t){return null!==t&&1===t.nodeType&&t.hasAttribute(\"data-lexical-slot\")}const G=x||g||p;function X(){const t=iu().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 Q(t){return null!==t&&1===t.nodeType&&t.hasAttribute(\"data-lexical-decorator-boundary\")}class Z{element;before;after;constructor(t,e,n){this.element=t,this.before=e||null,this.after=n||null}withBefore(t){return new Z(this.element,t,this.after)}withAfter(t){return new Z(this.element,this.before,t)}withElement(t){return this.element===t?this:new Z(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=tt(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=tt(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 tt(t,e){let n=e;for(;null!==n&&n.parentNode!==t;)n=n.parentNode;return n}class et extends Z{withBefore(t){return new et(this.element,t,this.after)}withAfter(t){return new et(this.element,this.before,t)}withElement(t){return this.element===t?this:new et(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(;Y(e);)t=e,e=e.nextSibling;Q(e)&&(t=e,e=e.nextSibling);const n=t?t.nextSibling:this.element.firstChild;return null!==n&&n===q()?n:t}getDecoratorBoundaryAnchor(t){let e;if(\"leading\"===t){const t=super.getFirstChildAnchor();for(e=t?t.nextSibling:this.element.firstChild;Y(e);)e=e.nextSibling}else e=this.before?this.before.previousSibling:this.element.lastChild,null!==e&&e===q()&&(e=e.previousSibling);return Q(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(X(),t?t.nextSibling:this.element.firstChild)}else this.element.insertBefore(X(),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&&Y(n)?null:t;if(e.__lexicalLastChildKind!==o)if(e.__lexicalLastChildKind=o,null===o)this.removeManagedLineBreak();else{const t=\"decorator\"===o&&G;this.insertManagedLineBreak(t)}}removeManagedLineBreak(){const t=this.getManagedLineBreak();if(t){const e=this.element,n=\"IMG\"===t.nodeName?t.nextSibling:null;n&&e.removeChild(n),e.removeChild(t),e.__lexicalLineBreak=void 0}}insertManagedLineBreak(t){const e=this.getManagedLineBreak();if(e){if(t===(\"IMG\"===e.nodeName))return;this.removeManagedLineBreak()}const n=this.element,o=this.before||this.getDecoratorBoundaryAnchor(\"trailing\"),r=iu().createElement(\"br\");if(r.setAttribute(\"data-lexical-managed-linebreak\",\"true\"),n.insertBefore(r,o),t){const t=iu().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=\"\",n.insertBefore(t,r),n.__lexicalLineBreak=t}else n.__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=q(),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=nt(e,n);r.push(o);const i=nt(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 nt(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()}function ot(){let t;try{t=\"0.52.0+prod.esm\"}catch{}return t??'\"<unknown>+source\"'}const rt=/* @__PURE__ */ot();class it{_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 st=null;function lt(t,e=1e3){return t instanceof ct?t.clone():t.size<e?new Map(t):(new ct).init(new Map(t),void 0,t.size)}class ct{_mutable=!1;_old=void 0;_nursery=void 0;_size=0;clone(){return this._mutable=!1,(new ct).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===st?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!==st?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!==st&&void 0!==n||(this._size++,n===st&&o.delete(t)),o.set(t,e),this}delete(t){const e=this.has(t);return e&&(this.getNursery().set(t,st),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!==st&&(void 0!==o&&(n[1]=o),yield n)}for(const n of t)n[1]===st||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 at=!1;function ut(t,n,...o){const r=at;let i;try{at=t,i=n()}finally{at=r}var s;return null===(s=i)||\"object\"!=typeof s&&\"function\"!=typeof s||\"function\"!=typeof s.then||e(421),i}function ft(){return at}function dt(t){const n=t.exportJSON(at),o=t.constructor;return n.type!==o.getType()&&e(130,o.name),yl(t)&&!Array.isArray(n.children)&&e(59,o.name),n}function ht(t,e,n,o,r,i){if(yl(t)){let s=t.getFirstChild();for(;null!==s;){const t=s.__key;s.__parent===e&&((yl(s)||wf(s)&&null!==s.__slots)&&ht(s,t,n,o,r,i),n.has(t)||i.delete(t),r.push(t)),s=s.getNextSibling()}}for(const s of wf(t)&&null!==t.__slots?t.__slots.values():[]){const t=o.get(s);void 0!==t&&Ef(t)&&t.__slotHost===e&&((yl(t)||wf(t)&&null!==t.__slots)&&ht(t,s,n,o,r,i),n.has(s)||i.delete(s),r.push(s))}}let gt=!1,_t=0;function pt(t){_t=t.timeStamp}function yt(t,e,n){const o=\"BR\"===t.nodeName,r=e.__lexicalLineBreak;return r&&(t===r||o&&t.previousSibling===r)||o&&void 0!==ta(t,n)}function mt(t,e,n){const o=Qa(Wa(n)),r=o&&cu(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&&ga(e,l,i,s,!1)}function xt(t,e,n){if(zi(t)){const e=t.anchor.getNode();if(e.is(n)&&t.format!==e.getFormat())return!1}return Rc(e)&&n.isAttached()}function St(t,e,n){for(let o=t;o&&!Uu(o);o=Fa(o)){const t=ta(o,e);if(void 0!==t){const e=Xc(t,n);if(e)return Sl(e)||!Su(o)?void 0:[o,e]}}}function Ct(t,e,n){gt=!0;const o=performance.now()-_t>100;try{al(t,()=>{const r=fs()||function(t){return t.read(\"latest\",()=>{const t=fs();return null!==t?t.clone():null})}(t),i=new Map,s=t._editorState,l=t._blockCursorElement;let c=!1,a=\"\";for(let n=0;n<e.length;n++){const f=e[n],d=f.type,h=f.target,g=St(h,t,s);if(!g)continue;const[_,p]=g;if(\"characterData\"===d)o&&ki(p)&&Rc(h)&&xt(r,h,p)&&mt(h,p,t);else if(\"childList\"===d){c=!0;const e=f.addedNodes;for(let n=0;n<e.length;n++){const o=e[n],r=Qc(o),i=o.parentNode;if(!(null==i||o===l||null!==r||yt(o,i,t)||Q(o)||t._slotsUsed&&Su(o)&&o.hasAttribute(\"data-lexical-slot\")||Uu(o))){if(u){const t=(Su(o)?o.innerText:null)||o.nodeValue;t&&(a+=t)}i.removeChild(o)}}const n=f.removedNodes,o=n.length;if(o>0){let e=0;for(let r=0;r<o;r++){const o=n[r];yt(o,h,t)||l===o?(h.appendChild(o),e++):Q(o)&&e++}o!==e&&i.set(_,p)}}}if(i.size>0)for(const[e,n]of i)n.reconcileObservedMutation(e,t);const f=n.takeRecords();if(f.length>0){for(let e=0;e<f.length;e++){const n=f[e],o=n.addedNodes,r=n.target;for(let e=0;e<o.length;e++){const n=o[e],i=n.parentNode;null==i||\"BR\"!==n.nodeName||yt(n,r,t)||i.removeChild(n)}}n.takeRecords()}null!==r&&(c&&sa(r),u&&Oa(t)&&r.insertRawText(a))})}finally{gt=!1}}function vt(t){const e=t._observer;null!==e&&Ct(t,e.takeRecords(),e)}function kt(t){!function(t){0===_t&&Wa(t).addEventListener(\"textInput\",pt,!0)}(t),t._observer=new MutationObserver((e,n)=>{Ct(t,e,n)})}function bt(t,e,n){const{isEqual:o}=t;return e===n||void 0!==o&&o(e,n)}function Tt(t,e){return bt(t,e,t.defaultValue)}function Nt(t){return\"object\"==typeof t&&null!==t}function wt(t,n){const o=Ft(t,n).getter;return Nt(o)&&void 0!==o.getterTable||e(405,n),At(o.getterTable)}function Et(t,n){const o=Ft(t,n).setter;return Nt(o)&&void 0!==o.setterTable||e(406,n),At(o.setterTable)}function Ot(t,n,o){let{meta:r}=Ft(t,n);for(let t=0;;)if(\"aliased\"===r.kind){if(t===o)return At(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 Mt(t,n){const o=Ft(t,n),{setter:r}=o;Nt(r)&&void 0!==r.setterTable||e(408,n);const i=String(o.defaultValue);return Jt(r.setterTable,i)||e(409,n,i),r.setterTable[i]}function At(t){return Object.assign(Object.create(null),t)}function Ft(t,n){const o=t.get(n);return void 0===o&&e(410,n),o}function Dt(t,e,n,o,r){void 0!==r&&Pt.add(r);const i=void 0===n,s=i?t(void 0):n;return i&&Kt(s),Object.assign(t,{accepts:r,defaultValue:s,isEqual:o,meta:e})}const Pt=new WeakSet;function It(t){const{accepts:e}=t;return void 0===e||Pt.has(e)?void 0:e}const Lt=new WeakSet;function zt(t){return null!==t&&\"object\"==typeof t&&Lt.add(t),t}function Kt(t){if(null!==t&&\"object\"==typeof t&&!Object.isFrozen(t)&&!Lt.has(t)){Object.freeze(t);for(const e of Object.values(t))Kt(e)}}function Bt(t){const{isEqual:e}=t;return void 0===e?void 0:(t,n)=>null==t||null==n?t===n:e(t,n)}function Rt(t,e){return n=>e(n)||Wt(t,n)}function Wt(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 Wt(t,e)?{parsed:t(e)}:void 0;const o=t(e);return Tt(t,o)&&e!==t.defaultValue?void 0:{parsed:o}}(t,e)}const $t=new WeakMap;function jt(t){const e=$t.get(t);if(void 0!==e)return e;const n=function(t){const e=t.meta;if(null==e)return!1;if(void 0!==It(t))return!1;switch(e.kind){case\"raw\":return!0;case\"union\":return null!=e.members&&e.members.length>0&&e.members.every(t=>jt(t));case\"nullable\":case\"optional\":case\"transform\":case\"aliased\":return null!=e.inner&&jt(e.inner);default:return!1}}(t);return $t.set(t,n),n}function Ut(t,e){const n=t.meta;if(null==n)return Wt(t,e)?1:4;const o=It(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=Ut(e.item,n[o]);r>t&&(t=r)}return t>=3?3:t}case\"object\":{const t=e.fields;if(!Ht(n))return 4;if(null==t)return 1;if(!o&&qt(n,t))return 4;let r=1;for(const e of Object.keys(n))if(Jt(t,e)){const o=Ut(t[e],n[e]);o>r&&(r=o)}return r>=3?3:r}case\"union\":return null==e.members?1:Vt(e.members,n).fit;case\"aliased\":case\"nullable\":case\"optional\":case\"transform\":return(\"aliased\"===e.kind?\"string\"==typeof n&&null!=e.aliases&&Jt(e.aliases,n):\"nullable\"===e.kind?null==n:\"optional\"===e.kind&&void 0===n)||null==e.inner?1:Ut(e.inner,n);default:return o||Wt(t,n)?1:4}}(t,n,e,r);return r&&4===i?3:i}function Vt(t,e){let n,o=4,r=4;for(let i=0;i<t.length;i++){const s=t[i],l=Ut(s,e),c=l<3&&jt(s)?3:l;if(c<o&&(n=s,o=c,r=l,1===c))break}return{fit:r,member:n}}function Jt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Ht(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 qt(t,e){for(const n of Object.keys(t))if(!Jt(e,n))return!0;return!1}function Yt(t=\"\"){return Dt(e=>\"string\"==typeof e?e:t,{kind:\"string\"},void 0,void 0,t=>\"string\"==typeof t)}const Gt=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function Xt(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&&Gt.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 Dt(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 Qt(t=!1){return Dt(e=>\"boolean\"==typeof e?e:t,{kind:\"boolean\"},void 0,void 0,t=>\"boolean\"==typeof t)}function Zt(t,...e){const n=zt(0!==e.length?e[0]:t[0]),o=new Set(t);return Dt(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 te(t,e={}){const{defaultAsNull:n}=e;return Dt(e=>{if(null==e)return null;const o=t(e);return n&&Tt(t,o)?null:o},{defaultAsNull:n,inner:t,kind:\"nullable\"},void 0,Bt(t),Rt(t,t=>null==t))}function ee(t,e={}){const{omitDefault:n}=e;return Dt(e=>{if(void 0===e)return;const o=t(e);return n&&Tt(t,o)?void 0:o},{inner:t,kind:\"optional\",omitDefault:n},void 0,Bt(t),Rt(t,t=>void 0===t))}function ne(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(!ne(t[n],e[n]))return!1;return!0}if(!Ht(t)||!Ht(e))return!1;const n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(n=>Jt(e,n)&&ne(t[n],e[n]))}function oe(t,...e){const n=0!==e.length?zt(e[0]):t[0].defaultValue;return Dt(e=>{if(void 0===e)return n;const o=(e=>{const n=function(t,e){return Vt(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,ne,e=>(void 0!==e||void 0===n)&&t.some(t=>Wt(t,e)))}function re(){return t=>function(t){return{meta:{fields:t,kind:\"node\"}}}(t)}function ie(t,e){const n=t=>\"string\"==typeof t&&Jt(e,t);return Dt(o=>n(o)?e[o]:t(o),{aliases:e,inner:t,kind:\"aliased\"},t.defaultValue,t.isEqual,e=>n(e)||Wt(t,e))}function se(t,e,n={}){return Dt(n=>e(t(n)),{inner:t,kind:\"transform\"},zt(e(t.defaultValue)),n.isEqual,e=>Wt(t,e))}function le(){return Dt(t=>void 0===t?void 0:t,{kind:\"raw\"},void 0,void 0,()=>!0)}function ce(t){return Dt(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(!bt(t,e[o],n[o]))return!1;return!0},t=>Array.isArray(t))}function ae(t){const e=function(t,e){const n=Object.entries(e);return Dt(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)=>Ht(t)&&Ht(o)&&!qt(t,e)&&!qt(o,e)&&n.every(([e,n])=>bt(n,t[e],o[e])),t=>Ht(t)&&!qt(t,e))}(0,t);return e}function ue(t,e){return de(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}})}function fe(t,e){return de(0,t,e)}function de(t,e,n){return Object.assign(t=>e(t),{accepts:e.accepts,defaultValue:e.defaultValue,getter:n.getter,isEqual:e.isEqual,meta:e.meta,setter:n.setter})}const he=\"direct\",ge=\"latest\";class _e{key;parse;unparse;isEqual;defaultValue;resetOnCopyNode;schema;constructor(t,e){this.key=t;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||Ne).bind(e),this.isEqual=e.isEqual?e.isEqual.bind(e):void 0!==n&&void 0!==n.isEqual?(t,e)=>bt(n,t,e):Object.is,this.defaultValue=void 0!==n?n.defaultValue:this.parse(void 0),this.resetOnCopyNode=e.resetOnCopyNode||!1}}function pe(t,e){return new _e(t,e)}function ye(t,e,n=ge){const o=(n===ge?t.getLatest():t).__state;return o?o.getValue(e):e.defaultValue}function me(t,e,n){const o=ye(t,n,he),r=ye(e,n,he);return n.isEqual(o,r)?null:[o,r]}function xe(t,e,n){let o;if(Ws(),\"function\"==typeof n){const r=t.getLatest(),i=ye(r,e);if(o=n(i),e.isEqual(i,o))return r}else o=n;const r=t.getWritable();return ke(r).updateFromKnown(e,o),r}function Se(t){const e=new Map,n=new Set;for(const{ownNodeConfig:o}of Sf(\"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 Ce=new Set([\"__proto__\",\"constructor\",\"prototype\"]);class ve{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.updateFromKnown(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 Te(t)&&(e[V]=t),e}getWritable(t){if(this.node===t)return this;const{sharedNodeState:e,unknownState:n}=this,o=new Map(this.knownState);return new ve(t,e,function(t,e,n){let o;if(n)for(const[r,i]of Object.entries(n)){if(Ce.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;o.has(t)||r&&n in r||(r&&(delete r[n],this.unknownState=Te(r)),this.size++),o.set(t,e)}updateFromUnknown(t,e){if(Ce.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 ke(t){const e=t.getWritable(),n=e.__state?e.__state.getWritable(e):new ve(e,function(t){return t.__state?t.__state.sharedNodeState:Ec(Eu(),t.getType()).sharedNodeState}(e));return e.__state=n,n}function be(t,e){const n=t.getWritable(),o=e[V];return(n.__state||o)&&ke(t).updateFromJSON(o),n}function Te(t){if(t)for(const e in t)return t}function Ne(t){return t}function we(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 Ee(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 Oe(t,e){const n=t.__state;return n&&n.node===t?n.getWritable(e):n}function Me(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&&we(n,t,e)||e&&we(n,e,t)||t&&Ee(n,t,e)||e&&Ee(n,e,t))}(c,a))}function Ae(t,e){const n=t.mergeWithSibling(e),o=Vs()._normalizedNodes;return o.add(t.__key),o.add(e.__key),n}function Fe(t){let e,n,o=t;if(\"\"!==o.__text||!o.isSimpleText()||o.isUnmergeable()){for(;null!==(e=o.getPreviousSibling())&&ki(e)&&e.isSimpleText()&&!e.isUnmergeable();){if(\"\"!==e.__text){if(Me(e,o)){o=Ae(e,o);break}break}e.remove()}for(;null!==(n=o.getNextSibling())&&ki(n)&&n.isSimpleText()&&!n.isUnmergeable();){if(\"\"!==n.__text){if(Me(o,n)){o=Ae(o,n);break}break}n.remove()}}else o.remove()}function De(t){return Pe(t.anchor),Pe(t.focus),t}function Pe(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),ki(o)){t.set(o.__key,r?o.getTextContentSize():0,\"text\",!0);break}if(!yl(o))break;t.set(o.__key,r?o.getChildrenSize():0,\"element\",!0)}}const Ie=Symbol.for(\"@lexical/CachedTextSize\");function Le(t,n){return Ze.read(()=>{let o=0,r=t;for(let t=0;t<n&&null!==r;t++){const i=Qe.get(r);if(void 0===i&&e(345,r),yl(i)){const s=tn.get(r);if(void 0!==s&&yl(s)&&s.__parent!==i.__parent)o+=i.getTextContentSize();else{const t=en.get(r),n=t&&t.__lexicalTextContent;\"string\"!=typeof n&&e(346,i.getType()),o+=n.length}t<n-1&&!i.isInline()&&(o+=2)}else{const t=i[Ie];void 0===t&&e(347,i.getType(),r),o+=t}r=i.__next}return o},{editor:Re})}function ze(t){yl(t)||void 0===t[Ie]&&(t[Ie]=ki(t)?t.__text.length:t.getTextContentSize())}const Ke=4;let Be,Re,We,$e=\"\",je=null,Ue=null,Ve=null;function Je(){return{firstTextKey:Ve,format:je,style:Ue}}function He(t){null!==t.firstTextKey&&(je=t.format,Ue=t.style,Ve=t.firstTextKey)}function qe(t){if(null!==Ve)return;const n=t.__lexicalFirstTextKey;if(void 0===n&&e(348),null===n)return;const o=tn.get(n);ki(o)&&(je=o.getFormat(),Ue=o.getStyle(),Ve=n)}let Ye,Ge,Xe,Qe,Ze,tn,en,nn,on,rn,sn=!1,ln=!1;function cn(t,e){const n=Qe.get(t),o=tn.has(t);if(null!==e){const n=Dn(t);n.parentNode===e&&e.removeChild(n)}if(!o){if(Re._keyToDOMMap.delete(t),yl(n)){const t=bf(n,Qe);an(t,0,t.length-1,null)}if(void 0!==n){for(const t of mn(n).values()){const e=Sn(t);cn(t,null),null!==e&&e.remove()}Ta(on,We,Ye,n,\"destroyed\")}}}function an(t,e,n,o){for(let r=e;r<=n;++r){const e=t[r];void 0!==e&&cn(e,o)}}function un(t,e){t.setProperty(\"text-align\",e)}const fn=\"40px\";function dn(t,e){const n=Be.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, ${fn}))`),ka(t,\"class\"),ka(t,\"style\")}function hn(t,e){const n=t.style;0===e?un(n,\"\"):1===e?un(n,\"left\"):2===e?un(n,\"center\"):3===e?un(n,\"right\"):4===e?un(n,\"justify\"):5===e?un(n,\"start\"):6===e&&un(n,\"end\"),ka(t,\"style\")}function gn(t,e){const n=function(t){const e=t.__dir;if(null!==e)return e;if(vl(t))return null;const n=t.getParent();return null===n||Va(n)&&null===n.__dir?\"auto\":null}(e);null!==n?t.dir=n:t.removeAttribute(\"dir\")}function _n(t){const e=iu().createElement(\"div\");return e.setAttribute(\"data-lexical-slot\",t),e.style.display=\"none\",e}function pn(t,e,n){e||\"false\"===t.contentEditable?Vu(n,Re):n.removeAttribute(\"contenteditable\")}function yn(t,e,n){const o=$e,r=Je();$e=\"\";let i=\"\";const s=Sl(t);for(const[o,r]of n){const n=_n(o);pn(e,s,n),e.appendChild(n),$e=\"\";const l=Je();vn(r,Mu(t,n,Re)),He(l),xn(t,o,e,n),i+=$e}return He(r),$e=o,i}function mn(t){return wf(t)&&null!==t.__slots?t.__slots:Nf}function xn(t,e,n,o){const r=rn.$getSlotTargetElement(t,e,n,Re);null!==r&&(o.parentElement!==r&&r.appendChild(o),o.style.display=\"\")}function Sn(t){const e=en.get(t);return void 0!==e?e.parentElement:null}function Cn(t,e,n){const o=mn(t),r=mn(e);for(const[t,e]of o)if(!r.has(t)){const t=Sn(e);cn(e,null),null!==t&&t.remove()}const i=$e,s=Je();let l=\"\",c=null;const a=Sl(e);for(const[t,i]of r){const r=o.get(t);let s=void 0!==r?Sn(r):null;$e=\"\";const u=Je();if(null===s){s=_n(t);let o=null;for(const t of n.children)if(!t.hasAttribute(\"data-lexical-slot\")){o=t;break}n.insertBefore(s,o),vn(i,Mu(e,s,Re))}else r===i?En(i,s):(void 0!==r&&cn(r,s),vn(i,Mu(e,s,Re)));if(He(u),pn(n,a,s),xn(e,t,n,s),l+=$e,s.parentElement===n){const t=null===c?n.firstChild:c.nextSibling;t!==s&&n.insertBefore(s,t),c=s}}return He(s),$e=i,l}function vn(t,n){const o=tn.get(t);if(void 0===o&&e(60),null!==n){const e=Qe.get(t);if(void 0!==e){const r=en.get(t);if(void 0!==r){const i=Ef(e)?e.__slotHost:null,s=Ef(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),En(t,n.element)}}}const r=rn.$createDOM(o,Re);if(function(t,e,n){const o=n._keyToDOMMap;Zc(e,n,t),o.set(t,e)}(t,r,Re),ki(o)?r.setAttribute(\"data-lexical-text\",\"true\"):Sl(o)&&(r.setAttribute(\"data-lexical-decorator\",\"true\"),ju(r,{captureSelection:!0})),yl(o)){const t=o.__indent,e=o.__size;gn(r,o),0!==t&&dn(r,t);const n=mn(o),i=n.size>0?yn(o,r,n):\"\";if(0===e)r.__lexicalTextContent=i,r.__lexicalFirstTextKey=null,$e+=i,n.size>0&&(r.__lexicalSlotTextLength=i.length);else{const t=$e,s=e-1;if(kn(bf(o,tn),o,0,s,Mu(o,r,Re)),\"\"!==i){const e=r.__lexicalTextContent||\"\";r.__lexicalTextContent=i+e,$e=t+i+e}n.size>0&&(r.__lexicalSlotTextLength=i.length)}const s=o.__format;0!==s&&hn(r,s),o.isInline()||(Nn(0,o,r),Tn(o,r))}else{const e=o.getTextContent();if(Sl(o)){const e=o.decorate(Re,Be);null!==e&&On(t,e),r.contentEditable=\"false\";const n=mn(o);n.size>0&&yn(o,r,n)}$e+=e}return null!==n&&n.insertChild(r),rn.$decorateDOM(o,null,r,Re),ze(o),Ta(on,We,Ye,o,\"created\"),r}function kn(t,n,o,r,i){const s=$e,l=Je();$e=\"\",je=null,Ue=null,Ve=null;let c=o;for(;c<=r;++c){const e=Je();vn(t[c],i);const n=tn.get(t[c]);null!==n&&ki(n)?null===je&&(je=n.getFormat(),Ue=n.getStyle(),Ve=n.__key):yl(n)&&c<r&&!n.isInline()&&($e+=A),He(e)}const a=Re._keyToDOMMap.get(n.__key);void 0===a&&e(349,n.__key),a.__lexicalTextContent=$e,a.__lexicalFirstTextKey=Ve,$e=s+$e,He(l)}function bn(t,e){if(!t)return!1;const n=e.get(t);return Sl(n)&&!n.isInline()}function Tn(t,e){const n=Mu(t,e,Re);n.setDecoratorBoundaryAnchor(\"leading\",bn(t.__first,tn)),n.setDecoratorBoundaryAnchor(\"trailing\",bn(t.__last,tn))}function Nn(t,e,n){const o=Mu(e,n,Re),r=function(t,e){if(t){const n=t.__last;if(n){const t=e.get(n);if(t)return Fl(t)?\"line-break\":Sl(t)&&t.isInline()?\"decorator\":null}return\"empty\"}return null}(e,tn);o.setManagedLineBreak(r)}function wn(t,e,n){const o=e.__lexicalFirstTextKey;if(null!=o){const e=t.__key;let r=o;for(;null!==r;){const t=tn.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=tn.get(o);if(ki(t))return je=t.getFormat(),void(Ue=t.getStyle())}}e.__lexicalFirstTextKey=Ve}function En(t,n){const o=Qe.get(t);let r=tn.get(t);void 0!==o&&void 0!==r||e(61);const i=sn||Xe.has(t)||Ge.has(t),s=Aa(Re,t);if(o===r&&!i){let t;if(yl(o)){const n=s.__lexicalTextContent;\"string\"!=typeof n&&e(355,o.getType()),t=n,qe(s)}else t=o.getTextContent();return $e+=t,s}if(o!==r&&i&&Ta(on,We,Ye,r,\"updated\"),rn.$updateDOM(r,o,s,Re)){const o=vn(t,null);return null===n&&e(62),n.replaceChild(o,s),cn(t,null),o}if(yl(o)){yl(r)||e(334,t);const n=r.__indent;(sn||n!==o.__indent)&&dn(s,n);const l=r.__format;(sn||l!==o.__format)&&hn(s,l);const c=i&&(mn(r).size>0||mn(o).size>0)?Cn(o,r,s):\"\";if(i){const t=$e;if(function(t,n,o){var r;je=null,Ue=null,Ve=null,function(t,n,o){const r=$e,i=t.__size,s=n.__size;$e=\"\";const l=o.element,c=Re._keyToDOMMap.get(n.__key);void 0===c&&e(351,n.__key);const a=s-i;if(!sn&&Math.abs(a)<=1&&i>=Ke&&t.__first===n.__first&&(0!==a||!Re._cloneNotNeeded.has(t.__key))){const i=c.__lexicalTextContent,u=nn.get(t.__key);if(!sn&&\"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=tn.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=Le(s,f);let o=s,a=0;for(;null!==o&&a<f;){const t=tn.get(o);if(void 0===t)break;const e=Je();En(o,l),ki(t)&&null===je&&(je=t.getFormat(),Ue=t.getStyle(),Ve=t.__key),He(e),o=t.__next,a++}let d=\"\";for(o=s,a=0;null!==o&&a<f;){const t=tn.get(o);if(void 0===t)break;let n;if(yl(t)){const r=Re._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&&yl(t)&&!t.isInline()&&(d+=A),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=_,$e=r+_,void wn(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=Qe.get(u);if(void 0===t)return!1;u=t.__prev}if(null===u)return!1;const f=tn.get(s),d=Qe.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=tn.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=Qe.get(g);g=t?t.__next:null}const p=new Set(_),y=new Set(h),m=[];let x=0,S=0;for(;x<a&&S<l;)if(h[S]===_[x])m.push({key:h[S],kind:\"reconcile\"}),x++,S++;else if(y.has(_[x])){if(p.has(h[S]))return!1;m.push({key:h[S],kind:\"create\",nextIndex:S}),S++}else m.push({key:_[x],kind:\"destroy\"}),x++;for(;x<a;)m.push({key:_[x++],kind:\"destroy\"});for(;S<l;)m.push({key:h[S],kind:\"create\",nextIndex:S}),S++;const C=Le(u,a);for(const t of m){const e=Je();if(\"reconcile\"===t.kind)En(t.key,o.element);else if(\"destroy\"===t.kind)cn(t.key,o.element);else{let e=null;for(let n=t.nextIndex+1;n<l;n++){const t=Re._keyToDOMMap.get(h[n]);if(void 0!==t){e=t;break}}vn(t.key,o.withBefore(e??o.before))}if(\"destroy\"!==t.kind){const e=tn.get(t.key);e&&ki(e)&&null===je&&(je=e.getFormat(),Ue=e.getStyle(),Ve=e.__key)}He(e)}let v=\"\";for(let t=0;t<l;t++){const n=tn.get(h[t]);if(void 0===n)return!1;let o;if(yl(n)){const r=Re._keyToDOMMap.get(h[t]),i=r&&r.__lexicalTextContent;\"string\"!=typeof i&&e(350,n.getType()),o=i}else o=n.getTextContent();v+=o,t<l-1&&yl(n)&&!n.isInline()&&(v+=A)}const k=r.__lexicalSlotTextLength||0,b=k>0?i.slice(k):i;return r.__lexicalTextContent=b.slice(0,b.length-C)+v,!0}(t,0,o,c,i,s,f,a)){const t=c.__lexicalTextContent;return\"string\"!=typeof t&&e(353),$e=r+t,void wn(n,c,u)}}}if(0===a){let n=t.__first,o=0;for(;null!==n;){const t=tn.get(n);if(void 0===t)break;const r=sn||Xe.has(n)||Ge.has(n),i=Je();if(r)En(n,l);else{let o,r;if(yl(t)){r=en.get(n);const i=r&&r.__lexicalTextContent;\"string\"!=typeof i&&e(354,t.getType()),o=i}else o=t.getTextContent();$e+=o,void 0!==r&&qe(r)}ki(t)?null===je&&(je=t.getFormat(),Ue=t.getStyle(),Ve=t.__key):yl(t)&&o<s-1&&!t.isInline()&&($e+=A),He(i),n=t.__next,o++}return c.__lexicalTextContent=$e,c.__lexicalFirstTextKey=Ve,void($e=r+$e)}}if(1===i&&1===s){const e=t.__first,r=n.__first;if(e===r)En(e,l);else{const t=Dn(e),n=vn(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}cn(e,null)}const i=tn.get(r);ki(i)&&null===je&&(je=i.getFormat(),Ue=i.getStyle(),Ve=i.__key)}else{const r=bf(t,Qe),c=bf(n,tn);if(r.length!==i&&e(227),c.length!==s&&e(228),0===i)0!==s&&kn(c,n,0,s-1,o);else if(0===s){if(0!==i){const t=null==o.after&&null==o.before&&0===mn(n).size&&null==o.element.__lexicalLineBreak;an(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=Je();if(t===o)u=Mn(En(o,i.element)),f++,d++;else{if(void 0===a&&(a=An(n,d)),void 0===c)c=An(e,f);else if(!c.has(t)){f++,He(r);continue}if(!a.has(t)){u=Mn(Dn(t)),cn(t,i.element),f++,c.delete(t),He(r);continue}if(c.has(o)){const t=Aa(Re,o);t!==u&&i.withBefore(u??i.before).insertChild(t),u=Mn(En(o,i.element)),f++,d++}else vn(o,i.withBefore(u??i.before)),d++}const s=tn.get(o);null!==s&&ki(s)?null===je&&(je=s.getFormat(),Ue=s.getStyle(),Ve=s.__key):yl(s)&&d<=l&&!s.isInline()&&($e+=A),He(r)}const h=f>s,g=d>l;if(h&&!g){const e=n[l+1],o=void 0===e?null:Re.getElementByKey(e);kn(n,t,d,l,i.withBefore(o??i.before))}else g&&!h&&an(e,f,s,i.element)}(n,r,c,i,s,o)}c.__lexicalTextContent=$e,c.__lexicalFirstTextKey=Ve,$e=r+$e}(t,n,Mu(n,o,Re)),Va(n)||(r=n,null==je||je===r.__textFormat||ln||r.setTextFormat(je),function(t){null==Ue||Ue===t.__textStyle||ln||t.setTextStyle(Ue)}(n))}(o,r,s),r.isInline()||(vl(r)||Nn(0,r,s),Tn(r,s)),\"\"!==c){const e=s.__lexicalTextContent||\"\";s.__lexicalTextContent=c+e,$e=t+c+e,s.__lexicalSlotTextLength=c.length}else(mn(r).size>0||mn(o).size>0)&&(s.__lexicalSlotTextLength=0)}else{const t=s.__lexicalTextContent;\"string\"!=typeof t&&e(356,o.getType()),$e+=t,qe(s)}if((sn||r.__dir!==o.__dir||r.__parent!==o.__parent)&&(gn(s,r),vl(r)&&!sn))for(const t of r.getChildren())yl(t)&&gn(Aa(Re,t.getKey()),t)}else{const e=r.getTextContent();if(Sl(r)){const e=r.decorate(Re,Be);null!==e&&On(t,e),i&&(mn(r).size>0||mn(o).size>0)&&Cn(o,r,s)}$e+=e}if(!ln&&vl(r)){const t=r.getLatest();if(t.__cachedText!==$e){const e=t.getWritable();e.__cachedText=$e,r=e}}return rn.$decorateDOM(r,o,s,Re),ze(r),s}function On(t,e){let n=Re._pendingDecorators;const o=Re._decorators;if(null===n){if(o[t]===e)return;n=na(Re)}n[t]=e}function Mn(t){let e=t.nextSibling;return null!==e&&e===Re._blockCursorElement&&(e=e.nextSibling),e}function An(t,e){const n=new Set;for(let o=e;o<t.length;o++)n.add(t[o]);return n}function Fn(t,e,n,o,r,i){$e=\"\",je=null,Ue=null,Ve=null,sn=2===o,Re=n,Be=n._config,rn=n._config.dom||mc,We=n._nodes,Ye=Re._listeners.mutation,Ge=r,Xe=i,Qe=t._nodeMap,Ze=t,tn=e._nodeMap,ln=e._readOnly,en=lt(n._keyToDOMMap),nn=function(){const t=new Map,e=e=>{for(const n of e){const e=tn.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(Ge.keys()),e(Xe),t}();const s=new Map;return on=s,En(\"root\",null),Re=void 0,We=void 0,Ge=void 0,Xe=void 0,Qe=void 0,Ze=void 0,tn=void 0,Be=void 0,en=void 0,nn=void 0,on=void 0,rn=mc,s}function Dn(t){const n=en.get(t);return void 0===n&&e(75,t),n}\n/*@__INLINE__*/function Pn(t){return()=>{}}function In(t){return{type:t}}const Ln=/* @__PURE__ */In(\"SELECTION_CHANGE_COMMAND\"),zn=/* @__PURE__ */In(\"SELECTION_INSERT_CLIPBOARD_NODES_COMMAND\"),Kn=/* @__PURE__ */In(\"CLICK_COMMAND\"),Bn=/* @__PURE__ */In(\"BEFORE_INPUT_COMMAND\"),Rn=/* @__PURE__ */In(\"INPUT_COMMAND\"),Wn=/* @__PURE__ */In(\"COMPOSITION_START_COMMAND\"),$n=/* @__PURE__ */In(\"COMPOSITION_END_COMMAND\"),jn=/* @__PURE__ */In(\"DELETE_CHARACTER_COMMAND\"),Un=/* @__PURE__ */In(\"INSERT_LINE_BREAK_COMMAND\"),Vn=/* @__PURE__ */In(\"INSERT_PARAGRAPH_COMMAND\"),Jn=/* @__PURE__ */In(\"CONTROLLED_TEXT_INSERTION_COMMAND\"),Hn=/* @__PURE__ */In(\"PASTE_COMMAND\"),qn=/* @__PURE__ */In(\"REMOVE_TEXT_COMMAND\"),Yn=/* @__PURE__ */In(\"DELETE_WORD_COMMAND\"),Gn=/* @__PURE__ */In(\"DELETE_LINE_COMMAND\"),Xn=/* @__PURE__ */In(\"FORMAT_TEXT_COMMAND\"),Qn=/* @__PURE__ */In(\"SET_TEXT_FORMAT_COMMAND\"),Zn=/* @__PURE__ */In(\"UNDO_COMMAND\"),to=/* @__PURE__ */In(\"REDO_COMMAND\"),eo=/* @__PURE__ */In(\"KEYDOWN_COMMAND\"),no=/* @__PURE__ */In(\"KEY_ARROW_RIGHT_COMMAND\"),oo=/* @__PURE__ */In(\"MOVE_TO_END\"),ro=/* @__PURE__ */In(\"KEY_ARROW_LEFT_COMMAND\"),io=/* @__PURE__ */In(\"MOVE_TO_START\"),so=/* @__PURE__ */In(\"KEY_ARROW_UP_COMMAND\"),lo=/* @__PURE__ */In(\"KEY_ARROW_DOWN_COMMAND\"),co=/* @__PURE__ */In(\"KEY_ENTER_COMMAND\"),ao=/* @__PURE__ */In(\"KEY_SPACE_COMMAND\"),uo=/* @__PURE__ */In(\"KEY_BACKSPACE_COMMAND\"),fo=/* @__PURE__ */In(\"KEY_ESCAPE_COMMAND\"),ho=/* @__PURE__ */In(\"KEY_DELETE_COMMAND\"),go=/* @__PURE__ */In(\"KEY_TAB_COMMAND\"),_o=/* @__PURE__ */In(\"INSERT_TAB_COMMAND\"),po=/* @__PURE__ */In(\"INDENT_CONTENT_COMMAND\"),yo=/* @__PURE__ */In(\"OUTDENT_CONTENT_COMMAND\"),mo=/* @__PURE__ */In(\"DROP_COMMAND\"),xo=/* @__PURE__ */In(\"FORMAT_ELEMENT_COMMAND\"),So=/* @__PURE__ */In(\"DRAGSTART_COMMAND\"),Co=/* @__PURE__ */In(\"DRAGOVER_COMMAND\"),vo=/* @__PURE__ */In(\"DRAGEND_COMMAND\"),ko=/* @__PURE__ */In(\"COPY_COMMAND\"),bo=/* @__PURE__ */In(\"CUT_COMMAND\"),To=/* @__PURE__ */In(\"SELECT_ALL_COMMAND\"),No=/* @__PURE__ */In(\"CLEAR_EDITOR_COMMAND\"),wo=/* @__PURE__ */In(\"CLEAR_HISTORY_COMMAND\"),Eo=/* @__PURE__ */In(\"CAN_REDO_COMMAND\"),Oo=/* @__PURE__ */In(\"CAN_UNDO_COMMAND\"),Mo=/* @__PURE__ */In(\"FOCUS_COMMAND\"),Ao=/* @__PURE__ */In(\"BLUR_COMMAND\"),Fo=/* @__PURE__ */In(\"KEY_MODIFIER_COMMAND\");function Do(t,e){return{...e,[J]:t}}const Po=/* @__PURE__ */Do(\"metaKey\",{ctrlKey:!a,metaKey:a}),Io=/* @__PURE__ */Do(\"altKey\",{altKey:a,ctrlKey:!a}),Lo=[[\"altKey\",1],[\"ctrlKey\",2],[\"metaKey\",4],[\"shiftKey\",8]];function zo(t,e,n){const o=t.get(e);o?o.push(n):t.set(e,[n])}class Ko{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 Lo){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))zo(this.byKey,`${e}:${r}`,t),1===n.length&&(/[0-9]/.test(n)?zo(this.byCode,`${e}:Digit${n}`,t):/[a-z]/.test(r)&&zo(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 Lo)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 Bo(t){const e=new Ko;for(const n of t)e.add(n);return e}function Ro(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 Wo(t,e,n,o){return t.addEventListener(e,n,o),t.removeEventListener.bind(t,e,n,o)}const $o=/* @__PURE__ */Object.freeze({});let jo;const Uo=new WeakMap,Vo=new WeakMap,Jo=/* @__PURE__ */Ro(t=>(t.addEventListener(\"selectionchange\",kr),()=>t.removeEventListener(\"selectionchange\",kr)));function Ho(t,e,n,o,r,i){const s=t.anchor,l=t.focus,c=s.getNode(),a=Vs();let u;if(void 0!==i)u=i;else{const t=Qa(Wa(a));u=null!==t?cu(t,a._rootElement):null}const f=null!==u?u.anchorNode:null,h=s.key,g=a.getElementByKey(h),_=n.length;return h!==l.key||!ki(c)||(!r&&(!d||a._inputState.lastBeforeInputInsertTextTimeStamp<o+50)||c.isDirty()&&_<2||aa(n))&&s.offset!==l.offset&&!c.isComposing()||Bc(c)||c.isDirty()&&_>1||(r||!d)&&null!==g&&!c.isComposing()&&f!==Pu(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=Kc(e);return 0===n?!e.canInsertTextBefore()||!o.canInsertTextBefore()&&!e.isComposing()||r||function(t){const e=t.getPreviousSibling();return(ki(e)||yl(e)&&e.isInline())&&!e.canInsertTextAfter()}(e):n===e.getTextContentSize()&&(!e.canInsertTextAfter()||!o.canInsertTextAfter()&&!e.isComposing()||r)}(t,c)}function qo(t,e){return Rc(t)&&null!==t.nodeValue&&0!==e&&e!==t.nodeValue.length}function Yo(t,n,o){const{anchorNode:r,anchorOffset:i,focusNode:s,focusOffset:l}=cu(t,n._rootElement),c=n._inputState;if(c.isSelectionChangeFromDOMUpdate){c.isSelectionChangeFromDOMUpdate=!1;const t=c.selectionChangeFromDOMUpdatePoints;if(c.selectionChangeFromDOMUpdatePoints=null,qo(r,i)&&qo(s,l)&&!c.postDeleteSelectionToRestore&&(null===t||t.anchorNode===r&&t.anchorOffset===i&&t.focusNode===s&&t.focusOffset===l))return}al(n,()=>{if(!o)return void sa(null);if(!Dc(n,r,s))return;let a=fs();if(c.postDeleteSelectionToRestore&&zi(a)&&a.isCollapsed()){const t=a.anchor,e=c.postDeleteSelectionToRestore.anchor;(t.key===e.key&&t.offset===e.offset+1||1===t.offset&&e.getNode().is(t.getNode().getPreviousSibling()))&&(a=c.postDeleteSelectionToRestore.clone(),sa(a))}if(c.postDeleteSelectionToRestore=null,zi(a)){const o=a.anchor,u=o.getNode();if(a.isCollapsed()){\"Range\"===t.type&&r===s&&(a.dirty=!0);const i=Wa(n).event,l=i?i.timeStamp:performance.now(),{format:f,style:d,offset:h,key:g,timeStamp:_}=c.collapsedSelectionFormat,p=ra(),y=!1===n.isComposing()&&\"\"===p.getTextContent();if(l<_+200&&o.offset===h&&o.key===g)Go(a,f,d);else if(\"text\"===o.type)ki(u)||e(141),Xo(a,u);else if(\"element\"===o.type&&!y){yl(u)||e(259);const t=o.getNode();t.isEmpty()?function(t,e){Go(t,e.getTextFormat(),e.getTextStyle())}(a,t):Go(a,a.format,\"\")}}else{const t=o.key,e=a.focus.key,n=a.getNodes(),r=n.length,s=a.isBackward(),c=s?l:i,u=s?i:l,f=s?e:t,d=s?t:e;let h=O,g=!1;for(let t=0;t<r;t++){const e=n[t],o=e.getTextContentSize();if(ki(e)&&0!==o&&!(0===t&&e.__key===f&&c===o||t===r-1&&e.__key===d&&0===u)&&(g=!0,h&=e.getFormat(),0===h))break}a.format=g?h:0}}!function(t,e,n=!1){(n||ol(t,e))&&t.dispatchCommand(Ln)}(n,a,null!==a&&(a.dirty||!zi(a)))})}function Go(t,e,n){t.format===e&&t.style===n||(t.format=e,t.style=n,t.dirty=!0)}function Xo(t,e){Go(t,e.getFormat(),e.getStyle())}function Qo(t,e){al(e,()=>{const n=fs(),o=Qa(Wa(e)),r=ds();if(o)if(zi(n)){const t=n.anchor,e=t.getNode();\"element\"===t.type&&0===t.offset&&n.isCollapsed()&&!vl(e)&&1===ra().getChildrenSize()&&e.getTopLevelElementOrThrow().isEmpty()&&null!==r&&n.is(r)&&(o.removeAllRanges(),n.dirty=!0)}else if(\"touch\"===t.pointerType||\"pen\"===t.pointerType){const n=cu(o,e._rootElement).anchorNode;(Su(n)||Rc(n))&&sa(us(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(Su(e)){const n=e.getBoundingClientRect();if(i<=(n.top+n.bottom)/2){s=t;break}}}o.setBaseAndExtent(n,s,n,s);const l=us(r,o,e,t);null!==l?sa(l):o.removeAllRanges()}}Ma(e,Kn,t)})}function Zo(t,e){const n=_u(t),o=t.pointerType;Cu(n)&&\"touch\"!==o&&\"pen\"!==o&&0===t.button&&al(e,()=>{Ju(n,e)||(e._inputState.isSelectionChangeFromMouseDown=!0)})}function tr(t){if(!t.getTargetRanges)return null;const e=t.getTargetRanges();return 0===e.length?null:e[0]}function er(t){const{lastKeyCode:e}=Vs()._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=fs();if(!zi(o)||!o.isCollapsed())return;const r=o.anchor.getNode();if(!ki(r))return;const{offset:i}=o.anchor;if(r.getTextContentSize()===i){const t=r.getNextSibling();if(\"\\n\"===n){if(g)return;if(Fl(t))t.selectEnd();else if(!t){const t=kf(r,is),e=t&&t.getNextSibling();yl(e)&&e.selectStart()}}else\"\\t\"===n?Ei(t)&&t.selectEnd():ki(t)&&t.getTextContent()[0]===n&&t.select(1,1)}else r.getTextContent()[i]===n&&r.select(i+1,i+1)}function nr(t){t.isInsertTextAfterHandledSelectionCommand=!1,null!==t.handledSelectionCommandTimeoutId&&(clearTimeout(t.handledSelectionCommandTimeoutId),t.handledSelectionCommandTimeoutId=null)}function or(t){a&&!g&&y&&(nr(t),t.isInsertTextAfterHandledSelectionCommand=!0,t.handledSelectionCommandTimeoutId=setTimeout(()=>nr(t),0))}function rr(t,e){const n=_u(t);if(Su(n)&&Ju(n,e))return!0;const o=e.getRootElement();if(null===o)return!1;const r=gu(o.ownerDocument);return null!==r&&o.contains(r)&&Ju(r,e)}function ir(t){const n=t.inputType,o=tr(t),r=Vs(),i=r._inputState,s=fs();if(\"insertText\"===n&&t.data&&i.isInsertTextAfterHandledSelectionCommand){if(nr(i),t.preventDefault(),zi(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=ds();if(!zi(t))return!0;sa(t.clone())}if(zi(s)){const n=s.anchor.key===s.focus.key;if(function(t,e){return\"MediaLast\"===t.lastKeyCode&&e<t.lastKeyDownTimeStamp+30}(i,t.timeStamp)&&r.isComposing()&&n){if(Yc(null),i.lastKeyDownTimeStamp=0,setTimeout(()=>{al(r,()=>{Yc(null)})},30),zi(s)){const t=s.anchor.getNode();t.markDirty(),ki(t)||e(142),Xo(s,t)}}else{if(Yc(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=!Sl(Ea(s.anchor,!0))),!u){Ma(r,jn,!0);const t=fs();m&&zi(t)&&t.isCollapsed()&&(i.postDeleteSelectionToRestore=t,setTimeout(()=>i.postDeleteSelectionToRestore=null))}}return!0}}if(!zi(s))return\"historyUndo\"!==n&&\"historyRedo\"!==n||(t.preventDefault(),Ma(r,\"historyUndo\"===n?Zn:to)),!0;const l=t.data;null!==i.unprocessedBeforeInputData&&ha(!1,r,i.unprocessedBeforeInputData),s.dirty&&null===i.unprocessedBeforeInputData||!s.isCollapsed()||vl(s.anchor.getNode())||null===o||s.applyDOMRange(o),i.unprocessedBeforeInputData=null;const c=s.anchor,a=s.focus,u=c.getNode(),f=a.getNode();if(\"insertText\"===n||\"insertTranspose\"===n){if(\"\\n\"===l)t.preventDefault(),Ma(r,Un,!1);else if(l===A)t.preventDefault(),Ma(r,Vn);else if(null==l&&t.dataTransfer){const e=t.dataTransfer.getData(\"text/plain\");t.preventDefault(),s.insertRawText(e)}else null!=l&&Ho(s,o,l,t.timeStamp,!0)?(t.preventDefault(),Ma(r,Jn,l),er(l)):i.unprocessedBeforeInputData=l;return i.lastBeforeInputInsertTextTimeStamp=t.timeStamp,!0}switch(t.preventDefault(),n){case\"insertFromYank\":case\"insertFromDrop\":case\"insertReplacementText\":Ma(r,Jn,t),er((t.dataTransfer?t.dataTransfer.getData(\"text/plain\"):null)??t.data);break;case\"insertFromComposition\":{const e=i.hadOrphanedCompositionEvents;i.hadOrphanedCompositionEvents=!1;const n=r._compositionKey;Yc(null),e||Ma(r,Jn,t),fr(n);break}case\"insertLineBreak\":Yc(null),i.isInsertLineBreak=!1,Ma(r,Un,!1);break;case\"insertParagraph\":Yc(null),i.isInsertLineBreak?(i.isInsertLineBreak=!1,Ma(r,Un,!1)):Ma(r,Vn);break;case\"insertFromPaste\":case\"insertFromPasteAsQuotation\":Ma(r,Hn,t);break;case\"deleteByComposition\":(function(t,e){return t!==e||yl(t)||yl(e)||!Kc(t)||!Kc(e)})(u,f)&&Ma(r,qn,t);break;case\"deleteByDrag\":za(jr),Ma(r,qn,t);break;case\"deleteByCut\":Ma(r,qn,t);break;case\"deleteContent\":Ma(r,jn,!1);break;case\"deleteWordBackward\":Ma(r,Yn,!0);break;case\"deleteWordForward\":Ma(r,Yn,!1);break;case\"deleteHardLineBackward\":case\"deleteSoftLineBackward\":Ma(r,Gn,!0);break;case\"deleteContentForward\":case\"deleteHardLineForward\":case\"deleteSoftLineForward\":Ma(r,Gn,!1);break;case\"formatStrikeThrough\":Ma(r,Xn,\"strikethrough\");break;case\"formatBold\":Ma(r,Xn,\"bold\");break;case\"formatItalic\":Ma(r,Xn,\"italic\");break;case\"formatUnderline\":Ma(r,Xn,\"underline\");break;case\"historyUndo\":Ma(r,Zn);break;case\"historyRedo\":Ma(r,to)}return!0}function sr(t,e){t.stopPropagation();const n=e._inputState;nr(n),al(e,()=>{rr(t,e)||e.dispatchCommand(Rn,t)},{event:t}),n.unprocessedBeforeInputData=null}function lr(t){const e=Vs(),n=e._inputState,o=fs(),r=t.data,i=tr(t);let s=!1;if(null!=r&&zi(o)){const l=Qa(Wa(e)),c=null!==l?cu(l,e._rootElement):null,a=\"insertCompositionText\"===t.inputType&&\"ending-firefox\"!==n.compositionPhase&&!e.isComposing();a&&(n.hadOrphanedCompositionEvents=!0);const f=o.anchor.getNode(),h=\"insertCompositionText\"===t.inputType&&\"ending-firefox\"!==n.compositionPhase&&e.isComposing()&&ki(f)&&Bc(f);if(!a&&!h&&Ho(o,i,r,t.timeStamp,!1,c)){if(s=!0,\"ending-firefox\"===n.compositionPhase){const t=dr(e,r);if(n.compositionPhase=\"idle\",t)return za(Vr),la(),!0}const i=o.anchor.getNode();if(null===l||null===c)return!0;const a=o.isBackward(),f=a?o.anchor.offset:o.focus.offset,h=a?o.focus.offset:o.anchor.offset;d&&!o.isCollapsed()&&ki(i)&&null!==c.anchorNode&&i.getTextContent().slice(0,f)+r+i.getTextContent().slice(f+h)===da(c.anchorNode)||Ma(e,Jn,r);const g=r.length;u&&g>1&&\"insertCompositionText\"===t.inputType&&!e.isComposing()&&(o.anchor.offset-=g,o._cachedNodes=null,o._cachedIsBackward=null),m&&e.isComposing()&&(n.lastKeyDownTimeStamp=0,Yc(null))}}return s||(ha(!1,e,null!==r?r:void 0),\"ending-firefox\"===n.compositionPhase&&(dr(e,r||void 0),za(Vr),n.compositionPhase=\"idle\")),la(),!0}function cr(t,e){Ma(e,Wn,t)}function ar(t){const e=Vs(),n=e._inputState,o=fs();if(zi(o)&&!e.isComposing()){n.compositionPhase=\"composing\",n.hadOrphanedCompositionEvents=!1;const r=o.anchor,i=o.anchor.getNode();if(Yc(r.key),za(Ur),t.timeStamp<n.lastKeyDownTimeStamp+30||\"element\"===r.type||!o.isCollapsed()||!m&&(i.getFormat()!==o.format||ki(i)&&i.getStyle()!==o.style)||ki(i)&&(Bc(i)||0===r.offset&&!i.canInsertTextBefore()||r.offset===i.getTextContentSize()&&!i.canInsertTextAfter())){Ma(e,Jn,F);const t=fs();zi(t)&&Yc(t.anchor.key)}}return!0}function ur(t){const e=Vs();return e._inputState.compositionPhase=\"idle\",dr(e,t.data),za(Vr),!0}function fr(t){if(null===t)return;const e=Xc(t);if(!ki(e)||\"text\"===e.getType()||Bc(e)||!e.isAttached())return;const n=fs(),o=zi(n)&&n.anchor.key===t?n.anchor.offset:null,r=vi(e.getTextContent());if(r.setFormat(e.getFormat()),r.setStyle(e.getStyle()),e.replace(r),null!==o){const t=Math.min(o,r.getTextContentSize());r.select(t,t)}}function dr(t,e){const n=t._compositionKey;if(Yc(null),null!==n&&null!=e){if(\"\"===e){const e=Xc(n),o=t.getElementByKey(n),r=null!==o&&ki(e)?Pu(e,o,t):null;if(null!==r&&null!==r.nodeValue&&ki(e)){const n=Qa(Wa(t)),o=n&&cu(n,t._rootElement);let i=null,s=null;null!==o&&o.anchorNode===r&&(i=o.anchorOffset,s=o.focusOffset),ga(e,r.nodeValue,i,s,!0)}return fr(n),!1}if(\"\\n\"===e[e.length-1]){const e=fs();if(zi(e)||Bi(e)){if(zi(e)){const t=e.focus;e.anchor.set(t.key,t.offset,t.type)}return Ma(t,co,null),fr(n),!1}}const o=Xc(n);if(null!==o&&ki(o)&&Bc(o)){o.markDirty();const t=fs(),r=o.getTextContentSize(),i=zi(t)&&t.anchor.key===n?t.anchor.offset:r;return o.select(i,i).insertText(e),!0}}return ha(!0,t,e),fr(n),!1}function hr(t,e){const n=e._inputState;u?n.compositionPhase=\"ending-firefox\":g||!p&&!x?Ma(e,$n,t):(n.compositionPhase=\"ending-safari\",n.compositionEndData=t.data)}function gr(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&&nr(n),e.isComposing()||Ma(e,eo,t)}const _r={altKey:\"any\",ctrlKey:\"any\",metaKey:\"any\",shiftKey:\"any\"},pr={ctrlKey:!0},yr={metaKey:!0},mr={shiftKey:\"any\"},xr={altKey:\"any\",shiftKey:\"any\"};function Sr(t){const e=Vs(),n=e._inputState;if(null==t.key)return!0;if(\"ending-safari\"===n.compositionPhase){const o=function(t){return\"Backspace\"===t.key}(t);if(o&&al(e,()=>{dr(e,n.compositionEndData)}),n.compositionPhase=\"idle\",n.compositionEndData=\"\",o)return!0}let o=e._keyDownShortcuts;null===o&&(o=Bo(function(){const t=(t,e,n)=>({key:t,modifiers:e,onMatch:(t,e)=>{Ma(e,n,t)}}),e=(t,e,n,o)=>({key:t,modifiers:e,onMatch:(t,e)=>{t.preventDefault(),Ma(e,n,o)}}),n=(t,e)=>({key:\"Enter\",modifiers:t,onMatch:(t,n)=>{const o=n._inputState;o.isInsertLineBreak=e&&(!g||o.isShiftKeyDown),Ma(n,co,t),t.defaultPrevented&&(o.isInsertLineBreak=!1)}}),o=(t,e)=>({key:t,modifiers:Po,onMatch:(t,n)=>{const o=n._editorState._selection;null===o||zi(o)||(t.preventDefault(),Ma(n,e,t))}});return[t(\"ArrowRight\",mr,no),t(\"ArrowLeft\",mr,ro),t(\"ArrowUp\",xr,so),t(\"ArrowDown\",xr,lo),n({..._r,shiftKey:!0},!0),n({..._r,shiftKey:!1},!1),t(\" \",_r,ao),{key:\"Backspace\",modifiers:mr,onMatch:(t,e)=>{Ma(e,uo,t)&&or(e._inputState)}},t(\"Escape\",_r,fo),t(\"Delete\",{},ho),e(\"Backspace\",Io,Yn,!0),e(\"Delete\",Io,Yn,!1),e(\"b\",Po,Xn,\"bold\"),e(\"u\",Po,Xn,\"underline\"),e(\"i\",Po,Xn,\"italic\"),t(\"Tab\",mr,go),e(\"z\",Po,Zn,void 0),e(\"z\",{...Po,shiftKey:!0},to,void 0),...a?[{key:\"o\",modifiers:pr,onMatch:(t,e)=>{t.preventDefault(),Ma(e,Un,!0)}},t(\"ArrowLeft\",{metaKey:!0,...mr},io),t(\"ArrowRight\",{metaKey:!0,...mr},oo),e(\"h\",pr,jn,!0),e(\"d\",pr,jn,!1),e(\"Backspace\",yr,Gn,!0),e(\"Delete\",yr,Gn,!1),e(\"k\",pr,Gn,!1)]:[t(\"Home\",mr,io),t(\"End\",mr,oo),e(\"y\",pr,to,void 0)],{key:\"a\",modifiers:Po,onMatch:(t,e)=>{t.preventDefault(),Ma(e,To,t)&&or(e._inputState)}},o(\"c\",ko),o(\"x\",bo)]}()),e._keyDownShortcuts=o);const r=o.match(t);return r&&r.onMatch(t,e),function(t){return t.ctrlKey||t.shiftKey||t.altKey||t.metaKey}(t)&&e.dispatchCommand(Fo,t),!0}function Cr(t){let e=t.__lexicalEventHandles;return void 0===e&&(e=[],t.__lexicalEventHandles=e),e}const vr=new Map;function kr(t){const e=Za(t.target);if(null===e)return;const n=Da(t.target);let o=null,r=null;const i=null!==n?Vo.get(n):void 0;if(null!==n){if(void 0!==i){const t=i.editors;let n=i.hasShadowEditor;if(void 0===n){n=!1;for(const e of t)if(null!==e._rootElement&&tu(e._rootElement.getRootNode())){n=!0;break}i.hasShadowEditor=n}if(n){let n=null,i=null;for(const s of t){const t=s._rootElement;if(null===t)continue;const l=cu(e,t).anchorNode;if(null!==l&&Ic(l)===s){if(tu(t.getRootNode())){o=s,r=l;break}null===n&&(n=s,i=l)}}null===o&&null!==n&&(o=n,r=i)}else{const t=e.anchorNode;null===t||Su(t)&&null!==t.shadowRoot||(o=Ic(t),null!==o&&(r=t))}}if(null===o){const t=gu(n);o=null!==t?Ic(t):null}}if(null===o)return;if(o._inputState.isSelectionChangeFromMouseDown){if(void 0!==i)for(const t of i.editors)t._inputState.isSelectionChangeFromMouseDown=!1;al(o,()=>{const n=ds(),i=r??cu(e,o._rootElement).anchorNode;(Su(i)||Rc(i))&&sa(us(n,e,o,t))})}const s=ua(o),l=s[s.length-1],c=l._key,a=vr.get(c),u=a||l;u!==o&&Yo(e,u,!1),Yo(e,o,!0),o!==l?vr.set(c,o):a&&vr.delete(c)}function br(t){t._lexicalHandled=!0}function Tr(t){return!0===t._lexicalHandled}const Nr=/* @__PURE__ */Pn();function wr(t,n,o){Ws();const r=t.__key,i=t.getParent();if(null===i)return void(null!==Of(t)&&e(367,r,String(Of(t))));const s=function(t){const e=fs();if(!zi(e)||!yl(t))return e;const{anchor:n,focus:o}=e,r=n.getNode(),i=o.getNode();return Ba(r,t)&&n.set(t.__key,0,\"element\"),Ba(i,t)&&o.set(t.__key,0,\"element\"),e}(t);let l=!1;if(zi(s)&&n){const e=s.anchor,n=s.focus;e.key===r&&(ps(e,t,i,t.getPreviousSibling(),t.getNextSibling()),l=!0),n.key===r&&(ps(n,t,i,t.getPreviousSibling(),t.getNextSibling()),l=!0)}else Bi(s)&&n&&t.isSelected()&&t.selectPrevious();if(zi(s)&&n&&!l&&hs(s,i)){const e=t.getIndexWithinParent();Jc(t),gs(s,i,e,-1)}else Jc(t);o||Va(i)||i.canBeEmpty()||!i.isEmpty()||wr(i,n),n&&s&&vl(i)&&i.isEmpty()&&i.selectEnd()}function Er(t){return t}const Or=Symbol.for(\"ephemeral\");function Mr(t){return t[Or]||!1}const Ar={configurable:!0,enumerable:!1,value:void 0,writable:!0};class Fr{__type;__key;__parent;__prev;__next;__state;static getType(){const{ownNodeType:t}=_f(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||Tf(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\",Ar),Object.defineProperty(this,Ie,Ar),Vc(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=Xc(t);if(null===e)break;t=null!==e.__parent?e.__parent:Of(e)}return!1}isSelected(t){const e=t||fs();if(null==e)return!1;const n=e.getNodes().some(t=>t.__key===this.__key);if(ki(this))return n;if(zi(e)&&\"element\"===e.anchor.type&&\"element\"===e.focus.type){if(e.isCollapsed())return!1;const t=this.getParent();if(Sl(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:Xc(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(Va(n)||null!==Of(t))return yl(t)||t===this&&Sl(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:Xc(t)}getPreviousSiblings(){const t=[],e=this.getParent();if(null===e)return t;let n=e.getFirstChild();for(;null!==n&&!n.is(this);)t.push(n),n=n.getNextSibling();return t}getNextSibling(){const t=this.getLatest().__next;return null===t?null:Xc(t)}getNextSiblings(){const t=[];let e=this.getNextSibling();for(;null!==e;)t.push(e),e=e.getNextSibling();return t}is(t){return null!=t&&this.__key===t.__key}isBefore(t){const n=Ed(this,t);return null!==n&&(\"descendant\"===n.type||(\"branch\"===n.type?-1===Td(n):(\"same\"!==n.type&&\"ancestor\"!==n.type&&e(279),!1)))}isParentOf(t){return Ba(t,this)}getNodesBetween(t){const n=this.isBefore(t),o=[],r=new Set;let i=this;for(;null!==i;){const s=i.__key;if(r.has(s)||(r.add(s),o.push(i)),i===t)break;const l=yl(i)?n?i.getFirstChild():i.getLastChild():null;if(null!==l){i=l;continue}const c=n?i.getNextSibling():i.getPreviousSibling();if(null!==c){i=c;continue}const a=i.getParentOrThrow();if(r.has(a.__key)||o.push(a),a===t)break;let u=null,f=a;do{if(null===f&&e(68),u=n?f.getNextSibling():f.getPreviousSibling(),f=f.getParent(),null===f)break;null!==u||r.has(f.__key)||o.push(f)}while(null===u);i=u}return n||o.reverse(),o}isDirty(){const t=Vs()._dirtyLeaves;return null!==t&&t.has(this.__key)}getLatest(){if(Mr(this))return this;const t=Xc(this.__key);return null===t&&e(113),t}getWritable(){if(Mr(this))return this;Ws();const t=js(),n=Vs(),o=this.__key,r=n._cloneNotNeeded,i=r.get(o),s=t._selection;if(null!==s&&s.setCachedNodes(null),void 0!==i)return qc(i),i;const l=t._nodeMap,c=l.get(o);void 0===c&&e(113);const a=Ku(c);return r.set(o,a),l.set(o,a),qc(a),a}getTextContent(){return jf(this)}getTextContentSize(){return this.getTextContent().length}createDOM(t,n){e(70)}updateDOM(t,n,o){e(71)}getDOMSlot(t){return new Z(t)}exportDOM(t){return{element:Ou(t).$createDOM(this,t)}}exportJSON(t=!1){const e=function(t,e){const n=Gu(Yu(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 yl(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=uf(t)[i.field];s=void 0===i.getterTable?e:Jt(i.getterTable,e)?i.getterTable[e]:void 0}else s=i.getter.call(t);\"ownField\"===i.kind&&void 0!==i.when&&(!ff(i,s)&&i.when.call(t)||(s=void 0)),o&&ff(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 gf(be(this,t),t)}static transform(){return null}remove(t){wr(this,!0,t)}replace(t,n){Ws();let o=fs();null!==o&&(o=o.clone()),qa(this,t);const r=this.getLatest(),i=this.__key,s=Mf(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(),d=null!==f&&zi(o)&&hs(o,f),h=d?c.getIndexWithinParent():-1;Jc(c),d&&null!==f&&zi(o)&&gs(o,f,h,-1);const g=r.getPreviousSibling(),_=r.getNextSibling(),p=r.__prev,y=r.__next,m=r.__parent;wr(r,!1,!0),null===g?a.__first=l:g.getWritable().__next=l,c.__prev=p,null===_?a.__last=l:_.getWritable().__prev=l,c.__next=y,c.__parent=m,a.__size=null!==f&&f.is(a)?u-1:u;let x=0;if(n&&(yl(this)&&yl(c)||e(139),x=c.getChildrenSize(),c.splice(x,0,this.getChildren())),zi(o)){sa(o);const t=o.anchor,e=o.focus;t.key===i&&(n&&\"element\"===t.type?t.set(c.__key,x+t.offset,\"element\"):Fi(t,c)),e.key===i&&(n&&\"element\"===e.type?e.set(c.__key,x+e.offset,\"element\"):Fi(e,c))}return Gc()===i&&Yc(l),c}insertAfter(t,e=!0){Ws(),qa(this,t);const n=this.getWritable(),o=t.getWritable();this.getParentOrThrow();const r=o.getParent(),i=fs();let s=!1,l=!1,c=-1;if(null!==r&&e&&zi(i)&&hs(i,r)){const e=r.__key,n=i.anchor,o=i.focus;c=t.getIndexWithinParent(),s=\"element\"===n.type&&n.key===e&&n.offset===c+1,l=\"element\"===o.type&&o.key===e&&o.offset===c+1}Jc(o),-1!==c&&null!==r&&zi(i)&&gs(i,r,c,-1);const a=this.getNextSibling(),u=this.getParentOrThrow().getWritable(),f=o.__key,d=n.__next;if(null===a?u.__last=f:a.getWritable().__prev=f,u.__size++,n.__next=f,o.__next=d,o.__prev=n.__key,o.__parent=n.__parent,e&&zi(i)){const t=u.__key;if(s||l||hs(i,u)){const e=this.getIndexWithinParent();gs(i,u,e+1),s&&i.anchor.set(t,e+2,\"element\"),l&&i.focus.set(t,e+2,\"element\")}}return t}insertBefore(t,e=!0){Ws(),qa(this,t);const n=this.getWritable(),o=t.getWritable();this.getParentOrThrow();const r=o.__key,i=fs(),s=o.getParent(),l=null!==s&&e&&zi(i)&&hs(i,s),c=l?o.getIndexWithinParent():-1;Jc(o),l&&null!==s&&zi(i)&&gs(i,s,c,-1);const a=this.getPreviousSibling(),u=this.getParentOrThrow().getWritable(),f=n.__prev,d=e&&zi(i)&&hs(i,u),h=d?this.getIndexWithinParent():-1;return null===a?u.__first=r:a.getWritable().__next=r,u.__size++,n.__prev=r,o.__prev=f,o.__next=n.__key,o.__parent=n.__parent,d&&zi(i)&&gs(i,u,h),t}isParentRequired(){return!1}createParentElementNode(){return oc()}selectStart(){return this.selectPrevious()}selectEnd(){return this.selectNext(0,0)}selectPrevious(t,e){Ws();const n=Mf(this);if(null!==n)return n.selectPrevious(t,e);const o=this.getPreviousSibling(),r=this.getParentOrThrow();if(null===o)return r.select(0,0);if(yl(o))return o.select();if(!ki(o)){const t=o.getIndexWithinParent()+1;return r.select(t,t)}return o.select(t,e)}selectNext(t,e){Ws();const n=Mf(this);if(null!==n)return n.selectNext(t,e);const o=this.getNextSibling(),r=this.getParentOrThrow();if(null===o)return r.select();if(yl(o))return o.select(0,0);if(!ki(o)){const t=o.getIndexWithinParent();return r.select(t,t)}return o.select(t,e)}markDirty(){this.getWritable()}reconcileObservedMutation(t,e){this.markDirty()}}function Dr(t){return t instanceof Fr}const Pr=\"historic\",Ir=\"history-push\",Lr=\"history-merge\",zr=\"paste\",Kr=\"cut\",Br=\"collaboration\",Rr=\"skip-collab\",Wr=\"skip-scroll-into-view\",$r=\"skip-dom-selection\",jr=\"skip-selection-focus\",Ur=\"composition-start\",Vr=\"composition-end\",Jr=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function Hr(t,e){if(\"number\"==typeof t)return Number.isFinite(t)?t:e;if(\"string\"!=typeof t||!Jr.test(t))return e;const n=Number(t);return Number.isFinite(n)?n:e}function qr(t,e,n,o,r){const i=Hr(t,e);return i>=n&&i<=o&&Number.isInteger(i)?i:e}const Yr=t=>{const e=wt(t,\"format\"),n=Et(t,\"format\"),o=Mt(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=qr(e.indent,0,0,Infinity),t.__textFormat=Hr(e.textFormat,0);const s=e.textStyle;return t.__textStyle=\"string\"==typeof s?s:\"\",t}}};function Gr(t,e){t.__detail=e.__detail,t.__format=e.__format,t.__mode=e.__mode,t.__style=e.__style,t.__text=e.__text}const Xr=t=>{const e=wt(t,\"mode\"),n=Ot(t,\"detail\",0),o=Ot(t,\"format\",0),r=Et(t,\"mode\"),i=Mt(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]:Hr(s,0);const l=e.format;t.__format=\"string\"==typeof l&&l in o?o[l]:Hr(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:Gr}},Qr=t=>{const e=wt(t,\"format\"),n=Et(t,\"format\"),o=Mt(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=qr(e.indent,0,0,Infinity),t.__textFormat=Hr(e.textFormat,0);const s=e.textStyle;return t.__textStyle=\"string\"==typeof s?s:\"\",t}}},Zr=()=>({exportJSON:function(t){return{type:t.__type,version:1}},exportCompactJSON:function(t){return{type:t.__type}}}),ti=t=>{const e=wt(t,\"mode\"),n=Ot(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]:Hr(o,0);const r=e.style;return t.__style=\"string\"==typeof r?r:\"\",t}}};function ei(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 ni(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 oi(t,e){for(const n in e){const o=e[n];null==o?t.removeProperty(n):ni(t,n,o)}}function ri(t,e,n=\"\"){if(e===n)return;const o=ei(n),r=ei(e);for(const e in r)delete o[e],ni(t,e,r[e]);for(const e in o)t.removeProperty(e)}const ii=/* @__PURE__ */re()({detail:/* @__PURE__ */ue(/* @__PURE__ */ie(/* @__PURE__ */Xt(),B),{field:\"__detail\"}),format:/* @__PURE__ */ue(/* @__PURE__ */ie(/* @__PURE__ */Xt(),K),{field:\"__format\"}),mode:/* @__PURE__ */ue(/* @__PURE__ */Zt([\"normal\",\"token\",\"segmented\"]),{field:\"__mode\",getterTable:U,setterTable:j}),style:/* @__PURE__ */ue(/* @__PURE__ */Yt(),{field:\"__style\"}),text:/* @__PURE__ */ue(/* @__PURE__ */Yt(),{field:\"__text\",getter:\"getTextContent\",setter:\"setTextContent\"})});function si(t,e){return 16&e?\"code\":128&e?\"mark\":32&e?\"sub\":64&e?\"sup\":null}function li(t,e){return 1&e?\"strong\":2&e?\"em\":\"span\"}function ci(t,e,n,o,r){const i=o.classList;let s=ba(r,\"base\");void 0!==s&&i.add(...s),s=ba(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 K){const o=K[t];if(s=ba(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)}ka(o,\"class\")}function ai(t,e,n){const o=n.isComposing(),r=t+(o?M:\"\"),i=Eu(),s=Ou(i).$getDOMSlot(n,e,i),l=s.getFirstChild();if(null===l||l.nodeType!==Node.TEXT_NODE)return void s.insertChild(iu().createTextNode(r));const c=l,a=c.nodeValue;if(a!==r)if(o||u){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);0!==e&&c.deleteData(t,e),c.insertData(t,n)}else c.nodeValue=r}function ui(t,e,n,o,r,i){ai(r,t,e);const s=i.theme.text;void 0!==s&&ci(0,0,o,t,s)}function fi(t,e){const n=iu().createElement(e);return n.appendChild(t),n}function di(t){return null!=t&&!0===t.__isInlineFormattable}class hi extends Fr{__text;__format;__style;__mode;__detail;get __isInlineFormattable(){return!0}$config(){return this.config(\"text\",{extends:Fr,generated:Xr,importDOM:{\"#text\":()=>({conversion:mi,priority:0}),b:()=>({conversion:_i,priority:0}),code:()=>({conversion:Ci,priority:0}),em:()=>({conversion:Ci,priority:0}),i:()=>({conversion:Ci,priority:0}),mark:()=>({conversion:Ci,priority:0}),s:()=>({conversion:Ci,priority:0}),span:()=>({conversion:gi,priority:0}),strong:()=>({conversion:Ci,priority:0}),sub:()=>({conversion:Ci,priority:0}),sup:()=>({conversion:Ci,priority:0}),u:()=>({conversion:Ci,priority:0})},json:ii})}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===Gc()}isSegmented(){return 2===this.getLatest().__mode}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(t){const e=K[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 jc(this.getLatest().__format,t,e)}canHaveFormat(){return!0}isInline(){return!0}createDOM(t,e){const n=this.__format,o=si(0,n),r=li(0,n),i=null===o?r:o,s=iu().createElement(i);let l=s;this.hasFormat(\"code\")&&s.setAttribute(\"spellcheck\",\"false\"),null!==o&&(l=iu().createElement(r),s.appendChild(l)),ui(l,this,0,n,this.__text,t);const c=this.__style;return\"\"!==c&&ri(s.style,c),s}updateDOM(t,n,o){const r=this.__text,i=t.__format,s=this.__format,l=si(0,i),c=si(0,s),a=li(0,i),u=li(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=iu().createElement(u);return ui(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)),ai(r,f,this);const d=o.theme.text;void 0!==d&&i!==s&&ci(0,i,s,f,d);const h=t.__style,g=this.__style;return h!==g&&(ri(n.style,g,h),ka(n,\"style\")),!1}exportDOM(t){let{element:n}=super.exportDOM(t);return Su(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=fi(n,\"b\")),this.hasFormat(\"italic\")&&(n=fi(n,\"i\")),this.hasFormat(\"strikethrough\")&&(n=fi(n,\"s\")),this.hasFormat(\"underline\")&&(n=fi(n,\"u\")),{element:n}}selectionTransform(t,e){}setFormat(t){const e=this.getWritable();return e.__format=\"string\"==typeof t?K[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=jc(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=j[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){Ws();let n=t,o=e;const r=fs(),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(!zi(r))return ss(s,n,s,o,\"text\",\"text\");{const t=Gc();t!==r.anchor.key&&t!==r.focus.key||Yc(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=fs();if(o&&zi(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){Ws();const e=this.getLatest(),n=e.getTextContent();if(\"\"===n)return[];const o=e.__key,r=Gc(),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=fs();if(zi(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=vi(a),f.__format=d,f.__style=h,f.__detail=g,f.__state=Oe(e,f),_=!0):f=e.setTextContent(a);const x=[f];for(let t=1;t<c;t++){const n=vi(s[t]);n.__format=d,n.__style=h,n.__detail=g,n.__state=Oe(e,n);const i=n.__key;r===o&&Yc(i),x.push(n)}const S=p?p.offset:null,C=y?y.offset:null;let v=0;for(const t of x){if(!p&&!y)break;const e=v+t.getTextContentSize();if(null!==p&&null!==S&&S<=e&&S>=v&&(p.set(t.getKey(),S-v,\"text\"),S<e&&(p=null)),null!==y&&null!==C&&C<=e&&C>=v){y.set(t.getKey(),C-v,\"text\");break}v=e}if(null!==u){!function(t){const e=t.getPreviousSibling(),n=t.getNextSibling();null!==e&&qc(e),null!==n&&qc(n)}(this);const t=u.getWritable(),e=this.getIndexWithinParent();_?(t.splice(e,0,x),this.remove()):t.splice(e,1,x),zi(m)&&gs(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;Gc()===r&&Yc(o);const l=fs();if(zi(l)){const e=l.anchor,i=l.focus;null!==e&&e.key===r&&ys(e,n,o,t,s),null!==i&&i.key===r&&ys(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 gi(t){return{forChild:bi(t.style),node:null}}function _i(t){const e=t,n=\"normal\"===e.style.fontWeight;return{forChild:bi(e.style,n?void 0:\"bold\"),node:null}}const pi=new WeakMap;function yi(t){if(!Su(t))return!1;if(\"PRE\"===t.nodeName)return!0;const e=t.style.whiteSpace;return\"string\"==typeof e&&e.startsWith(\"pre\")}function mi(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=pi.get(n))&&!yi(n);)o.push(n),n=n.parentNode;const r=void 0===e?n:e;for(let t=0;t<o.length;t++)pi.set(o[t],r);return r}(n))return{node:ks(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=xi(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=xi(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:vi(o)}}function xi(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,Su(n)){const t=n.style.display;if(\"\"===t&&!bu(n)||\"\"!==t&&!t.startsWith(\"inline\"))return null}let o=n;for(;null!==(o=e?n.firstChild:n.lastChild);)n=o;if(Rc(n))return n;if(\"BR\"===n.nodeName)return null}}const Si={code:\"code\",em:\"italic\",i:\"italic\",mark:\"highlight\",s:\"strikethrough\",strong:\"bold\",sub:\"subscript\",sup:\"superscript\",u:\"underline\"};function Ci(t){const e=Si[t.nodeName.toLowerCase()];return void 0===e?{node:null}:{forChild:bi(t.style,e),node:null}}function vi(t=\"\"){return Ha(new hi(t))}function ki(t){return t instanceof hi}function bi(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=>ki(t)||di(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}const Ti=/* @__PURE__ */re()({detail:/* @__PURE__ */fe(/* @__PURE__ */Xt(2),{getter:{field:\"__detail\"},setter:null}),mode:/* @__PURE__ */fe(/* @__PURE__ */Zt([\"normal\"]),{getter:{field:\"__mode\",getterTable:{0:\"normal\"}},setter:null}),text:/* @__PURE__ */fe(/* @__PURE__ */Yt(\"\\t\"),{getter:{field:\"__text\",method:\"getTextContent\"},setter:null})});class Ni extends hi{$config(){return this.config(\"tab\",{extends:hi,generated:ti,json:Ti})}constructor(t=void 0){super(\"\\t\",t),this.__detail=2}createDOM(t){const e=super.createDOM(t),n=ba(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 wi(){return Ha(new Ni)}function Ei(t){return t instanceof Ni}class Oi{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:bd(Vl(Ll(this,\"next\")),Vl(Ll(t,\"next\")))<0}getNode(){const t=Xc(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,Rs()||(Gc()===i&&Yc(t),null!==r&&(r.setCachedNodes(null),zi(r)&&(r._cachedIsBackward=null),r.dirty=!0)))}}function Mi(t,e,n){return new Oi(t,e,n)}function Ai(t,e){let n=e.__key,o=t.offset,r=\"element\";if(ki(e)){r=\"text\";const t=e.getTextContentSize();o>t&&(o=t)}else if(!yl(e)){const t=e.getNextSibling();if(ki(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 Fi(t,e){if(yl(e)){const n=e.getLastDescendant();yl(n)||ki(n)?Ai(t,n):Ai(t,e)}else Ai(t,e)}function Di(t,e,n,o){const r=t.getNode(),i=r.getChildAtIndex(t.offset),s=vi();if(s.setFormat(n),s.setStyle(o),rc(i))i.splice(0,0,[s]);else if(null!==i){const t=Va(r)?oc().append(s):s;i.insertBefore(t)}else if(Va(r)){const t=r.getLastChild();yl(t)&&!t.isInline()&&t.isEmpty()?t.append(s):r.append(oc().append(s))}else r.append(s);t.is(e)&&e.set(s.__key,0,\"text\"),t.set(s.__key,0,\"text\")}function Pi(t,n,o,r){const i=t.anchor.getNode();ki(i)||e(398);const s=t.anchor.offset,l=vi(n);l.setFormat(o),l.setStyle(r);const c=i.getParentOrThrow();if(0===s)c.isInline()&&!i.__prev?c.insertBefore(l):i.insertBefore(l,!1);else if(s===i.getTextContentSize())c.isInline()&&!i.__next?c.insertAfter(l):i.insertAfter(l,!1);else{const[t]=i.splitText(s);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 Ii{_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(!Bi(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 Ii(new Set(this._nodes))}extract(){return this.getNodes()}insertRawText(t){}insertText(){}insertNodes(t){const e=this.getNodes().filter(t=>null===Of(t)),n=e.length;if(0===n)return;const o=e[n-1];let r;if(ki(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=Xc(t);null!==e&&n.push(e)}return Rs()||(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===Of(t));if((fs()||ds())===this&&t[0]){const e=ad(t[0],\"next\");Kl(vd(e,e))}for(const e of t)e.remove();Li()}}function Li(){const t=ra();if(0===t.getChildrenSize()&&null===Df(fs())){const e=oc();t.append(e),e.select()}}function zi(t){return t instanceof Ki}class Ki{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!!zi(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,i=new Set;for(const n of t)if(id(n)){const{origin:t}=n;0===e.length?r.add(t):(i.add(t),e.push(t))}else{const{origin:t}=n;yl(t)&&i.has(t)||e.push(t)}if(o&&e.push(o.caret.origin),rd(t.focus)&&yl(t.focus.origin)&&null===t.focus.getNodeAtCaret())for(let n=hd(t.focus.origin,\"previous\");id(n)&&r.has(n.origin)&&!n.origin.isEmpty()&&n.origin.is(e[e.length-1]);n=_d(n))r.delete(n.origin),e.pop();for(;e.length>1;){const t=e[e.length-1];if(!yl(t)||i.has(t)||t.isEmpty()||r.has(t))break;e.pop()}if(0===e.length&&t.isCollapsed()){const n=Vl(t.anchor),o=Vl(t.anchor.getFlipped()),r=t=>nd(t)?t.origin:t.getNodeAtCaret(),i=r(n)||r(o)||(t.anchor.getNodeAtCaret()?n.origin:o.origin);e.push(i)}return e}(Hl(Rl(this),\"next\"));return Rs()||(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(){const t=this.getNodes();if(0===t.length)return\"\";const e=t[0],n=t[t.length-1],o=this.anchor,r=this.focus,i=o.isBefore(r),[s,l]=Ui(this);let c=\"\",a=!0;for(let u=0;u<t.length;u++){const f=t[u];if(yl(f)&&!f.isInline()){a||(c+=\"\\n\");let t=\"\";for(const e of If(f)){const n=Lf(f,e);null!==n&&(t+=n.getTextContent())}\"\"!==t?(c+=t,a=!1):a=!f.isEmpty()}else if(a=!1,ki(f)){let t=f.getTextContent();f===e?f===n?\"element\"===o.type&&\"element\"===r.type&&r.offset!==o.offset||(t=s<l?t.slice(s,l):t.slice(l,s)):t=i?t.slice(s):t.slice(l):f===n&&(t=i?t.slice(0,l):t.slice(0,s)),c+=t}else!Sl(f)&&!Fl(f)||f===n&&this.isCollapsed()||(c+=f.getTextContent())}return c}applyDOMRange(t){const e=Vs(),n=e.getEditorState()._selection,o=rs(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),De(this)}clone(){const t=this.anchor,e=this.focus;return new Ki(Mi(t.key,t.offset,t.type),Mi(e.key,e.offset,e.type),this.format,this.style)}toggleFormat(t){this.format=jc(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=K[t];return 0!==(this.format&e)}insertRawText(t){this.insertNodes(ks(t))}insertText(t){let n=this.format,o=this.style;if(!this.isCollapsed()){const e=(this.focus.isBefore(this.anchor)?this.focus:this.anchor).getNode();if(ki(e)&&(n=e.getFormat(),o=e.getStyle()),this.removeText(),this.format=n,this.style=o,\"\"===t)return;if(null===Gc())return\"element\"===this.anchor.type&&Di(this.anchor,this.focus,n,o),void Pi(this,t,n,o)}\"element\"===this.anchor.type&&Di(this.anchor,this.focus,n,o);const r=this.anchor.getNode();ki(r)||e(398);const i=this.anchor.offset,s=r.getParentOrThrow(),l=r.getTextContentSize();if(Bc(r)||0===i&&(!r.canInsertTextBefore()||!s.canInsertTextBefore()&&!r.__prev)||i===l&&(!r.canInsertTextAfter()||!s.canInsertTextAfter()&&!r.__next)){if(r.isSegmented()&&0!==i&&i!==l){if(null!==Gc())r.setMode(\"normal\").setFormat(n).setStyle(o);else{const t=vi(r.getTextContent());t.setFormat(n),t.setStyle(o);const e=fs()===this;r.replace(t),this.setTextNodeRange(t,i,t,i),e&&fs()!==this&&sa(this)}return void(\"\"!==t&&this.insertText(t))}if(\"\"===t)return;if(0===i){const e=r.getPreviousSibling();if(ki(e)&&e.canInsertTextAfter()&&!Bc(e))e.select();else{const t=vi();t.setFormat(n),t.setStyle(o),s.canInsertTextBefore()?r.insertBefore(t):s.insertBefore(t),t.select()}return void this.insertText(t)}if(i===l){const e=r.getNextSibling();if(ki(e)&&e.canInsertTextBefore()&&!Bc(e))e.select(0,0);else{const t=vi();t.setFormat(n),t.setStyle(o),s.canInsertTextAfter()?r.insertAfter(t):s.insertAfter(t),t.select(0,0)}return void this.insertText(t)}const e=vi(t);return e.setFormat(n),e.setStyle(o),r.replace(e),void e.select()}if(\"\"===t)return;const c=s.isInline()&&0===i&&!r.__prev,a=s.isInline()&&i===l&&!r.__next,u=r.getFormat()!==n||r.getStyle()!==o;if(c||a||u){if(\"\"!==r.getTextContent()||c||a)return void Pi(this,t,n,o);r.setFormat(n),r.setStyle(o)}r.spliceText(i,0,t,!0),r.isComposing()&&\"text\"===this.anchor.type&&this.anchor.set(this.anchor.key,this.anchor.offset-t.length,this.anchor.type)}removeText(){const t=fs()===this,e=this.anchor.key;Bl(this,Ul(Rl(this))),this.isCollapsed()&&function(t,e){const n=t.anchor;if(n.key===e)return;const o=n.getNode();let r=0,i=\"\";ki(o)?(r=o.getFormat(),i=o.getStyle()):yl(o)&&(r=o.getTextFormat(),i=o.getTextStyle()),t.format===r&&t.style===i||(t.format=r,t.style=i,t.dirty=!0)}(this,e),t&&fs()!==this&&sa(this)}formatText(t,e=null){$i(this,t,e)}insertNodes(t){if(0===t.length)return;this.isCollapsed()||this.removeText();const n=this.anchor.getNode();if(\"element\"===this.anchor.type&&yl(n)&&n.isShadowRoot()&&null!==Of(n)){let o=n.getFirstChild()??n.append(oc()).getFirstChild();if(null!==o&&!yl(o)){const t=oc();o.insertBefore(t),o=t}if(null!==o){o.selectStart();const n=fs();return zi(n)||e(369),n.insertNodes(t)}}if(\"element\"===this.anchor.type&&Va(n)){const e=Os(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=kf(r,wu);const s=t[t.length-1];if(yl(i)&&\"__language\"in i){if(\"__language\"in t[0])this.insertText(t[0].getTextContent());else{const[,e]=Ns(this);i.splice(e,0,t),s.selectEnd()}return}if(!t.some(t=>(yl(t)||Sl(t))&&!t.isInline())){yl(i)||e(211,r.constructor.name,r.getType());const[n,o]=Ns(this,!0);return(yl(n)?n:i).splice(o,0,t),void s.selectEnd()}if(yl(i)&&null!==Of(i)){const[,e]=Ns(this),n=Ts(t);i.splice(e,0,n);const o=n[n.length-1];return void(void 0!==o?o.selectEnd():i.select(e,e))}if(null===i){const e=Os(t),n=e.getLastDescendant();let o=Ll(this.anchor,\"next\");for(const t of e.getChildren())o=Zl(t,o);return void(null!==n&&n.selectEnd())}if(yl(i)&&!i.isParentRequired()&&!Va(i.getParentOrThrow())){const[,e]=Ns(this),n=Ts(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=Os(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&&yl(e)?e.getChildAtIndex(t.offset-1):null;for(let t=e;null!==t&&!wu(t)&&!Va(t);t=t.getParent()){const e=t.getPreviousSibling();if(null!==e)return e}return null}(t);return Fl(e)&&Fl(e.getPreviousSibling())}(o),f=yl(i)&&i.isEmpty()?null:this.insertParagraph();f&&!i.isAttached()&&(r=this.anchor.getNode(),i=kf(r,wu));const d=a[a.length-1];let h=a[0];var g;g=h,u||!yl(g)||!wu(g)||g.isEmpty()||!yl(i)||i.isEmpty()&&!i.canMergeWhenEmpty()||(yl(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 _=kf(c,wu),p=c.selectEnd();f&&(yl(_)&&(f.canMergeWhenEmpty()||wu(d))?(_.append(...f.getChildren()),f.remove()):f.isEmpty()&&f.remove()),yl(i)&&i.isEmpty()&&i.remove();const y=yl(i)?i.getLastChild():null;Fl(y)&&_!==i&&y.remove();const m=Vl(Ll(p.anchor,\"next\"));zl(p.anchor,m),zl(p.focus,m)}insertParagraph(){this.isCollapsed()||this.removeText();const t=this.anchor.getNode();if(\"element\"===this.anchor.type&&Va(t)){const e=oc();return t.splice(this.anchor.offset,0,[e]),e.select(),e}const[,n]=Ns(this),o=kf(this.anchor.getNode(),wu);if(null!==o&&null!==Of(o))return null;yl(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=Al();if(this.insertNodes([e]),t){const t=e.getParentOrThrow(),n=e.getIndexWithinParent();t.select(n,n)}}extract(){const t=[...this.getNodes()],e=t.length;let n=t[0],o=t[e-1];const[r,i]=Ui(this),s=this.isBackward(),[l,c]=s?[this.focus,this.anchor]:[this.anchor,this.focus],[a,u]=s?[i,r]:[r,i];if(0===e)return[];if(1===e){if(ki(n)&&!this.isCollapsed()){const t=n.splitText(a,u),e=0===a?t[0]:t[1];return e?(l.set(e.getKey(),0,\"text\"),c.set(e.getKey(),e.getTextContentSize(),\"text\"),[e]):[]}return[n]}if(ki(n)&&(a===n.getTextContentSize()?t.shift():0!==a&&([,n]=n.splitText(a),t[0]=n,l.set(n.getKey(),0,\"text\"))),ki(o)){const e=o.getTextContent().length;0===u?t.pop():u!==e&&([o]=o.splitText(u),t[t.length-1]=o,c.set(o.getKey(),o.getTextContentSize(),\"text\"))}return t}modify(t,e,n){if(Ms(this,t,e,n))return;const o=\"move\"===t,r=Vs(),i=Qa(Wa(r));if(!i)return;const s=r._blockCursorElement,l=r._rootElement,c=this.focus.getNode();null===l||null===s||!yl(c)||c.isInline()||c.canBeEmpty()||Xa(s,r,l);const a=Aa(r,this.focus.key);let u=a;if(\"text\"===this.focus.type&&(u=ki(c)?Pu(c,a,r):null),this.dirty){const t=Aa(r,this.anchor.key);let e=t;if(\"text\"===this.anchor.type){const n=this.anchor.getNode();e=ki(n)?Pu(n,t,r):null}e&&u&&ms(i,e,this.anchor.offset,u,this.focus.offset)}if(\"character\"===n&&ki(c)&&c.isUnmergeable()&&(e?0===this.focus.offset:this.focus.offset===c.getTextContentSize())){const t=ad(c,e?\"previous\":\"next\").getNodeAtCaret();if(ki(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?Pu(t,n,r):null;if(o){const t=e?o.length:0;ms(i,o,t,o,t)}}}}if(Hi(i,t,e?\"backward\":\"forward\",n,l),i.rangeCount>0){const t=su(i,r._rootElement),n=t||i.getRangeAt(0),s=this.anchor.getNode(),l=vl(s)?s:ja(s);this.applyDOMRange(n),this.dirty=!0,o||(qi(this,e,l),(t?\"backward\"!==i.direction:i.anchorNode===n.startContainer&&i.anchorOffset===n.startOffset)||Ji(this))}\"lineboundary\"===n&&Ms(this,t,e,n,\"decorators\")}forwardDeletion(t,e,n){if(!n&&(\"element\"===t.type&&yl(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(yl(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=yl(n)?n.getNextSibling():null;if(!(yl(n)&&n.isEmpty()&&yl(t)&&t.isShadowRoot()))return}const o=Ll(e,t?\"previous\":\"next\"),r=Sd(o);if(r.getTextSlices().every(t=>null===t||0===t.distance)){if(\"element\"===e.type){const t=o.getNodeAtCaret();if(yl(t)&&Ga(t)){const e=t.getParent();t.remove();const n=ia(e,t);return void(null!==n&&n.selectStart())}}let t={type:\"initial\"};for(const e of r.iterNodeCarets(\"shadowRoot\"))if(id(e))if(e.origin.isInline());else{if(e.origin.isShadowRoot()){if(\"merge-block\"===t.type)break;if(yl(r.anchor.origin)&&r.anchor.origin.isEmpty()){const t=Vl(e);Bl(this,vd(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(rd(e)){if(yl(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(Sl(e.origin)){if(e.origin.isIsolated());else if(\"merge-next-block\"===t.type&&(e.origin.isKeyboardSelectable()||!e.origin.isInline())&&yl(r.anchor.origin)&&r.anchor.origin.isEmpty()){r.anchor.origin.remove();const t=cs();t.add(e.origin.getKey()),sa(t)}else{const t=e.origin,n=t.getParent();t.remove();const o=ia(n,t);null!==o&&o.selectStart()}return}if(Fl(e.origin))return void e.origin.remove();break}}if(\"merge-block\"===t.type){const{caret:e,block:n}=t;if(If(n).length>0)return;return e.origin.isEmpty()&&!n.isEmpty()&&e.origin.getParent()===n.getParent()?void e.origin.remove(!0):(Bl(this,vd(!e.origin.isEmpty()&&n.isEmpty()?Wl(ad(n,e.direction)):r.anchor,e)),this.removeText())}for(let t=e.getNode();null!==t;){if(null!==Of(t))return;if(yl(t)&&t.isShadowRoot())break;t=t.getParent()}}const i=this.focus;if(Yi(this,t,\"character\"),this.isCollapsed()){if(t&&0===e.offset&&function(t,e){for(let n=e;n;n=n.getParent()){if(yl(n)){if(n.collapseAtStart(t))return!0;if(Va(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 Qi(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 Qi(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&&!aa(i=r.getTextContent().slice(c,a))&&!Xi(i)&&(e?o.set(o.key,u,o.type):n.set(n.key,u,n.type))}var i}(this,t)}}e||Vi(this),this.removeText(),t&&!e&&this.isCollapsed()&&\"element\"===this.anchor.type&&0===this.anchor.offset&&Li()}deleteLine(t){const e=this.isCollapsed(),n=es(this.anchor);if(null!==n&&Sl(Mf(n)))return this.isCollapsed()||this.focus.set(this.anchor.key,this.anchor.offset,this.anchor.type),void this.deleteCharacter(t);this.isCollapsed()&&Yi(this,t,\"lineboundary\"),this.isCollapsed()?this.deleteCharacter(t):kf(this.anchor.getNode(),wu)!==kf(this.focus.getNode(),wu)?(this.focus.set(this.anchor.key,this.anchor.offset,this.anchor.type),this.deleteCharacter(t)):(e||Vi(this),this.removeText())}deleteWord(t){const e=this.isCollapsed();if(this.isCollapsed()){const e=this.anchor,n=e.getNode();if(this.forwardDeletion(e,n,t))return;Yi(this,t,\"word\")}this.isCollapsed()?this.deleteCharacter(t):(e||Vi(this),this.removeText())}isBackward(){const t=this._cachedIsBackward;if(null!==t)return t;const e=this.focus.isBefore(this.anchor);return Rs()||(this._cachedIsBackward=e),e}getStartEndPoints(){return[this.anchor,this.focus]}}function Bi(t){return t instanceof Ii}function Ri(t,e){if(Bi(t)){for(const n of t.getNodes())di(n)&&n.setFormat(e(n.getFormat()));return}if(t.isCollapsed())return t.setFormat(e(t.format)),void Yc(null);const n=[];for(const o of t.getNodes())ki(o)?n.push(o):yl(o)?o.setTextFormat(e(o.getTextFormat())):di(o)&&o.setFormat(e(o.getFormat()));const o=n.length;if(0===o)return t.setFormat(e(t.format)),void Yc(null);const r=t.anchor,i=t.focus,s=t.isBackward(),l=s?i:r,c=s?r:i;let a=0,u=n[0],f=\"element\"===l.type?0:l.offset;if(\"text\"===l.type&&f===u.getTextContentSize()&&(a=1,u=n[1],f=0),null==u)return;const d=o-1;let h=n[d];const g=\"text\"===c.type?c.offset:h.getTextContentSize();if(u.is(h)){if(f===g)return;const n=e(u.getFormat());if(Bc(u)||0===f&&g===u.getTextContentSize())u.setFormat(n);else{const t=u.splitText(f,g),e=0===f?t[0]:t[1];e.setFormat(n),\"text\"===l.type&&l.set(e.__key,0,\"text\"),\"text\"===c.type&&c.set(e.__key,g-f,\"text\")}return void(t.format=n)}0===f||Bc(u)||([,u]=u.splitText(f),f=0);const _=e(u.getFormat());u.setFormat(_);const p=e(h.getFormat());g>0&&(g===h.getTextContentSize()||Bc(h)||([h]=h.splitText(g)),h.setFormat(p));for(let t=a+1;t<d;t++){const o=n[t];o.setFormat(e(o.getFormat()))}\"text\"===l.type&&l.set(u.__key,f,\"text\"),\"text\"===c.type&&c.set(h.__key,g,\"text\"),t.format=_|p}function Wi(t,e){const n=[];for(const[t,o]of Object.entries(e))\"boolean\"==typeof o&&n.push([t,o]);0!==n.length&&Ri(t,t=>{for(const[e,o]of n)t=jc(t,e,o?K[e]:0);return t})}function $i(t,e,n=null){const o=null===n&&zi(t)?jc(t.format,e,null):n;Ri(t,t=>jc(t,e,o))}function ji(t){const e=t.offset;if(\"text\"===t.type)return e;const n=t.getNode();return e===n.getChildrenSize()?n.getTextContent().length:0}function Ui(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]:[ji(n),ji(o)]}function Vi(t){const e=ra();!e.isEmpty()&&tc(e,t)&&(t.anchor.set(e.getKey(),0,\"element\"),t.focus.set(e.getKey(),e.getChildrenSize(),\"element\"))}function Ji(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 Hi(t,e,n,o,r){const i=\"character\"===o?cu(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=cu(t,r);c.focusNode===s&&c.focusOffset===l&&t.modify(e,n,o)}function qi(t,e,n){const o=t.getNodes(),r=o.filter(t=>Ba(t,n));if(0===r.length||r.length===o.length)return!1;const i=e?r[0]:r[r.length-1],s=yl(i)?i:i.getParentOrThrow();return e?s.selectStart():s.selectEnd(),!0}function Yi(t,e,n){if(Ms(t,\"extend\",e,n))return;const o=Vs(),r=Qa(Wa(o));if(!r||\"function\"!=typeof r.modify)return;const i=o._blockCursorElement,s=o._rootElement,l=t.anchor,c=t.focus.getNode();null===s||null===i||!yl(c)||c.isInline()||c.canBeEmpty()||Xa(i,o,s);const a=t=>{const e=t.getNode(),n=o.getElementByKey(t.key);return null!==n&&\"text\"===t.type&&ki(e)?Pu(e,n,o):n},u=l.getNode(),f=a(l);if(null===f)return;const d=l.offset,h=t.isCollapsed(),g=t.focus,_=h?f:a(g);if(null===_)return;const p=g.offset;if(ms(r,_,p,_,p),Hi(r,\"move\",e?\"backward\":\"forward\",n,s),0===r.rangeCount)return;const y=su(r,s)||r.getRangeAt(0);let m=y.startContainer,x=y.startOffset;if(\"lineboundary\"===n&&Rc(m)&&Ic(m)===o){const t=ca(m);if(Sl(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&&ki(u)&&u.isUnmergeable()&&d===(e?0:u.getTextContentSize())){const n=ad(u,e?\"previous\":\"next\").getNodeAtCaret();if(ki(n)){const o=e?n.getTextContentSize()-1:1;return t.focus.set(n.__key,o,\"text\"),void(t.dirty=!0)}}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 void(o!==d&&(t.focus.set(l.key,o,\"text\"),t.dirty=!0))}const[S,C,v,k]=e?[m,x,f,d]:[f,d,m,x],b=vl(u)?u:ja(u);t.applyDOMRange({collapsed:!1,endContainer:v,endOffset:k,startContainer:S,startOffset:C}),t.dirty=!0,!qi(t,e,b)&&e&&Ji(t),\"lineboundary\"===n&&Ms(t,\"extend\",e,n,\"decorators\")}function Gi(){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 Xi=/* @__PURE__ */Gi();function Qi(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 Zi(t,n,o,r){let i,s=n,l=!1;if(Su(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!==ta(t,r)||Ju(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=ca(d),ki(i))s=fd(i,c?\"next\":\"previous\");else{let a=ca(t);if(null===a)return null;if(yl(a)){const l=r.getElementByKey(a.getKey());null===l&&e(214);const u=Mu(a,l,r);[a,s]=u.resolveChildIndex(a,l,t,n),yl(a)||e(215),c&&s>=a.getChildrenSize()&&(s=Math.max(0,a.getChildrenSize()-1));let f=a.getChildAtIndex(s);if(yl(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=yl(f)?f:f.getParentOrThrow()),s=0}ki(f)?(i=f,a=null,s=fd(f,c?\"next\":\"previous\")):f!==a&&c&&!h&&(yl(a)||e(216),s=Math.min(a.getChildrenSize(),s+1))}else{const e=Mf(a),o=null!==e?e:a,i=o.getIndexWithinParent(),l=r.getElementByKey(a.getKey());let c=\"after\";if(null!==l&&ca(t)===a){const e=Mu(a,l,r);e.element!==l?c=e.resolveLeafPosition(l,t,n):0===n&&Sl(a)&&(c=\"before\")}s=\"before\"===c?i:i+1,a=o.getParentOrThrow()}if(yl(a))return[Mi(a.__key,s,\"element\"),l]}}else i=ca(t);return ki(i)?[Mi(i.__key,fd(i,s,\"clamp\"),\"text\"),l]:null}function ts(t,e,n){const o=t.offset,r=t.getNode();if(0===o){const o=r.getPreviousSibling(),i=r.getParent();if(e){if((n||!e)&&null===o&&yl(i)&&i.isInline()){const e=i.getPreviousSibling();ki(e)&&t.set(e.__key,e.getTextContent().length,\"text\")}}else yl(o)&&!n&&o.isInline()?t.set(o.__key,o.getChildrenSize(),\"element\"):ki(o)&&!r.isUnmergeable()&&t.set(o.__key,o.getTextContent().length,\"text\")}else if(o===r.getTextContent().length){const o=r.getNextSibling(),i=r.getParent();if(e&&yl(o)&&o.isInline())t.set(o.__key,0,\"element\");else if((n||e)&&null===o&&yl(i)&&i.isInline()&&!i.canInsertTextAfter()&&i.getTextContentSize()>1){const e=i.getNextSibling();ki(e)&&t.set(e.__key,0,\"text\")}}}function es(t){const e=Xc(t.key);return null===e?null:Ff(e)}function ns(t,e,n){const o=es(t),r=es(e);if(o===r||null!==o&&null!==r&&o.is(r))return!1;const i=n(o,r);if(null!==o)return yl(o)?e.set(o.getKey(),i?o.getChildrenSize():0,\"element\"):e.set(o.getKey(),i?o.getTextContentSize():0,\"text\"),!0;const s=Mf(r);if(null===s)return!1;const l=s.getParent();if(null===l)return!1;const c=s.getIndexWithinParent();return e.set(l.getKey(),i?c+1:c,\"element\"),!0}function os(t){const e=ns(t.anchor,t.focus,(e,n)=>function(t,e,n,o){if(null!==n&&null!==o){const t=Mf(n),e=Mf(o);if(null!==t&&t.is(e)){for(const e of Pf(t).values()){if(e===n.getKey())return!0;if(e===o.getKey())return!1}return!0}return null===t||null===e||t.isBefore(e)}if(null!==n){const t=Mf(n),o=Xc(e.key);return null===t||null===o||!(!t.is(o)&&!t.isParentOf(o))||t.isBefore(o)}const r=Mf(o),i=Xc(t.key);return null!==r&&null!==i&&!r.is(i)&&!r.isParentOf(i)&&i.isBefore(r)}(t.anchor,t.focus,e,n));return e&&(t.dirty=!0),e}function rs(t,e,n,o,r,i){if(null===t||null===n||!Dc(r,t,n))return null;const s=Zi(t,e,zi(i)?i.anchor:null,r);if(null===s)return null;const l=Zi(n,o,zi(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=ca(t),o=ca(n);if(Sl(e)&&Sl(o))return null}const d=r._slotsUsed&&ns(c,u,()=>0!==(t.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_FOLLOWING));return function(t,e){if(\"text\"===t.type&&\"text\"===e.type){const n=t.isBefore(e),o=t.is(e);ts(t,n,o),ts(e,!n,o),o&&e.set(t.key,t.offset,t.type)}}(c,u),[c,u,a||f||d]}function is(t){return yl(t)&&!t.isInline()}function ss(t,e,n,o,r,i){const s=js(),l=new Ki(Mi(t,e,r),Mi(n,o,i),0,\"\");return l.dirty=!0,s._selection=l,l}function ls(){const t=Mi(\"root\",0,\"element\"),e=Mi(\"root\",0,\"element\");return new Ki(t,e,0,\"\")}function cs(){return new Ii(new Set)}function as(t,e){return us(null,t,e,null)}function us(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=!gt&&(l||\"beforeinput\"===s||\"compositionstart\"===s||\"compositionend\"===s||\"click\"===s&&i&&3===i.detail||\"drop\"===s||void 0===s);let a,u,f,d;if(zi(t)&&!c)return t.clone();{if(null===e)return null;const o=cu(e,n._rootElement);if(a=o.anchorNode,u=o.focusNode,f=o.anchorOffset,d=o.focusOffset,(l||void 0===s)&&zi(t)&&!Dc(n,a,u))return t.clone()}const h=rs(a,f,u,d,n,t);if(null===h)return null;const[g,_,p]=h;let y=0,m=\"\";if(zi(t)){const e=t.anchor;if(g.key===e.key)y=t.format,m=t.style;else{const t=g.getNode();ki(t)?(y=t.getFormat(),m=t.getStyle()):yl(t)&&(y=t.getTextFormat(),m=t.getTextStyle())}}const x=new Ki(g,_,y,m);return p&&(x.dirty=!0),x}function fs(){return js()._selection}function ds(){return Vs()._editorState._selection}function hs(t,e){const n=e.__key;return t.anchor.key===n||t.focus.key===n}function gs(t,e,n,o=1){if(!hs(t,e))return;const r=t.anchor,i=t.focus,s=e.__key;if(t.isCollapsed()){const e=r.offset;if(n<=e&&o>0||n<e&&o<0){const n=Math.max(0,e+o);r.set(s,n,\"element\"),i.set(s,n,\"element\"),_s(t)}}else{const l=t.isBackward(),c=l?i:r,a=c.getNode(),u=l?r:i,f=u.getNode();if(e.is(a)){const t=c.offset;(n<=t&&o>0||n<t&&o<0)&&c.set(s,Math.max(0,t+o),\"element\")}if(e.is(f)){const t=u.offset;(n<=t&&o>0||n<t&&o<0)&&u.set(s,Math.max(0,t+o),\"element\")}}_s(t)}function _s(t){const e=t.anchor,n=e.offset,o=t.focus,r=o.offset,i=e.getNode(),s=o.getNode();if(t.isCollapsed()){if(!yl(i))return;const t=i.getChildrenSize(),r=n>=t,s=r?i.getChildAtIndex(t-1):i.getChildAtIndex(n);if(ki(s)){let t=0;r&&(t=s.getTextContentSize()),e.set(s.__key,t,\"text\"),o.set(s.__key,t,\"text\")}return}if(yl(i)){const t=i.getChildrenSize(),o=n>=t,r=o?i.getChildAtIndex(t-1):i.getChildAtIndex(n);if(ki(r)){let t=0;o&&(t=r.getTextContentSize()),e.set(r.__key,t,\"text\")}}if(yl(s)){const t=s.getChildrenSize(),e=r>=t,n=e?s.getChildAtIndex(t-1):s.getChildAtIndex(r);if(ki(n)){let t=0;e&&(t=n.getTextContentSize()),o.set(n.__key,t,\"text\")}}}function ps(t,e,n,o,r){let i=null,s=0,l=null;null!==o?(i=o.__key,ki(o)?(s=o.getTextContentSize(),l=\"text\"):yl(o)&&(s=o.getChildrenSize(),l=\"element\")):null!==r&&(i=r.__key,ki(r)?l=\"text\":yl(r)&&(l=\"element\")),null!==i&&null!==l?t.set(i,s,l):(s=e.getIndexWithinParent(),-1===s&&(s=n.getChildrenSize()),t.set(n.__key,s,\"element\"))}function ys(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 ms(t,e,n,o,r){try{t.setBaseAndExtent(e,n,o,r)}catch(t){}}function xs(t,e,n){const o=Aa(t,e.getKey());if(yl(e)){const r=Mu(e,o,t);return[r.element,n+r.getFirstChildOffset()]}return[o,n]}function Ss(t,e,n,o,r,i){const s=i.getRootNode(),l=Wc(s)||tu(s)?gu(s):null;if(r.has(Br)&&l!==i||null!==l&&Ac(l,l))return;const c=cu(o,i);let a;if(!zi(e))return void(null!==t&&Dc(n,c.anchorNode,c.focusNode)&&o.removeAllRanges());const f=e.anchor,d=e.focus,h=f.getNode(),g=d.getNode(),[_,p]=xs(n,h,f.offset),[y,m]=xs(n,g,d.offset),x=e.format,S=e.style,C=e.isCollapsed();let v=_,k=y,b=!1;if(\"text\"===f.type?(v=ki(h)?Pu(h,_,n):null,b=h.getFormat()!==x||h.getStyle()!==S):zi(t)&&\"text\"===t.anchor.type&&(b=!0),\"text\"===d.type&&(k=ki(g)?Pu(g,y,n):null),null!==v&&null!==k){if(C&&(null===t||b||zi(t)&&(t.format!==x||t.style!==S))&&function(t,e,n,o,r,i){t._inputState.collapsedSelectionFormat={format:e,key:r,offset:o,style:n,timeStamp:i}}(n,x,S,p,f.key,performance.now()),(\"Range\"!==o.type||!C)&&c.anchorOffset===p&&c.focusOffset===m&&c.anchorNode===v&&c.focusNode===k){if(null===l||!i.contains(l)){const t=null!==l?Ic(l):null;null!==t&&t!==n||r.has(jr)||i.focus({preventScroll:!0})}if(\"element\"!==f.type)return}if(ms(o,v,p,k,m),u&&e.isCollapsed()&&null!==i&&!r.has(jr)){const t=hu(i);if(null===t||!i.contains(t)){const t=gu(i.ownerDocument),e=null!==t?Ic(t):null;null!==e&&e!==n||i.focus({preventScroll:!0})}}if(!r.has(Wr)&&e.isCollapsed()&&null!==i&&i===hu(i)){const t=zi(e)&&\"element\"===e.anchor.type?function(t,e,n){const o=e.childNodes[n];if(!Su(o))return o||null;const r=ta(o,t),i=void 0!==r?Xc(r):null;return null===i||yl(i)?o:Mu(i,o,t).element}(n,v,p):(void 0===a&&(a=lu(o,i)),a);if(null!==t){let e;if(Rc(t)){const n=t.ownerDocument.createRange();n.selectNode(t),e=n.getBoundingClientRect()}else e=Su(t)?t.getBoundingClientRect():function(t){const e=t.getBoundingClientRect(),{startContainer:n,startOffset:o}=t;if(!t.collapsed||0!==e.width||0!==e.height||!Rc(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=Da(n),i=Ra(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=Su(o)?o:Fa(o);for(;null!==s&&n.contains(s);){const e=Ia(i,s,t,r);t-=e,r-=e,s=s===n?null:Fa(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=Wa(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=Fa(f)}}(n,e,i,v)}}!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,v,p,k,m)}}function Cs(t){let e=fs()||ds();null===e&&(e=ra().selectEnd()),e.insertNodes(t)}function vs(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 ks(t){const e=[];return vs(t,{linebreak:()=>e.push(Al()),tab:()=>e.push(wi()),text:t=>e.push(vi(t))}),e}function bs(){const t=fs();return null===t?\"\":t.getTextContent()}function Ts(t){const e=[];for(const n of t)Fl(n)||(!yl(n)&&!Sl(n)||n.isInline()?e.push(n):yl(n)&&e.push(...Ts(n.getChildren())));return e}function Ns(t,n=!1){let o=t;t.isCollapsed()||o.removeText();const r=fs();zi(r)&&(o=r),zi(o)||e(161);const i=o.anchor;let s=i.getNode(),l=i.offset;for(;!wu(s)&&null===Of(s);){const t=s;if([s,l]=ws(s,l,n),t.is(s))break}return[s,l]}function ws(t,e,n=!1){const o=t.getParent();if(!o){const t=oc();return ra().append(t),t.select(),[ra(),0]}if(ki(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(!yl(t)||0===e)return[o,t.getIndexWithinParent()];const r=t.getChildAtIndex(e);if(r){const o=new Ki(Mi(t.__key,e,\"element\"),Mi(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 Es(t){return Fl(t)||$a(t)||ki(t)||t.isParentRequired()}function Os(t){const e=oc();let n=null;for(let o=0;o<t.length;o++){const r=t[o];if(Es(r)){if(null===n){n=r.createParentElementNode(),e.append(n);const i=t[o+1];if(Fl(r)&&(void 0===i||!Es(i)))continue}n.append(r)}else e.append(r),n=null}return e}function Ms(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=Ll(t.focus,n?\"previous\":\"next\"),s=\"lineboundary\"===o,l=\"move\"===e;let c=i,a=\"decorators-and-blocks\"===r,u=!1;if(!Jl(c)){for(const t of c){a=!1;const{origin:e}=t;if(Sl(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 Sd(i).iterNodeCarets(\"extend\"===e?\"shadowRoot\":\"root\")){if(id(t))t.origin.isInline()||(c=t);else{if(yl(t.origin))continue;Sl(t.origin)&&!t.origin.isInline()&&(c=t)}break}}if(c===i)return!1;if(l&&!s&&Sl(c.origin)&&c.origin.isKeyboardSelectable()){const t=cs();return t.add(c.origin.getKey()),sa(t),!0}return c=Vl(c),l&&zl(t.anchor,c),zl(t.focus,c),a||!s}let As=null,Fs=null,Ds=!1,Ps=!1,Is=!1;const Ls=new Set,zs=new Set;let Ks=0;const Bs={characterData:!0,childList:!0,subtree:!0};function Rs(){return Ds||null!==As&&As._readOnly}function Ws(){Ds&&e(13)}function $s(){Ks>99&&e(14)}function js(){return null===As&&e(195,Hs()),As}function Us(t){null!==js()&&null===Fs&&(Fs=t),Fs!==t&&n(378)}function Vs(){return null===Fs&&e(337,Hs()),Fs}function Js(){Vs()._dirtyType=2}function Hs(){let t=0;const e=new Set,n=vc.version;if(\"undefined\"!=typeof window)for(const o of ou(document)){const r=Lc(o);if(Pc(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 qs(){return Fs}function Ys(t,e,n){const o=e.__type,r=Ec(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 Gs(t,e){return void 0!==t&&t.__key!==e&&t.isAttached()}function Xs(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 Qs(t){return Zs(t,Vs()._nodes)}function Zs(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(yl(s)&&Array.isArray(l))for(let t=0;t<l.length;t++){const e=Zs(l[t],n);s.append(e)}const c=t.$slots;if(c){wf(s)||e(379,i.name);for(const t in c)Vf(s,t,Zs(c[t],n))}return s}function tl(t,e,n){const o=As,r=Ds,i=Fs;As=e,Ds=!0,Fs=t;try{return n()}finally{As=o,Ds=r,Fs=i}}function el(e,n){const o=Is;Is=!0;try{const o=function(t){if(zs.has(t))return!1;zs.add(t);try{for(let e=0;null!==t._pendingEditorState;e++){const n=t._pendingEditorState._selection,o=t._rootElement;if(!ol(t,n))return!1;const r=(null===n||zi(n))&&(t._headless||null===o||!o.isConnected);if(r||100===e)return t._lastNotifiedSelection=null===n?null:n.clone(),!r;cl(t,()=>t.dispatchCommand(Ln),void 0,!0)}return!1}finally{zs.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&&il(e,e._deferred));const s=e._editorState,l=s._selection,c=o._selection,a=0!==e._dirtyType,u=As,f=Ds,d=Fs,h=e._updating,g=e._observer;let _=null;if(e._pendingEditorState=null,e._editorState=o,!i&&a&&null!==g){Fs=e,As=o,Ds=!1,e._updating=!0;try{const t=e._dirtyType,n=e._dirtyElements,r=e._dirtyLeaves;g.disconnect(),_=Fn(s,o,e,t,n,r)}catch(t){if(t instanceof Error&&e._onError(t),Ps)throw t;return pc(e,null,r,o),kt(e),e._dirtyType=2,Ps=!0,el(e,s),void(Ps=!1)}finally{g.observe(r,Bs),e._updating=h,As=u,Ds=f,Fs=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 S=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=na(t)),delete o[i])}(e,o);const C=i?null:Qa(Wa(e));if(e._editable&&null!==C&&(a||null===c||c.dirty||!c.is(l))&&null!==r&&!x.has($r)){Fs=e,As=o;try{if(null!==g&&g.disconnect(),a||null===c||c.dirty){const t=e._blockCursorElement;null!==t&&Xa(t,e,r),Ss(l,c,e,C,x,r)}!function(t,e,n){let o=t._blockCursorElement;if(zi(n)&&n.isCollapsed()&&\"element\"===n.anchor.type&&e.contains(hu(e))){const r=n.anchor,i=r.getNode(),s=r.offset;let l=!1,c=null;if(s===i.getChildrenSize())Ga(i.getChildAtIndex(s-1))&&(l=!0);else{const e=i.getChildAtIndex(s);null!==e&&Ga(e)&&(l=!0,c=t.getElementByKey(e.__key))}if(l){const n=Mu(i,t.getElementByKey(i.__key),t).element;return null===o&&(t._blockCursorElement=o=function(t){const e=t.theme,n=iu().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=Pd(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&&Xa(o,t,e)}(e,r,c)}finally{null!==g&&g.observe(r,Bs),Fs=d,As=u}}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 v=e._pendingDecorators;null!==v&&(e._decorators=v,e._pendingDecorators=null,nl(\"decorator\",e,!0,v)),function(t,e,n){const o=oa(e),r=oa(n);o!==r&&nl(\"textcontent\",t,!0,r)}(e,n||s,o),nl(\"update\",e,!0,{dirtyElements:y,dirtyLeaves:p,editorState:o,mutatedNodes:_,normalizedNodes:m,prevEditorState:n||s,tags:x}),h||il(e,S),function(e){const n=e._updates;if(0===n.length)return void(e._cascadeCount=0);if(function(t){Ls.has(t)||(Ls.add(t),setTimeout(()=>{Ls.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;cl(e,t,n)}}(e)}(e,n),o&&e._onWarn(t(436))}finally{Is=o}}function nl(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 ol(t,e){const n=t._lastNotifiedSelection;return null===e?null!==n:!e.is(n)}function rl(t,e,n,o){const r=ua(t);let i;if(!Is)for(let t=0;t<r.length;t++)r[t]._updating||(r[t]._cascadeCount=0);if(e===Ln){if(Fs!==t||Ds){let r=!1;return al(t,()=>{r=rl(t,e,n,o)}),r}const r=js()._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(al(l,()=>{for(const r of e)if(r(n,o))return void(t=!0)}),t)return t}}}return i&&i.update(()=>{rl(i,e,n,o)}),!1}function il(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 sl(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),Xs(t,i.tag)),null==s?cl(t,o,i):o()}}return r}function ll(){const t=js();Ws(),t._flushSync=!0}function cl(t,n,o,r=!1){const i=t._updateTags;let s,l=!1,c=!1;void 0!==o&&(s=o.onUpdate,Xs(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=kl(u||a),f=!0),u._flushSync=c;const d=As,h=Ds,g=Fs,_=t._updating;As=u,Ds=!1,t._updating=!0,Fs=t;const p=t._headless||null===t.getRootElement();bc(null);try{f&&(p?null!==a._selection&&(u._selection=a._selection.clone()):u._selection=function(t,e){const n=t.getEditorState()._selection,o=Qa(Wa(t));return zi(n)||null==n?us(n,o,t,e):n.clone()}(t,o&&o.event||null));const r=t._compositionKey;n(),l=sl(t,l),function(t,e){const n=e.getEditorState()._selection,o=t._selection;if(zi(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);ki(e)&&e.isAttached()&&e.isSimpleText()&&!e.isUnmergeable()&&Fe(e)}}(u,t):function(t,e){const n=e._dirtyLeaves,o=e._dirtyElements,r=t._nodeMap,i=Gc(),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);ki(o)&&o.isAttached()&&o.isSimpleText()&&!o.isUnmergeable()&&Fe(o),void 0!==o&&Gs(o,i)&&Ys(e,o,s),n.add(t)}if(l=e._dirtyLeaves,c=l.size,c>0){Ks++;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&&Gs(c,i)&&Ys(e,c,s)}l=e._dirtyLeaves,c=l.size,a=e._dirtyElements,u=a.size,Ks++}e._dirtyLeaves=n,e._dirtyElements=o}(u,t),sl(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()||(yl(e)&&ht(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()||(wf(e)&&null!==e.__slots&&ht(e,t,r,i,s,n),r.has(t)||n.delete(t),s.push(t))}const l=Vs(),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(zi(i)){t._slotsUsed&&os(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 Bi(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 el(t)}finally{As=d,Ds=h,Fs=g,t._updating=_,Ks=0}if(r)return;const y=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);y?u._flushSync?(u._flushSync=!1,el(t)):f&&Mc(()=>{el(t)}):(u._flushSync=!1,f&&(i.clear(),t._deferred=[],t._pendingEditorState=null))}function al(t,e,n){Fs===t&&void 0===n?Rs()?cl(t,e,n):e():cl(t,e,n)}function ul(){return{...$,0:\"\"}}function fl(){return{...R,\"\":0}}const dl=/* @__PURE__ */ul(),hl=/* @__PURE__ */fl(),gl=/* @__PURE__ */re()({direction:/* @__PURE__ */ue(/* @__PURE__ */Zt([null,\"ltr\",\"rtl\"]),{field:\"__dir\"}),format:/* @__PURE__ */ue(/* @__PURE__ */Zt([\"\",\"left\",\"start\",\"center\",\"right\",\"end\",\"justify\"]),{field:\"__format\",getter:\"getFormatType\",getterTable:dl,setter:\"setFormat\",setterTable:hl}),indent:/* @__PURE__ */ue(/* @__PURE__ */Xt(0,{integer:!0,min:0}),{field:\"__indent\"}),textFormat:/* @__PURE__ */fe(/* @__PURE__ */Xt(),{getter:{field:\"__textFormat\",method:\"getSerializedTextFormat\",when:\"shouldSerializeTextStyles\"},setter:{field:\"__textFormat\"}}),textStyle:/* @__PURE__ */fe(/* @__PURE__ */Yt(),{getter:{field:\"__textStyle\",method:\"getSerializedTextStyle\",when:\"shouldSerializeTextStyles\"},setter:{field:\"__textStyle\"}})});function _l(t){if(Va(t)){let e=null;for(const n of t.getChildren())e=n.isInline()?(e||n.replace(n.createParentElementNode())).append(n):null}}class pl extends Fr{__first;__last;__size;__format;__style;__indent;__dir;__textFormat;__textStyle;__slotHost;__slots;$config(){return this.config(Symbol.for(\"ElementNode\"),{$transform:_l,extends:Fr,generated:Yr,json:gl})}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 $[t]||\"\"}getStyle(){return this.getLatest().__style}getIndent(){return this.getLatest().__indent}getChildren(){const t=[];let e=this.getFirstChild();for(;null!==e;)t.push(e),e=e.getNextSibling();return t}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===If(this).length}isDirty(){const t=Vs()._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 If(this)){const n=Lf(this,e);if(yl(n))for(const e of n.getAllTextNodes())t.push(e)}let e=this.getFirstChild();for(;null!==e;){if(ki(e)&&t.push(e),yl(e))for(const n of e.getAllTextNodes())t.push(n);e=e.getNextSibling()}return t}getFirstDescendant(){let t=this.getFirstChild();for(;yl(t);){const e=t.getFirstChild();if(null===e)break;t=e}return t}getLastDescendant(){let t=this.getLastChild();for(;yl(t);){const e=t.getLastChild();if(null===e)break;t=e}return t}getDescendantByIndex(t){const e=this.getChildren(),n=e.length;if(t>=n){const t=e[n-1];return yl(t)&&t.getLastDescendant()||t||null}const o=e[t];return yl(o)&&o.getFirstDescendant()||o||null}getFirstChild(){const t=this.getLatest().__first;return null===t?null:Xc(t)}getFirstChildOrThrow(){const t=this.getFirstChild();return null===t&&e(45,this.__key),t}getLastChild(){const t=this.getLatest().__last;return null===t?null:Xc(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=jf(this);const e=this.getChildren(),n=e.length;for(let o=0;o<n;o++){const r=e[o];t+=r.getTextContent(),yl(r)&&o!==n-1&&!r.isInline()&&(t+=A)}return t}getTextContentSize(){let t=function(t){let e=0;for(const n of If(t)){const o=Lf(t,n);null!==o&&(e+=o.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(),yl(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=K[t];return 0!==(this.getTextFormat()&e)}getFormatFlags(t,e){return jc(this.getLatest().__textFormat,t,e)}getTextStyle(){return this.getLatest().__textStyle}select(t,e){Ws();const n=fs();let o=t,r=e;const i=this.getChildrenSize();if(!this.canBeEmpty())if(0===t&&0===e){const t=this.getFirstChild();if(ki(t)||yl(t))return t.select(0,0)}else if(!(void 0!==t&&t!==i||void 0!==e&&e!==i)){const t=this.getLastChild();if(ki(t)||yl(t))return t.select()}void 0===o&&(o=i),void 0===r&&(r=i);const s=this.__key;return zi(n)?(n.anchor.set(s,o,\"element\"),n.focus.set(s,r,\"element\"),n.dirty=!0,n):ss(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){Mr(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=[],c=[];let 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())}if(n>0){let t=null===u?this.getFirstChild():u.getNextSibling();for(let o=0;o<n;o++){null===t&&e(100);const n=t.getNextSibling(),o=t.__key;Jc(t.getWritable()),c.push(o),t=n}}let d=u;for(const t of o){null!==d&&t.is(d)&&(u=d=d.getPreviousSibling()),null!==a&&t.is(a)&&(a=a.getNextSibling());const n=t.getWritable();n.__parent===s&&f--,Jc(n);const o=t.__key;if(null===d)i.__first=o,n.__prev=null;else{const t=d.getWritable();t.__next=o,n.__prev=t.__key}t.__key===s&&e(76),n.__parent=s,l.push(o),d=t}if(null===a)null!==d&&(d.getWritable().__next=null,i.__last=d.__key);else{const t=a.getWritable();if(null!==d){const e=d.getWritable();t.__prev=d.__key,e.__next=a.__key}else t.__prev=null}if(i.__size=f,c.length){const t=fs();if(zi(t)){const e=new Set(c),n=new Set(l),{anchor:o,focus:r}=t;ml(o,e,n)&&ps(o,o.getNode(),this,u,a),ml(r,e,n)&&ps(r,r.getNode(),this,u,a),0!==f||this.canBeEmpty()||Va(this)||this.remove()}}return i}getDOMSlot(t){return new et(t)}exportDOM(t){const{element:e}=super.exportDOM(t);if(Su(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(Va(this))return!1;for(let t=this.getFirstChild();null!==t;t=t.getNextSibling())if(ki(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){const n=Mu(this,t,e);let o=n.getFirstChild();for(let t=this.getFirstChild();t;t=t.getNextSibling()){const r=e.getElementByKey(t.getKey());null!==r&&(null==o?(n.insertChild(r),o=r):o!==r&&n.replaceChild(r,o),o=o.nextSibling)}}}function yl(t){return t instanceof pl}function ml(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 xl extends Fr{__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 Sl(t){return t instanceof xl}class Cl extends pl{__cachedText;$config(){return this.config(\"root\",{extends:pl})}constructor(){super(\"root\"),this.__cachedText=null}getTopLevelElementOrThrow(){e(51)}getTextContent(){const t=this.__cachedText;return null===t||!Rs()&&0!==Vs()._dirtyType?super.getTextContent():t}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)yl(t)||Sl(t)||e(282);return super.splice(t,n,o)}static importJSON(t){return ra().updateFromJSON(t)}collapseAtStart(){return!0}}function vl(t){return t instanceof Cl}function kl(t){return new wl(lt(t._nodeMap),null,t._slotsUsed)}function bl(){return new wl(new Map([[\"root\",new Cl]]),null,!1)}function Tl(t){const n=t.constructor,o=dt(t);if(yl(t)){const e=o.children,n=t.getChildren();for(let t=0;t<n.length;t++)e.push(Tl(n[t]))}const r=If(t);if(r.length>0){const i={};for(const o of r){const r=Lf(t,o);null===r&&e(366,n.name,o),i[o]=Tl(r)}o.$slots=i}return o}function Nl(t){return t instanceof wl}class wl{_nodeMap;_selection;_flushSync;_readOnly;_parsed;_slotsUsed;constructor(t,e=null,n=!1){this._nodeMap=t,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 tl(e&&e.editor||null,this,t)}clone(t){const e=new wl(this._nodeMap,void 0===t?this._selection:t,this._slotsUsed);return e._readOnly=!0,e._parsed=this._parsed,e}toJSON(t){return ut(\"boolean\"==typeof t&&t,()=>tl(null,this,()=>({root:Tl(ra())})))}}class El extends pl{$config(){return this.config(\"artificial\",{extends:pl})}createDOM(t){return iu().createElement(\"div\")}}class Ol extends Fr{$config(){return this.config(\"linebreak\",{extends:Fr,generated:Zr,importDOM:{br:t=>Dl(t)||Pl(t)?null:{conversion:Ml,priority:0}}})}getTextContent(){return\"\\n\"}createDOM(){return iu().createElement(\"br\")}updateDOM(){return!1}isInline(){return!0}}function Ml(t){return{node:Al()}}function Al(){return Ha(new Ol)}function Fl(t){return t instanceof Ol}function Dl(t){const e=t.parentElement;if(null!==e&&Nu(e)){const n=e.firstChild;if(n===t||n.nextSibling===t&&Il(n)){const n=e.lastChild;if(n===t||n.previousSibling===t&&Il(n))return!0}}return!1}function Pl(t){const e=t.parentElement;if(null!==e&&Nu(e)){const n=e.firstChild;if(n===t||n.nextSibling===t&&Il(n))return!1;const o=e.lastChild;if(o===t||o.previousSibling===t&&Il(o))return!0}return!1}function Il(t){return Rc(t)&&/^( |\\t|\\r?\\n)+$/.test(t.textContent||\"\")}function Ll(t,n){const{type:o,key:r,offset:i}=t,s=Ya(t.key);return\"text\"===o?(ki(s)||e(266,s.getType(),r),ud(s,n,i)):(yl(s)||e(267,s.getType(),r),ql(s,t.offset,n))}function zl(t,n){const{origin:o,direction:r}=n,i=\"next\"===r;nd(n)?t.set(o.getKey(),n.offset,\"text\"):rd(n)?ki(o)?t.set(o.getKey(),fd(o,r),\"text\"):t.set(o.getParentOrThrow().getKey(),o.getIndexWithinParent()+(i?1:0),\"element\"):(id(n)&&yl(o)||e(268),t.set(o.getKey(),i?0:o.getChildrenSize(),\"element\"))}function Kl(t){const e=fs(),n=zi(e)?e:ls();return Bl(n,t),sa(n),n}function Bl(t,e){zl(t.anchor,e.anchor),zl(t.focus,e.focus)}function Rl(t){const{anchor:e,focus:n}=t,o=Ll(e,\"next\"),r=Ll(n,\"next\"),i=bd(o,r)<=0?\"next\":\"previous\";return vd(xd(o,i),xd(r,i))}function Wl(t){const{direction:e,origin:n}=t,o=ad(n,Qf(e)).getNodeAtCaret();return o?ad(o,e):hd(n.getParentOrThrow(),e)}function $l(t,e=\"root\"){const n=[t];for(let o=id(t)?t.getParentCaret(e):t.getSiblingCaret();null!==o;o=o.getParentCaret(e))n.push(Wl(o));return n}function jl(t){return!!t&&t.origin.isAttached()}function Ul(t,n=\"removeEmptySlices\"){if(t.isCollapsed())return t;const o=\"root\",r=\"next\";let i=n;const s=Hl(t,r);let l=s.anchor.origin;for(;null!==l&&!Va(l);)l=l.getParent();const c=yl(l)?l.getFirstChild():null,a=$l(s.anchor,o),u=$l(s.focus.getFlipped(),o),f=new Set,d=[];for(const t of s.iterNodeCarets(o))if(id(t))f.add(t.origin.getKey());else if(rd(t)){const{origin:e}=t;yl(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),Jc(t)}for(const t of h)!t.canBeEmpty()&&!Va(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=Wl(ad(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=vi(t.getTextContent()).setStyle(t.getStyle()).setFormat(t.getFormat());o.replaceOrInsert(n),e=ud(n,r,e.offset)}n.is(a[0].origin)&&(a[0]=e),n.is(u[0].origin)&&(u[0]=e.getFlipped())}}let g,_;for(const t of a)if(jl(t)){g=Vl(t);break}for(const t of u)if(jl(t)){_=Vl(t);break}const p=function(t,e,n){if(!t||!e)return null;const o=t.getParentAtCaret(),r=e.getParentAtCaret();if(!o||!r)return null;const i=o.getParents().reverse();i.push(o);const s=r.getParents().reverse();s.push(r);const l=Math.min(i.length,s.length);let c;for(c=0;c<l&&i[c]===s[c];c++);const a=(t,e)=>{let n;for(let o=c;o<t.length;o++){const r=t[o];if(Va(r))return;!n&&e(r)&&(n=r)}return n},u=a(i,wu),f=u&&a(s,t=>n.has(t.getKey())&&wu(t));return f&&If(f).length>0?null:u&&f?[u,f]:null}(g,_,f);if(p){const[t,e]=p;hd(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(id(t)){const e=t.origin;if(wu(e))return e}else{const e=t.getParentAtCaret();if(e&&wu(e))return e}return null}(_),e=t&&t.getParent(),n=t&&t.getParents().findLast(Ua);if(t&&e&&!vl(e)&&t.isEmpty()&&f.has(t.getKey())&&0===If(t).length&&(!n||f.has(n.getKey()))){t.remove(!0);let n=e;for(;n&&!vl(n)&&n.isEmpty();){const t=n.getParent();if(t&&vl(t)&&t.getChildrenSize()<=1&&n.canBeEmpty())break;const e=n;n=t,e.remove(!0)}}}null!==ia(l,c)||null===l||l.isAttached()||ia(ra(),null);const y=[g,_,...a,...u].find(jl);if(y)return Cd(xd(Vl(y),t.direction));e(269,JSON.stringify(a.map(t=>t.origin.__key)))}function Vl(t){const e=function(t){let e=t;for(;id(e);){const t=_d(e);if(!id(t))break;e=t}return e}(t.getLatest()),{direction:n}=e;if(ki(e.origin))return nd(e)?e:ud(e.origin,n,n);const o=e.getAdjacentCaret();return rd(o)&&ki(o.origin)?ud(o.origin,n,Qf(n)):e}function Jl(t){return nd(t)&&t.offset!==fd(t.origin,t.direction)}function Hl(t,e){return t.direction===e?t:vd(xd(t.focus,e),xd(t.anchor,e))}function ql(t,e,n){let o=hd(t,\"next\");for(let t=0;t<e;t++){const t=o.getAdjacentCaret();if(null===t)break;o=t}return xd(o,n)}function Yl(t,e=\"root\"){let n=0,o=t,r=_d(o);for(;null===r;){if(n--,r=o.getParentCaret(e),!r)return null;o=r,r=_d(o)}return r&&[r,n]}function Gl(t){const{origin:n,offset:o,direction:r}=t;if(o===fd(n,r))return t.getSiblingCaret();if(o===fd(n,Qf(r)))return Wl(t.getSiblingCaret());const[i]=n.splitText(o);return ki(i)||e(281),xd(ad(i,\"next\"),r)}function Xl(t,e){return!0}function Ql(t,{$copyElementNode:e=Ja,$splitTextPointCaretNext:n=Gl,rootMode:o=\"shadowRoot\",$shouldSplit:r=Xl,removeEmptyDestination:i=!1}={}){if(nd(t))return n(t);const s=t.getParentCaret(o);if(s){const{origin:n}=s;if(id(t)){const t=Wl(s);if(i&&n.isEmpty())return n.remove(),t;if(!n.canBeEmpty()||!r(n,\"first\"))return t}const o=function(t){const e=[];for(let n=t.getAdjacentCaret();n;n=n.getAdjacentCaret())e.push(n.origin);return e}(t);(o.length>0||!i&&n.canBeEmpty()&&r(n,\"last\"))&&s.insert(e(n).splice(0,0,o))}return s}function Zl(t,n,o){let r=xd(n,\"next\");nd(r)&&(0===r.offset?r=ad(r.origin,\"previous\").getFlipped():r.offset===r.origin.getTextContentSize()&&(r=ad(r.origin,\"next\"))),r.origin.is(t)&&(rd(r)||e(342,t.getKey(),t.getType()),r=Wl(r)),(t.is(r.getNodeAtCaret())||t.is(r.getFlipped().getNodeAtCaret()))&&t.remove(!0);for(let t=r;t;t=Ql(t,o))r=t;return nd(r)&&e(283),r.insert(t.isInline()?oc().append(t):t),xd(ad(t.getLatest(),\"next\"),n.direction)}function tc(t,e){const n=Hl(zi(e)?Rl(e):e,\"next\"),o=Ff(n.anchor.origin),r=Ff(t.getLatest());if(null===o?null!==r:!o.is(r))return!1;const i=Vl(hd(t,\"next\")),s=xd(Vl(hd(t,\"previous\")),\"next\");return bd(n.anchor,i)<=0&&bd(n.focus,s)>=0}class ec extends pl{$config(){return this.config(\"paragraph\",{extends:pl,generated:Qr,importDOM:{p:()=>({conversion:nc,priority:0})}})}createDOM(t){const e=iu().createElement(\"p\"),n=ba(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(Su(e)){this.isEmpty()&&e.append(iu().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(ki),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(!zi(e))return!1;if(\"\"===this.getFormatType()&&0===this.getIndent()&&\"\"===this.getStyle())return!1;if(tc(this,e)){const t=this.getTextContent();return\"\"!==t&&e.getTextContent()===t}return!1}insertNewAfter(t,e){const n=oc();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=>ki(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 nc(t){const e=oc();if($u(e,t),Ru(t,e),\"\"===e.getFormatType()){const n=t.getAttribute(\"align\");n&&n&&n in R&&e.setFormat(n)}return Wu(e,t),{node:e}}function oc(){return Ha(new ec)}function rc(t){return t instanceof ec}function ic(t){console.warn(t)}const sc=0,lc=1,cc=2,ac=3,uc=4,fc=-8,dc=-7,hc=-6,gc=-5,_c=-4;function pc(t,e,n,o,r){const i=t._keyToDOMMap;i.clear(),t._editorState=bl(),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),t._inputState={collapsedSelectionFormat:{format:0,key:\"root\",offset:0,style:\"\",timeStamp:0},compositionEndData:\"\",compositionPhase:\"idle\",hadOrphanedCompositionEvents:!1,handledSelectionCommandTimeoutId:null,isInsertLineBreak:!1,isInsertTextAfterHandledSelectionCommand:!1,isSelectionChangeFromDOMUpdate:!1,isSelectionChangeFromMouseDown:!1,isShiftKeyDown:!1,lastBeforeInputInsertTextTimeStamp:0,lastKeyCode:null,lastKeyDownTimeStamp:0,postDeleteSelectionToRestore:null,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),Zc(n,t,\"root\"))}function yc(t){const e=new Set,n=new Set;for(const{klass:o,ownNodeConfig:r}of Sf(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 mc={$createDOM:(t,e)=>t.createDOM(e._config,e),$decorateDOM:(t,e,n,o)=>{},$exportDOM:(t,e)=>{const n=Oc(e,t.getType());return n&&void 0!==n.exportDOM?n.exportDOM(e,t):t.exportDOM(e)},$extractWithChild:(t,e,n,o,r)=>yl(t)&&t.extractWithChild(e,n,o),$getDOMSlot:(t,e,n)=>t.getDOMSlot(e),$getSlotTargetElement:(t,e,n,o)=>null,$shouldExclude:(t,e,n)=>yl(t)&&t.excludeFromCopy(\"html\"),$shouldInclude:(t,e,n)=>!e||t.isSelected(e),$updateDOM:(t,e,n,o)=>t.updateDOM(e,n,o._config)};function xc(t){const n=t||{},o=qs(),r=n.theme||{},i=void 0===t?o:n.parentEditor||null,s=n.disableEvents||!1,l=bl(),c=n.namespace||(null!==i?i._config.namespace:fa()),a=n.editorState,u=[Cl,hi,Ol,Ni,ec,El,...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===Fr||o.prototype instanceof Fr)){let r=\"<unknown>\";try{r=JSON.parse(rt)}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))}_f(o);const s=o.getType(),l=yc(o);_.set(s,{exportDOM:h&&h.export?h.export.get(o):void 0,klass:o,replace:r,replaceWithKlass:i,sharedNodeState:Se(u[t]),transforms:l})}}const p=new vc(l,i,_,{disableEvents:s,dom:{...mc,...t&&t.dom},namespace:c,theme:r},f||console.error,d||ic,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(Bn,ir,0),t.registerCommand(Rn,lr,0),t.registerCommand(Wn,ar,0),t.registerCommand($n,ur,0),t.registerCommand(eo,Sr,0)}(p),p}function Sc(t,e){const n=t.get(e);t.delete(e),n&&n()}function Cc(t,e,n){return t.set(e,n),Sc.bind(null,t,e)}class vc{static version=(()=>rt)();_headless;_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 ct,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=fa(),this._onError=r,this._onWarn=i,this._htmlConversions=s,this._editable=l,this._headless=null!==e&&e._headless,this._window=null,this._blockCursorElement=null,this._slotsUsed=!1,this._keyDownShortcuts=null,this._inputState={collapsedSelectionFormat:{format:0,key:\"root\",offset:0,style:\"\",timeStamp:0},compositionEndData:\"\",compositionPhase:\"idle\",hadOrphanedCompositionEvents:!1,handledSelectionCommandTimeoutId:null,isInsertLineBreak:!1,isInsertTextAfterHandledSelectionCommand:!1,isSelectionChangeFromDOMUpdate:!1,isSelectionChangeFromMouseDown:!1,isShiftKeyDown:!1,lastBeforeInputInsertTextTimeStamp:0,lastKeyCode:null,lastKeyDownTimeStamp:0,postDeleteSelectionToRestore:null,selectionChangeFromDOMUpdatePoints:null,unprocessedBeforeInputData:null},this._lastNotifiedSelection=null}isComposing(){return null!=this._compositionKey}registerUpdateListener(t){return Cc(this._listeners.update,t)}registerEditableListener(t){return Cc(this._listeners.editable,t)}registerDecoratorListener(t){return Cc(this._listeners.decorator,t)}registerTextContentListener(t){return Cc(this._listeners.textcontent,t)}registerRootListener(t){const e=this._listeners.root;return zd(Cc(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 it,new it,new it,new it,new it]);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=zu(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 function(t,e){const n=zu(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=Xc(e);t&&t.markDirty()}},null===t._pendingEditorState?{tag:Lr}:void 0)}(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 Ma(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=ba(this._config.theme,\"root\"),r=this._pendingEditorState||this._editorState;if(this._rootElement=t,pc(this,n,t,r,{preserveUpdateQueue:!0}),null!==n&&(this._config.disableEvents||function(t){const n=Uo.get(t);if(void 0===n)return void Nr();const o=Vo.get(n);if(void 0===o)return void Nr();Uo.delete(t);const r=Lc(t);Pc(r)?(function(t){if(null!==t._parentEditor){const e=ua(t),n=e[e.length-1]._key;vr.get(n)===t&&vr.delete(n)}else vr.delete(t._key)}(r),o.editors.delete(r),o.hasShadowEditor=void 0,t.__lexicalEditor=null):r&&e(198);const i=Cr(t);for(let t=0;t<i.length;t++)i[t]();t.__lexicalEventHandles=[]}(n),null!=o&&n.classList.remove(...o)),null!==t){const e=Ra(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,kt(this),this._updateTags.add(Lr),el(this),this._config.disableEvents||function(t,e){const n=t.ownerDocument;Uo.set(t,n);let o=Vo.get(n);void 0===o&&(o={editors:new Set,hasShadowEditor:void 0},Vo.set(n,o)),o.editors.add(e),o.hasShadowEditor=void 0,t.__lexicalEditor=e;const r=Cr(t);r.push(Jo.register(n));const i=function(){if(void 0!==jo)return jo;const t=[[\"keydown\",gr],[\"pointerdown\",Zo],[\"compositionstart\",cr],[\"compositionend\",hr],[\"input\",sr],[\"click\",Qo],[\"cut\",$o],[\"copy\",$o],[\"dragstart\",$o],[\"dragover\",$o],[\"dragend\",$o],[\"paste\",$o],[\"focus\",$o],[\"blur\",$o],[\"drop\",$o]];return d&&t.push([\"beforeinput\",(t,e)=>function(t,e){const n=t.inputType;\"deleteCompositionText\"===n||u&&Oa(e)||\"insertCompositionText\"!==n&&al(e,()=>{rr(t,e)||Ma(e,Bn,t)},{event:t})}(t,e)]),g&&t.push([\"keyup\",(t,e)=>function(t,e){t.shiftKey&&\"CapsLock\"!==t.key||(e._inputState.isShiftKeyDown=!1)}(t,e)]),jo=t,t}();for(let n=0;n<i.length;n++){const[o,s]=i[n],l=\"function\"==typeof s?t=>{Tr(t)||(br(t),(e.isEditable()||\"click\"===o)&&s(t,e))}:t=>{if(Tr(t))return;br(t);const n=e.isEditable();switch(o){case\"cut\":return n&&Ma(e,bo,t);case\"copy\":return Ma(e,ko,t);case\"paste\":return n&&Ma(e,Hn,t);case\"dragstart\":return n&&Ma(e,So,t);case\"dragover\":return n&&Ma(e,Co,t);case\"dragend\":return n&&Ma(e,vo,t);case\"focus\":return n&&Ma(e,Mo,t);case\"blur\":return e._inputState.isShiftKeyDown=!1,e._inputState.isInsertLineBreak=!1,n&&Ma(e,Ao,t);case\"drop\":return n&&Ma(e,mo,t)}};r.push(Wo(t,o,l))}}(t,this),null!=o&&t.classList.add(...o)}else this._window=null,this._updateTags.add(Lr),el(this);nl(\"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=kl(t),r._selection=t._selection?t._selection.clone():null),vt(this);const i=this._pendingEditorState,s=void 0!==e?e.tag:null;null===i||i.isEmpty()||(null!=s&&this._updateTags.add(s),el(this)),this._pendingEditorState=r,this._dirtyType=2,this._dirtyElements.set(\"root\",!1),this._compositionKey=null,this._slotsUsed=this._slotsUsed||t._slotsUsed,al(this,()=>{if(s&&this._updateTags.add(s),o&&(n(38),ra().append(oc())),t._parsed)for(const[t,e]of r._nodeMap.entries())yl(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=bl(),r=As,i=Ds,s=Fs,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,As=o,Ds=!1,Fs=e,bc(null);try{const r=e._nodes;Zs(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,As=r,Ds=i,Fs=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&&el(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]):cl(t,e,n)}(this,t,e)}focus(t,e={}){const n=this._rootElement;null!==n&&(n.setAttribute(\"autocapitalize\",\"off\"),al(this,()=>{const o=fs(),r=ra();null!==o?o.dirty||sa(o.clone()):0!==r.getChildrenSize()&&(\"rootStart\"===e.defaultSelection?r.selectStart():r.selectEnd()),za(\"focus\"),Ka(()=>{n.removeAttribute(\"autocapitalize\"),t&&t()})}),null===this._pendingEditorState&&n.removeAttribute(\"autocapitalize\"))}blur(){const t=this._rootElement;null!==t&&t.blur();const e=Qa(this._window);null!==e&&e.removeAllRanges()}isEditable(){return this._editable}setEditable(t){this._editable!==t&&(this._editable=t,nl(\"editable\",this,!0,t),this._slotsUsed&&this.update(()=>Js()))}toJSON(){return{editorState:this._editorState.toJSON(ft())}}}let kc=null;function bc(t){kc=t}const Tc=Symbol(\"INTERNAL_SKIP_AFTER_CLONE_FROM\");let Nc=1;function wc(){Nc=1}function Ec(t,n){const o=Oc(t,n);return void 0===o&&e(30,n),o}function Oc(t,e){return t._nodes.get(e)}const Mc=\"function\"==typeof queueMicrotask?queueMicrotask:t=>{Promise.resolve().then(t)};function Ac(t,e){const n=void 0!==e?e:(()=>{const e=t.getRootNode();return Wc(e)||tu(e)?gu(e):null})();if(!Su(n))return!1;if(n.hasAttribute(\"data-lexical-slot\"))return!1;const o=ea(n),r=n.nodeName;return Dr(o)&&(\"INPUT\"===r||\"TEXTAREA\"===r||\"true\"===n.contentEditable&&null==Lc(n))}const Fc=Ac;function Dc(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 Ic(e)===t&&t.read(\"latest\",()=>!Ac(e))}function Pc(t){return t instanceof vc}function Ic(t){let e=t;for(;null!=e;){const t=Lc(e);if(Pc(t))return t;e=Fa(e)}return null}function Lc(t){return t?t.__lexicalEditor:null}function zc(t){return L.test(t)?\"rtl\":z.test(t)?\"ltr\":null}function Kc(t){return Ei(t)||t.isToken()}function Bc(t){return Kc(t)||t.isSegmented()}function Rc(t){return Cu(t)&&3===t.nodeType}function Wc(t){return Cu(t)&&9===t.nodeType}function $c(t){let e=t;for(;null!=e;){if(Rc(e))return e;e=e.firstChild}return null}function jc(t,e,n){const o=K[e];if(null!==n&&(t&o)===(n&o))return t;let r=t^o;return\"subscript\"===e?r&=~K.superscript:\"superscript\"===e?r&=~K.subscript:\"lowercase\"===e?(r&=~K.uppercase,r&=~K.capitalize):\"uppercase\"===e?(r&=~K.lowercase,r&=~K.capitalize):\"capitalize\"===e&&(r&=~K.lowercase,r&=~K.uppercase),r}function Uc(t){return ki(t)||Fl(t)||Sl(t)}function Vc(t,e){const n=function(){const t=kc;return kc=null,t}();if(null!=(e=e||n&&n.__key))return void(t.__key=e);Ws(),$s();const o=Vs(),r=js(),i=\"\"+Nc++;r._nodeMap.set(i,t),yl(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 Jc(t){null!==Of(t)&&e(380,t.__key,String(Of(t)));const n=t.getParent();if(null!==n){const e=t.getWritable(),o=n.getWritable(),r=t.getPreviousSibling(),i=t.getNextSibling(),s=null!==i?i.__key:null,l=null!==r?r.__key:null,c=null!==r?r.getWritable():null,a=null!==i?i.getWritable():null;null===r&&(o.__first=s),null===i&&(o.__last=l),null!==c&&(c.__next=s),null!==a&&(a.__prev=l),e.__prev=null,e.__next=null,e.__parent=null,o.__size--}}const Hc=Jc;function qc(t){$s(),Mr(t)&&e(323,t.__key,t.__type);const n=null!==t.__parent?t.__parent:Ef(t)?t.__slotHost:null,o=js(),r=Vs(),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:Ef(t)?t.__slotHost:null}}(n,i,s);const l=t.__key;0===r._dirtyType&&(r._dirtyType=1),yl(t)?s.set(l,!0):r._dirtyLeaves.add(l)}function Yc(t){Ws();const e=Vs(),n=e._compositionKey;if(t!==n){if(e._compositionKey=t,null!==n){const t=Xc(n);null!==t&&t.getWritable()}if(null!==t){const e=Xc(t);null!==e&&e.getWritable()}}}function Gc(){return Rs()?null:Vs()._compositionKey}function Xc(t,e){const n=(e||js())._nodeMap.get(t);return void 0===n?null:n}function Qc(t,e){const n=ta(t,Vs());return void 0!==n?Xc(n,e):null}function Zc(t,e,n){t[`__lexicalKey_${e._key}`]=n}function ta(t,e){return t[`__lexicalKey_${e._key}`]}function ea(t,e){let n=t;for(;null!=n;){const t=Qc(n,e);if(null!==t)return t;n=Fa(n)}return null}function na(t){const e=t._decorators,n=Object.assign({},e);return t._pendingDecorators=n,n}function oa(t){return t.read(()=>ra().getTextContent())}function ra(){return js()._nodeMap.get(\"root\")}function ia(t,e){if(!(Va(t)&&t.isAttached()&&(vl(t)?0===t.getChildrenSize():t.isEmpty())&&(vl(t)||null!==e&&wu(e))))return null;const n=oc();return t.append(n),n}function sa(t){Ws();const e=js();null!==t&&(t.dirty=!0,t.setCachedNodes(null),zi(t)&&Vs()._slotsUsed&&os(t)),e._selection=t}function la(){Ws(),vt(Vs())}function ca(t){const e=function(t,e){let n=t;for(;null!=n;){const t=ta(n,e);if(void 0!==t)return t;n=Fa(n)}return null}(t,Vs());return null===e?null:Xc(e)}function aa(t){return/[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g.test(t)}function ua(t){const e=[];for(let n=t;null!==n;n=n._parentEditor)e.push(n);return e}function fa(){return Math.random().toString(36).replace(/[^a-z]+/g,\"\").substring(0,5)}function da(t){return Rc(t)?t.nodeValue:null}function ha(t,e,n){const o=Qa(Wa(e));if(null===o)return;const r=cu(o,e._rootElement),i=r.anchorNode;let{anchorOffset:s,focusOffset:l}=r;if(null!==i){let e=da(i);const o=ea(i);if(null!==e&&ki(o)){if((e===M||e===F)&&n){const t=n.length;e=n,s=t,l=t}null!==e&&ga(o,e,s,l,t)}}}function ga(t,e,n,o,r){let i=t;if(i.isAttached()&&(r||!i.isDirty())){const s=i.isComposing();if(i.isToken()&&s)return;let l=e;if((s||r)&&(e.endsWith(M)&&(l=e.slice(0,-M.length)),r)){const t=F;let e;for(;-1!==(e=l.indexOf(t));)l=l.slice(0,e)+l.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 c=i.getTextContent();if(r||l!==c){const e=fs();if(\"\"===l){if(Yc(null),p||g||x)i.remove();else{const t=Vs();_a(i,\"\",e),setTimeout(()=>{t.update(()=>{i.isAttached()&&\"\"===i.getTextContent()&&i.remove()})},20)}return}const r=i.getParent(),c=ds(),a=i.getTextContentSize(),u=Gc(),f=i.getKey();if(i.isToken()&&!s||null!==u&&f===u&&!s||zi(c)&&(null!==r&&!r.canInsertTextBefore()&&0===c.anchor.offset||c.anchor.key===t.__key&&0===c.anchor.offset&&!i.canInsertTextBefore()&&!s||c.focus.key===t.__key&&c.focus.offset===a&&!i.canInsertTextAfter()&&!s))return void i.markDirty();if(!zi(e)||null===n||null===o)return void _a(i,l,e);if(e.setTextNodeRange(i,n,i,o),i.isSegmented()){const t=vi(i.getTextContent());i.replace(t),i=t}_a(i,l,e)}}}function _a(t,e,n){if(t.setTextContent(e),zi(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=fd(t,i.offset,\"clamp\"),o=!0)}o&&(n._cachedNodes=null,n._cachedIsBackward=null)}}function pa(t,e){const n=t[J];return n&&e!==a?{...t,ctrlKey:t[n],[n]:t.ctrlKey}:t}function ya(t,e,n){const o=e[n]||!1;return\"any\"===o||o===t[n]}function ma(t,e){return ya(t,e,\"altKey\")&&ya(t,e,\"ctrlKey\")&&ya(t,e,\"shiftKey\")&&ya(t,e,\"metaKey\")}function xa(t,e,n){if(!ma(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 Sa(t){let e=t;for(;null!==e;){const t=e.getParent();if(null===t)return null;if(vl(t))return e;e=t}return null}function Ca(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(De(t),!vl(e))return t;const u=Sa(n.getNode());return yl(u)&&u.isShadowRoot()&&u.is(Sa(o.getNode()))&&(n.set(r,i,s),o.set(l,c,a)),t}function va(t){const e=ra();if(zi(t)){const e=t.anchor,n=t.focus,o=e.getNode();if(vl(o))return e.set(o.getKey(),0,\"element\"),n.set(o.getKey(),o.getChildrenSize(),\"element\"),Ca(t,o),t;const r=o.getTopLevelElementOrThrow(),i=r.getParent();return null===i?(yl(r)&&(e.set(r.getKey(),0,\"element\"),n.set(r.getKey(),r.getChildrenSize(),\"element\"),Ca(t,r)),t):(e.set(i.getKey(),0,\"element\"),n.set(i.getKey(),i.getChildrenSize(),\"element\"),Ca(t,i),t)}{const t=e.select(0,e.getChildrenSize());return sa(Ca(t,e)),t}}function ka(t,e){\"\"===t.getAttribute(e)&&t.removeAttribute(e)}function ba(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=Pd(r);return n[e]=t,t}return r}function Ta(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 Na(t){const e=t.getType(),n=js();if(n._readOnly){const t=zu(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 wa(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 Ea(t,e){const n=t.offset;if(\"element\"===t.type)return wa(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?wa(o.getParentOrThrow(),e,o.getIndexWithinParent()+(e?0:1)):t}}return null}function Oa(t){const e=Wa(t).event,n=e&&e.inputType;return\"insertFromPaste\"===n||\"insertFromPasteAsQuotation\"===n}function Ma(t,e,...n){return rl(t,e,n[0],t)}function Aa(t,n){const o=t._keyToDOMMap.get(n);return void 0===o&&e(75,n),o}function Fa(t){const e=t.assignedSlot||t.parentElement;if(null!==e)return e;const n=t.parentNode;return tu(n)?n.host:null}function Da(t){return Wc(t)?t:Su(t)?t.ownerDocument:null}function Pa(t,e){const n=parseFloat(t);return isFinite(n)?t.endsWith(\"%\")?n*e/100:n:0}function Ia(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+Pa(s.scrollPaddingLeft,r)*a,h=f+(r-Pa(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 S=u?Math.min(0,Math.max(-i,x)):Math.max(0,Math.min(i,x));const C=y*a;return Math.abs(S)<Math.abs(y)&&g+C>=d&&_+C<=h&&(S=0),S===y?0:(e.scrollLeft=S,(e.scrollLeft-y)*a)}function La(t){return Vs()._updateTags.has(t)}function za(t){Ws(),Vs()._updateTags.add(t)}function Ka(t){Ws(),Vs()._deferred.push(t)}function Ba(t,e){let n=t.getParent();for(;null!==n;){if(n.is(e))return!0;n=n.getParent()}return!1}function Ra(t){const e=Da(t);return e?e.defaultView:null}function Wa(t){const n=t._window;return null===n&&e(78),n}function $a(t){return yl(t)&&t.isInline()||Sl(t)&&t.isInline()}function ja(t){let e=t.getLatest();for(;null!==e;){if(null!==Of(e)&&yl(e))return e;const t=e.getParentOrThrow();if(Va(t))return t;e=t}return e}function Ua(t){return yl(t)&&t.isShadowRoot()}function Va(t){return vl(t)||Ua(t)}function Ja(t,e=!1){const n=t.constructor.clone(t,Tc);return Vc(n,null),n.afterCloneFrom(t),e||n.resetOnCopyNodeFrom(t),n}function Ha(t){const n=Vs(),o=t.getType(),r=Oc(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 qa(t,n){!vl(t.getParent())||yl(n)||Sl(n)||e(99)}function Ya(t){const n=Xc(t);return null===n&&e(63,t),n}function Ga(t){if(!t||t.isInline())return!1;if(Sl(t))return!0;if(yl(t)){if(t.isShadowRoot()){const e=t.getParent();return!(yl(e)&&e.isShadowRoot())}return!t.canBeEmpty()}return!1}function Xa(t,e,n){n.style.removeProperty(\"caret-color\"),e._blockCursorElement=null;const o=t.parentElement;null!==o&&o.removeChild(t)}function Qa(t){return r?(t||window).getSelection():null}function Za(t){const e=Ra(t);return e?e.getSelection():null}function tu(t){return vu(t)&&\"host\"in t}const eu=[];function nu(t){const e=t.getRootNode();if(e===t||!tu(e))return eu;const n=[e];let o=e.host;for(;;){const t=o.getRootNode();if(t===o||!tu(t))break;n.push(t),o=t.host}return n}function*ou(t){const e=[t];let n;for(;n=e.pop();){yield*n.querySelectorAll('[data-lexical-editor=\"true\"]');const t=(Wc(n)?n:n.ownerDocument).createTreeWalker(n,NodeFilter.SHOW_ELEMENT);let o;for(;o=t.nextNode();)o.shadowRoot&&e.push(o.shadowRoot)}}function ru(t){return null!==t?t.ownerDocument:document}function iu(){const t=qs();return ru(null!==t?t._rootElement:null)}function su(t,e){if(null===e||\"function\"!=typeof t.getComposedRanges)return null;const n=nu(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 lu(t,e){const n=su(t,e);if(null!==n){const t=uu(n);if(null!==t)return t}return t.rangeCount>0?t.getRangeAt(0):null}function cu(t,e){const n=su(t,e);return null===n?t:fu(n,du(t))}function au(t,e){const n=su(t,e);if(null===n)return{points:t,range:t.rangeCount>0?t.getRangeAt(0):null};const o=uu(n)??(t.rangeCount>0?t.getRangeAt(0):null);return{points:fu(n,du(t)),range:o}}function uu(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 fu(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 du(t){return t.direction}function hu(t){const e=t.getRootNode();return Wc(e)||tu(e)?e.activeElement:null}function gu(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 _u(t){const e=t.target;if(null!==e&&Su(e)&&null!==e.shadowRoot&&\"function\"==typeof t.composedPath){const e=t.composedPath();if(e.length>0)return e[0]}return e}function pu(t,n){let o=t.getChildAtIndex(n);null==o&&(o=t),Va(t)&&e(102);const r=t=>{const n=t.getParentOrThrow(),i=Va(n),s=t!==o||i?Ja(t):t;if(i)return yl(t)&&yl(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 yu(t){return Su(t)&&\"A\"===t.tagName}function mu(t){return Su(t)&&\"TR\"===t.tagName}function xu(t){return Su(t)&&(\"TD\"===t.tagName||\"TH\"===t.tagName)}function Su(t){return Cu(t)&&1===t.nodeType}function Cu(t){return\"object\"==typeof t&&null!==t&&\"nodeType\"in t&&\"number\"==typeof t.nodeType}function vu(t){return Cu(t)&&11===t.nodeType}const ku=/^(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 bu(t){return!(!Su(t)||!t.style.display.startsWith(\"inline\"))||ku.test(t.nodeName)}const Tu=/^(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 Nu(t){return(!Su(t)||!t.style.display.startsWith(\"inline\"))&&Tu.test(t.nodeName)}function wu(t){if(Sl(t)&&!t.isInline())return!0;if(!yl(t)||Va(t))return!1;const e=t.getFirstChild(),n=null===e||Fl(e)||ki(e)||e.isInline();return!t.isInline()&&!1!==t.canBeEmpty()&&n}function Eu(){return Vs()}function Ou(t=Eu()){return t._config.dom||mc}function Mu(t,n,o=Eu()){const r=Ou(o).$getDOMSlot(t,n,o);return yl(t)&&(Du(r)||e(344,t.getKey(),t.getType())),r}function Au(t,e,n,o){const r=t.read(\"latest\",()=>{const o=Xc(e);return null!==o?function(t,e,n=Eu()){const o=Lf(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 Fu(t,e,n){n.style.display=\"none\";const o=t.getElementByKey(e);null!==o&&n.parentElement!==o&&o.insertBefore(n,o.firstChild)}function Du(t){return t instanceof et}function Pu(t,e,n=Eu()){return $c(Mu(t,e,n).element)}const Iu=new WeakMap,Lu=new Map;function zu(t){if(!t._readOnly&&t.isEmpty())return Lu;t._readOnly||e(192);let n=Iu.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),Iu.set(t,n)),n}function Ku(t){const e=t.constructor.clone(t,Tc);return e.afterCloneFrom(t),e}function Bu(t){return(e=Ku(t))[Or]=!0,e;var e}function Ru(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 Wu(t,e){const n=e.getAttribute(\"dir\");return\"ltr\"===n||\"rtl\"===n?t.setDirection(n):t}function $u(t,e){const n=e.style.textAlign;return n&&n in R?t.setFormat(n):t}function ju(t,e){t.__lexicalUnmanaged=!0,e&&void 0!==e.captureSelection&&(t.__lexicalCapturedSelection=e.captureSelection)}function Uu(t){return!0===t.__lexicalUnmanaged}function Vu(t,e=Eu()){const n=e.isEditable();t.contentEditable=n?\"true\":\"false\",n?t.__lexicalEditor=e:delete t.__lexicalEditor}function Ju(t,e){let n=t;for(;null!=n;){if(!0===n.__lexicalCapturedSelection)return!0;if(Su(n)&&n.hasAttribute(\"data-lexical-slot\"))return!1;if(void 0!==ta(n,e))return!1;n=Fa(n)}return!1}function Hu(t,e){return Jt(t,e)&&t[e]!==Fr[e]}const qu=new WeakMap;function Yu(t){const n=qu.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===Fr||t.prototype instanceof Fr)){let n=\"<unknown>\",o=\"<unknown>\";try{n=t.getType()}catch(t){}try{vc.version&&(o=JSON.parse(vc.version))}catch(t){}e(290,t.name,n,o)}return t===xl||t===pl||t===Fr}(t),r=!o&&Hu(t,\"getType\")?t.getType:void 0,i=r&&!(Xu 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:Jt(t.prototype,H),klass:t,ownNodeConfig:s,ownNodeType:l},ownFieldsValidated:!1};qu.set(t,c);try{const n=function(t){const n=t.prototype,o=new Map,{fieldsBaseFirst:r}=rf(t);for(const[i,s]of r){const r=af(t,i,s);if(null===r)continue;if(Nt(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])Jt(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?Qu:[...o.values()]}(t),r=function(t){const n=t.prototype,o=new Map;for(const[r,i]of rf(t).fieldsDerivedFirst){const s=cf(t,r,i);if(null===s)continue;if(Nt(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?lf:[...o.values()]}(t),i=rf(t),a=function(t,e,n){let o,r=t;for(const{klass:e,ownNodeConfig:n}of Sf(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,Gu(Yu(r)))?o:null}(t,0,{getters:r,setters:n});c.compiled={flatStates:i.flatStates,generated:null===a?null:a(i.fields),getters:r,isCompactDefault:df(r),setters:n},function(t,e,n,o){if(!e&&n){if(!Hu(t,\"getType\")){const e=t,o=function(){return this!==e?Fr.getType.call(this):n};o[Xu]=!0,t.getType=o}if(Hu(t,\"clone\")||(t.clone=(e,n)=>{bc(e);const o=new t;return n!==Tc&&o.afterCloneFrom(e),o}),Hu(t,\"importJSON\")||(t.importJSON=o&&o.$importJSON||function(t){return e=>{const n=vf(t);return n.updateFromJSON===Fr.prototype.updateFromJSON?function(t,e){return gf(t.__state||void 0!==e[V]?be(t,e):t,e)}(n,e):n.updateFromJSON(e)}}(t)),!Hu(t,\"importDOM\")&&o){const{importDOM:e}=o;e&&(t.importDOM=()=>e)}}}(t,o,l,s),function(t){for(const{klass:e,ownNodeConfig:n}of Sf(t)){const t=e.prototype;if(Jt(t,\"afterCloneFrom\"))continue;const o=xf(e);if(0===o.length)continue;const r=Object.getPrototypeOf(t),i=n&&void 0!==n.generated?Gu(Yu(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[yf]=!0}}(t)}catch(e){throw qu.delete(t),e}return c}(t)}function Gu(t){const{compiled:n}=t;return void 0===n&&e(422,t.config.klass.name),n}const Xu=Symbol(\"lexical.synthesizedGetType\"),Qu=[];function Zu(t,e,n,o){const r=void 0===n.method?o:n.method,i=rf(t).declaredBy.get(e);if(void 0===i)return n;const s=t.prototype,l=i.prototype;return tf(s,l,r)&&tf(s,l,o)?n:r}function tf(t,e,n){return t[n]===e[n]}function ef(t){return`set${t.charAt(0).toUpperCase()}${t.slice(1)}`}function nf(t){return`get${t.charAt(0).toUpperCase()}${t.slice(1)}`}const of={declaredBy:new Map,fields:new Map,fieldsBaseFirst:[],fieldsDerivedFirst:[],flatStates:[]};function rf(t){const e=Yu(t);return void 0===e.composed&&(e.composed=function(t){const e=[],n=[],o=[];for(const{klass:r,ownNodeConfig:i}of Sf(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?of:{declaredBy:s,fields:i,fieldsBaseFirst:[...i],fieldsDerivedFirst:[...r],flatStates:[...l.values()]}}(t)),e.composed}function sf(t){const{fieldsDerivedFirst:e,flatStates:n}=rf(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 lf=[];function cf(t,e,n){const o=n.getter;if(null===o)return null;const r=void 0===o?nf(e):o;return Nt(r)?Zu(t,e,r,nf(e)):r}function af(t,e,n){const o=n.setter;if(null===o)return null;const r=void 0===o?ef(e):o;return Nt(r)?Zu(t,e,r,ef(e)):r}function uf(t){return t}function ff(t,e){const{defaultValue:n,isEqual:o}=t;return void 0===e||e===n||void 0!==o&&o(e,n)}function df(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&&ff(r,o)}}function hf(t){const{setterTable:e,schema:n}=t,{defaultValue:o}=n;return void 0===e?o:e[String(o)]}function gf(t,e){const n=Yu(t.constructor),{flatStates:o,generated:r,setters:i}=Gu(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=xe(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?uf(t)[r.field]=void 0===r.setterTable?i:Jt(r.setterTable,i)?r.setterTable[i]:hf(r):r.setter.call(t,i)}return t}(s,e,i)}function _f(t){return Yu(t).config}function pf(t){const e=[];for(const n of[t.getter,t.setter])Nt(n)&&\"__proto__\"!==n.field&&!e.includes(n.field)&&e.push(n.field);return e}const yf=\"__lexicalSynthesizedAfterCloneFrom\";function mf(t){const{declaredBy:e,fieldsBaseFirst:n}=rf(t),o=[];for(const[r,i]of n)if(e.get(r)===t)for(const t of pf(i))o.includes(t)||o.push(t);return o}function xf(t){const e=mf(t);if(0===e.length)return e;const n=new Set;for(const{klass:e}of Sf(t))if(e!==t)for(const t of mf(e))n.add(t);return 0===n.size?e:e.filter(t=>!n.has(t))}function*Sf(t){for(let e=t;e&&(e===Fr||Dr(e.prototype));){const t=_f(e),n=t.declaresOwnConfig;yield n?t:{...t,ownNodeConfig:void 0},e=n&&t.ownNodeConfig&&t.ownNodeConfig.extends||Tf(e)}}function Cf(t){const e=new Map,n=new Map;for(const o of t){const{ownNodeType:t}=_f(o);t&&(n.set(t,o),e.set(t,new Set))}for(const[t,o]of n)for(const{ownNodeType:n}of Sf(o)){const o=n&&e.get(n);o&&o.add(t)}return e}function vf(t){const e=Eu();Ws();const n=e.resolveRegisteredNodeAfterReplacements(e.getRegisteredNode(t)),o=new n.klass;return null===n.replace?o:Ha(o)}const kf=(t,e)=>{let n=t;for(;null!=n&&!vl(n);){if(e(n))return n;n=n.getParent()}return null};function bf(t,n){const o=[];let r=t.__first;for(;null!==r;){const t=null===n?Xc(r):n.get(r);null==t&&e(174),o.push(r),r=t.__next}return o}function Tf(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}const Nf=new Map;function wf(t){return yl(t)||Sl(t)}function Ef(t){return yl(t)||Sl(t)}function Of(t){const e=t.getLatest();return Ef(e)?e.__slotHost:null}function Mf(t){const n=Of(t);if(null===n)return null;const o=Xc(n);return yl(o)||Sl(o)||e(370),o}function Af(t){const e=Mf(t);if(null===e)return null;const n=t.getLatest().__key;for(const[t,o]of Pf(e))if(o===n)return t;return null}function Ff(t){let e=t.getLatest();for(;null!==e;){if(null!==Of(e))return e;e=e.getParent()}return null}function Df(t){if(null===t)return null;const e=zi(t)?t.anchor.getNode():t.getNodes()[0]??null;return null===e?null:Ff(e)}function Pf(t){const e=t.getLatest();return wf(e)&&null!==e.__slots?e.__slots:Nf}function If(t){return Array.from(Pf(t).keys())}function Lf(t,e){const n=Pf(t).get(e);return void 0===n?null:Xc(n)}const zf=[\"__proto__\",\"constructor\",\"prototype\"],Kf=Symbol(\"slotMapOwner\");function Bf(t){let e=t.__slots;return null!==e&&e[Kf]===t||(e=new Map(e),e[Kf]=t,t.__slots=e),e}const Rf=new WeakMap,Wf=[];function $f(t){for(const{ownNodeConfig:e}of Sf(t)){const t=e&&e.slots;if(t)return t}return Wf}function jf(t){let e=\"\";for(const n of If(t)){const o=Lf(t,n);null!==o&&(e+=o.getTextContent())}return e}function Uf(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 Vf(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;(!yl(o)&&!Sl(o)||o.isInline())&&e(374,o.__key);const i=t.getWritable(),s=Bf(i),l=s.get(n);void 0!==l&&Hf(l);const c=o.getWritable(),a=Mf(c);if(null!==a){const t=Af(c);null!==t&&Bf(a.getWritable()).delete(t),c.__slotHost=null}return Jc(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=Rf.get(t);if(void 0===n){const o=$f(t),r=new Map;for(const n of o)zf.includes(n)&&e(371,t.name,n),r.has(n)&&e(372,t.name,n),r.set(n,r.size);n=r,Rf.set(t,n)}return n}(t.constructor);let r=null,i=!0;for(const t of n.keys()){if(null!==r&&Uf(r,t,o)>0){i=!1;break}r=t}if(i)return;const s=Array.from(n).sort(([t],[e])=>Uf(t,e,o));n.clear();for(const[t,e]of s)n.set(t,e)}(i),Vs()._slotsUsed=!0,js()._slotsUsed=!0,i}function Jf(t,e){const n=t.getWritable();if(null===n.__slots)return n;const o=n.__slots.get(e);return void 0!==o&&(Hf(o),Bf(n).delete(e)),n}function Hf(t){const n=Xc(t);if(null===n)return;const o=n.getWritable();Ef(o)||e(377,t),o.__slotHost=null,o.remove()}const qf={next:\"previous\",previous:\"next\"};class Yf{origin;constructor(t){this.origin=t}[Symbol.iterator](){return kd({hasNext:rd,initial:this.getAdjacentCaret(),map:t=>t,step:t=>t.getAdjacentCaret()})}getAdjacentCaret(){return ad(this.getNodeAtCaret(),this.direction)}getSiblingCaret(){return ad(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=ad(t,this.direction)}for(const t of l.values())t.remove();return this}}class Gf extends Yf{type=\"child\";getLatest(){const t=this.origin.getLatest();return t===this.origin?this:hd(t,this.direction)}getParentCaret(t=\"root\"){return ad(Zf(this.getParentAtCaret(),t),this.direction)}getFlipped(){const t=Qf(this.direction);return ad(this.getNodeAtCaret(),t)||hd(this.origin,t)}getParentAtCaret(){return this.origin}getChildCaret(){return this}isSameNodeCaret(t){return t instanceof Gf&&this.direction===t.direction&&this.origin.is(t.origin)}isSamePointCaret(t){return this.isSameNodeCaret(t)}}const Xf={root:vl,shadowRoot:Va};function Qf(t){return qf[t]}function Zf(t,e=\"root\"){return null===t||Xf[e](t)?null:null===Of(t)?t:null}class td extends Yf{type=\"sibling\";getLatest(){const t=this.origin.getLatest();return t===this.origin?this:ad(t,this.direction)}getSiblingCaret(){return this}getParentAtCaret(){return this.origin.getParent()}getChildCaret(){return yl(this.origin)?hd(this.origin,this.direction):null}getParentCaret(t=\"root\"){return ad(Zf(this.getParentAtCaret(),t),this.direction)}getFlipped(){const t=Qf(this.direction);return ad(this.getNodeAtCaret(),t)||hd(this.origin.getParentOrThrow(),t)}isSamePointCaret(t){return t instanceof td&&this.direction===t.direction&&this.origin.is(t.origin)}isSameNodeCaret(t){return(t instanceof td||t instanceof ed)&&this.direction===t.direction&&this.origin.is(t.origin)}}class ed extends Yf{type=\"text\";offset;constructor(t,e){super(t),this.offset=e}getLatest(){const t=this.origin.getLatest();return t===this.origin?this:ud(t,this.direction,this.offset)}getParentAtCaret(){return this.origin.getParent()}getChildCaret(){return null}getParentCaret(t=\"root\"){return ad(Zf(this.getParentAtCaret(),t),this.direction)}getFlipped(){return ud(this.origin,Qf(this.direction),this.offset)}isSamePointCaret(t){return t instanceof ed&&this.direction===t.direction&&this.origin.is(t.origin)&&this.offset===t.offset}isSameNodeCaret(t){return(t instanceof td||t instanceof ed)&&this.direction===t.direction&&this.origin.is(t.origin)}getSiblingCaret(){return ad(this.origin,this.direction)}}function nd(t){return t instanceof ed}function od(t){return t instanceof Yf}function rd(t){return t instanceof td}function id(t){return t instanceof Gf}const sd={next:class extends ed{direction=\"next\";getNodeAtCaret(){return this.origin.getNextSibling()}insert(t){return this.origin.insertAfter(t),this}},previous:class extends ed{direction=\"previous\";getNodeAtCaret(){return this.origin.getPreviousSibling()}insert(t){return this.origin.insertBefore(t),this}}},ld={next:class extends td{direction=\"next\";getNodeAtCaret(){return this.origin.getNextSibling()}insert(t){return this.origin.insertAfter(t),this}},previous:class extends td{direction=\"previous\";getNodeAtCaret(){return this.origin.getPreviousSibling()}insert(t){return this.origin.insertBefore(t),this}}},cd={next:class extends Gf{direction=\"next\";getNodeAtCaret(){return this.origin.getFirstChild()}insert(t){return this.origin.splice(0,0,[t]),this}},previous:class extends Gf{direction=\"previous\";getNodeAtCaret(){return this.origin.getLastChild()}insert(t){return this.origin.splice(this.origin.getChildrenSize(),0,[t]),this}}};function ad(t,e){return t?new ld[e](t):null}function ud(t,e,n){return t?new sd[e](t,fd(t,n)):null}function fd(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 dd(t,e){return new yd(t,e)}function hd(t,e){return yl(t)?new cd[e](t):null}function gd(t){return t&&t.getChildCaret()||t}function _d(t){return t&&gd(t.getAdjacentCaret())}class pd{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 pd(t,e,this.direction)}isCollapsed(){return this.anchor.isSamePointCaret(this.focus)}getTextSlices(){const t=t=>{const e=this[t].getLatest();return nd(e)?function(t,e){const{direction:n,origin:o}=t;return dd(t,fd(o,\"focus\"===e?Qf(n):n)-t.offset)}(e,t):null},e=t(\"anchor\"),n=t(\"focus\");if(e&&n){const{caret:t}=e,{caret:o}=n;if(t.isSameNodeCaret(o))return[dd(t,o.offset-t.offset),null]}return[e,n]}iterNodeCarets(t=\"root\"){const e=nd(this.anchor)?this.anchor.getSiblingCaret():this.anchor.getLatest(),n=this.focus.getLatest(),o=nd(n),r=e=>e.isSameNodeCaret(n)?null:_d(e)||e.getParentCaret(t);return kd({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 yd{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 ud(t.setTextContent(r.slice(0,n)+r.slice(o)),e,n)}}function md(t){return t instanceof yd}function xd(t,e){return t.direction===e?t:t.getFlipped()}function Sd(t){return vd(t,xd(hd(ra(),Qf(t.direction)),t.direction))}function Cd(t){return vd(t,t)}function vd(t,n){return t.direction!==n.direction&&e(265),new pd(t,n,t.direction)}function kd(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 bd(t,n){const o=Ed(t.origin,n.origin);switch(null===o&&e(275,t.origin.getKey(),n.origin.getKey()),o.type){case\"same\":{const e=\"text\"===t.type,o=\"text\"===n.type;return e&&o?function(t,e){return Math.sign(t-e)}(t.offset,n.offset):t.type===n.type?0:e?-1:o?1:\"child\"===t.type?-1:1}case\"ancestor\":return\"child\"===t.type?-1:1;case\"descendant\":return\"child\"===n.type?1:-1;case\"branch\":return Td(o)}}function Td(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 Nd(t,e){return e.is(t)}function wd(t){return yl(t)?[t.getLatest(),null]:[t.getParent(),t.getLatest()]}function Ed(t,n){if(t.is(n))return{commonAncestor:t,type:\"same\"};const o=new Map;for(let[e,n]=wd(t);e;n=e,e=e.getParent())o.set(e,n);for(let[r,i]=wd(n);r;i=r,r=r.getParent()){const s=o.get(r);if(void 0!==s)return null===s?(Nd(t,r)||e(276),{commonAncestor:r,type:\"ancestor\"}):null===i?(Nd(n,r)||e(277),{commonAncestor:r,type:\"descendant\"}):((yl(s)||Nd(t,s))&&(yl(i)||Nd(n,i))&&r.is(s.getParent())&&r.is(i.getParent())||e(278),{a:s,b:i,commonAncestor:r,type:\"branch\"})}return null}function Od(t){return t}function Md(...t){return t}function Ad(...t){return t}function Fd(t){return t}function Dd(t,e){if(!e||t===e)return t;for(const n in e)if(t[n]!==e[n])return{...t,...e};return t}function Pd(...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 Id(t,...e){const n=Pd(...e);n.length>0&&t.classList.add(...n)}function Ld(t,...e){const n=Pd(...e);n.length>0&&t.classList.remove(...n)}function zd(...t){return()=>{for(let e=t.length-1;e>=0;e--)t[e]();t.length=0}}function Kd(t,e,n){return zd(...Object.entries(e).map(([e,o])=>Wo(t,e,o,n)))}export{za as $addUpdateTag,Ha as $applyNodeReplacement,Us as $assumeActiveEditor,Ll as $caretFromPoint,Rl as $caretRangeFromSelection,Ku as $cloneWithProperties,Bu as $cloneWithPropertiesEphemeral,bd as $comparePointCaretNext,Ja as $copyNode,vf as $create,bf as $createChildrenArray,Al as $createLineBreakNode,cs as $createNodeSelection,oc as $createParagraphNode,Mi as $createPoint,ls as $createRangeSelection,as as $createRangeSelectionFromDom,wi as $createTabNode,vi as $createTextNode,dt as $exportNodeJSON,Sd as $extendCaretToRange,kf as $findMatchingParent,ll as $flushSyncAfterUpdate,$i as $formatText,Js as $fullReconcile,ks as $generateNodesFromRawText,_d as $getAdjacentChildCaret,Ea as $getAdjacentNode,Yl as $getAdjacentSiblingOrParentSiblingCaret,xd as $getCaretInDirection,vd as $getCaretRange,Hl as $getCaretRangeInDirection,Ui as $getCharacterOffsets,hd as $getChildCaret,ql as $getChildCaretAtIndex,gd as $getChildCaretOrSelf,Cd as $getCollapsedCaretRange,Ed as $getCommonAncestor,Td as $getCommonAncestorResultBranchOrder,Mu as $getDOMSlot,Pu as $getDOMTextNode,iu as $getDocument,Eu as $getEditor,Ou as $getEditorDOMRenderConfig,ea as $getNearestNodeFromDOMNode,ja as $getNearestRootOrShadowRoot,Xc as $getNodeByKey,Ya as $getNodeByKeyOrThrow,Qc as $getNodeFromDOMNode,ds as $getPreviousSelection,ra as $getRoot,fs as $getSelection,Df as $getSelectionSlotFrame,ad as $getSiblingCaret,Lf as $getSlot,Ff as $getSlotFrame,Mf as $getSlotHost,Af as $getSlotNameWithinHost,If as $getSlotNames,ye as $getState,me as $getStateChange,bs as $getTextContent,fd as $getTextNodeOffset,ud as $getTextPointCaret,dd as $getTextPointCaretSlice,ke as $getWritableNodeState,Ba as $hasAncestor,La as $hasUpdateTag,Zl as $insertNodeToNearestRootAtCaret,Cs as $insertNodes,is as $isBlockElementNode,tc as $isBlockFullySelected,id as $isChildCaret,ft as $isCompactExport,Sl as $isDecoratorNode,Nl as $isEditorState,Du as $isElementDOMSlot,yl as $isElementNode,Jl as $isExtendableTextPointCaret,$a as $isInlineElementOrDecoratorNode,di as $isInlineFormattable,Uc as $isLeafNode,Dr as $isLexicalNode,Fl as $isLineBreakNode,od as $isNodeCaret,Bi as $isNodeSelection,rc as $isParagraphNode,zi as $isRangeSelection,vl as $isRootNode,Va as $isRootOrShadowRoot,Ac as $isSelectionCapturedInDecoratorInput,Ua as $isShadowRootNode,rd as $isSiblingCaret,Ef as $isSlotChild,wf as $isSlotHost,Ei as $isTabNode,ki as $isTextNode,nd as $isTextPointCaret,md as $isTextPointCaretSlice,Bc as $isTokenOrSegmented,Kc as $isTokenOrTab,Vu as $markSlotEditable,Ga as $needsBlockCursorBeside,Na as $nodesOfType,Vl as $normalizeCaret,De as $normalizeSelection__EXPERIMENTAL,Ka as $onUpdate,Qs as $parseSerializedNode,Jc as $removeFromParent,Jf as $removeSlot,Ul as $removeTextFromCaretRange,Wl as $rewindSiblingCaret,va as $selectAll,Yc as $setCompositionKey,Wu as $setDirectionFromDOM,$u as $setFormatFromDOM,zl as $setPointFromCaret,sa as $setSelection,Kl as $setSelectionFromCaretRange,Vf as $setSlot,xe as $setState,Wi as $setTextFormat,Ql as $splitAtPointCaretNext,pu as $splitNode,Ss as $updateDOMSelection,Bl as $updateRangeSelectionFromCaretRange,ut as $withCompactExport,El as ArtificialNode__DO_NOT_USE,Bn as BEFORE_INPUT_COMMAND,Ao as BLUR_COMMAND,Eo as CAN_REDO_COMMAND,Oo as CAN_UNDO_COMMAND,d as CAN_USE_BEFORE_INPUT,r as CAN_USE_DOM,No as CLEAR_EDITOR_COMMAND,wo as CLEAR_HISTORY_COMMAND,Kn as CLICK_COMMAND,Br as COLLABORATION_TAG,_c as COMMAND_PRIORITY_BEFORE_CRITICAL,fc as COMMAND_PRIORITY_BEFORE_EDITOR,gc as COMMAND_PRIORITY_BEFORE_HIGH,dc as COMMAND_PRIORITY_BEFORE_LOW,hc as COMMAND_PRIORITY_BEFORE_NORMAL,uc as COMMAND_PRIORITY_CRITICAL,sc as COMMAND_PRIORITY_EDITOR,ac as COMMAND_PRIORITY_HIGH,lc as COMMAND_PRIORITY_LOW,cc as COMMAND_PRIORITY_NORMAL,$n as COMPOSITION_END_COMMAND,Vr as COMPOSITION_END_TAG,Wn as COMPOSITION_START_COMMAND,Ur as COMPOSITION_START_TAG,Jn as CONTROLLED_TEXT_INSERTION_COMMAND,Io as CONTROL_OR_ALT,Po as CONTROL_OR_META,J as CONTROL_OR_OTHER_KEY,ko as COPY_COMMAND,bo as CUT_COMMAND,Kr as CUT_TAG,mc as DEFAULT_EDITOR_DOM_CONFIG,jn as DELETE_CHARACTER_COMMAND,Gn as DELETE_LINE_COMMAND,Yn as DELETE_WORD_COMMAND,vo as DRAGEND_COMMAND,Co as DRAGOVER_COMMAND,So as DRAGSTART_COMMAND,mo as DROP_COMMAND,xl as DecoratorNode,pl as ElementNode,Mo as FOCUS_COMMAND,xo as FORMAT_ELEMENT_COMMAND,Xn as FORMAT_TEXT_COMMAND,Pr as HISTORIC_TAG,Lr as HISTORY_MERGE_TAG,Ir as HISTORY_PUSH_TAG,po as INDENT_CONTENT_COMMAND,Rn as INPUT_COMMAND,Un as INSERT_LINE_BREAK_COMMAND,Vn as INSERT_PARAGRAPH_COMMAND,_o as INSERT_TAB_COMMAND,Vi as INTERNAL_$expandSelectionToWholeDocument,wu as INTERNAL_$isBlock,O as IS_ALL_FORMATTING,_ as IS_ANDROID,m as IS_ANDROID_CHROME,a as IS_APPLE,x as IS_APPLE_WEBKIT,S as IS_BOLD,y as IS_CHROME,b as IS_CODE,u as IS_FIREFOX,w as IS_HIGHLIGHT,g as IS_IOS,C as IS_ITALIC,p as IS_SAFARI,v as IS_STRIKETHROUGH,T as IS_SUBSCRIPT,N as IS_SUPERSCRIPT,k as IS_UNDERLINE,lo as KEY_ARROW_DOWN_COMMAND,ro as KEY_ARROW_LEFT_COMMAND,no as KEY_ARROW_RIGHT_COMMAND,so as KEY_ARROW_UP_COMMAND,uo as KEY_BACKSPACE_COMMAND,ho as KEY_DELETE_COMMAND,eo as KEY_DOWN_COMMAND,co as KEY_ENTER_COMMAND,fo as KEY_ESCAPE_COMMAND,Fo as KEY_MODIFIER_COMMAND,ao as KEY_SPACE_COMMAND,go as KEY_TAB_COMMAND,Ol as LineBreakNode,oo as MOVE_TO_END,io as MOVE_TO_START,he as NODE_STATE_DIRECT,V as NODE_STATE_KEY,ge as NODE_STATE_LATEST,yo as OUTDENT_CONTENT_COMMAND,Hn as PASTE_COMMAND,zr as PASTE_TAG,ec as ParagraphNode,to as REDO_COMMAND,qn as REMOVE_TEXT_COMMAND,Cl as RootNode,Ln as SELECTION_CHANGE_COMMAND,zn as SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,To as SELECT_ALL_COMMAND,Qn as SET_TEXT_FORMAT_COMMAND,Rr as SKIP_COLLAB_TAG,$r as SKIP_DOM_SELECTION_TAG,Wr as SKIP_SCROLL_INTO_VIEW_TAG,jr as SKIP_SELECTION_FOCUS_TAG,K as TEXT_TYPE_TO_FORMAT,Ni as TabNode,hi as TextNode,Zn as UNDO_COMMAND,Id as addClassNamesToElement,Ot as aliasTableOf,ie as aliasedValue,ce as arrayValue,Qt as booleanValue,Er as buildImportMap,Bo as compileKeyboardShortcuts,Md as configExtension,In as createCommand,xc as createEditor,Ro as createRefCountedRegistry,Se as createSharedNodeState,pe as createState,Ad as declarePeerDependency,It as declaredAccepts,Od as defineExtension,Zt as enumValue,ou as findAllLexicalElementsDeep,Qf as flipDirection,hu as getActiveElement,gu as getActiveElementDeep,_u as getComposedEventTarget,sf as getComposedSchemaFields,su as getComposedStaticRange,Da as getDOMOwnerDocument,Qa as getDOMSelection,Za as getDOMSelectionFromTarget,cu as getDOMSelectionPoints,lu as getDOMSelectionRange,au as getDOMSelectionRangeAndPoints,nu as getDOMShadowRoots,$c as getDOMTextNode,$f as getDeclaredSlots,Lc as getEditorPropertyFromDOMNode,Ic as getNearestEditorFromDOMNode,Fa as getParentElement,Oc as getRegisteredNode,Ec as getRegisteredNodeOrThrow,Cf as getRegisteredSubtypeMap,ru as getRootOwnerDocument,_f as getStaticNodeConfig,ei as getStyleObjectFromCSS,zc as getTextDirection,yc as getTransformSetFromKlass,wt as getterTableOf,Nu as isBlockDomNode,Rs as isCurrentlyReadOnlyMode,Ju as isDOMCapturingSelection,Wc as isDOMDocumentNode,Cu as isDOMNode,tu as isDOMShadowRoot,Rc as isDOMTextNode,Uu as isDOMUnmanaged,vu as isDocumentFragment,xa as isExactShortcutMatch,yu as isHTMLAnchorElement,Su as isHTMLElement,xu as isHTMLTableCellElement,mu as isHTMLTableRowElement,bu as isInlineDomNode,Pl as isLastChildInBlockNode,Pc as isLexicalEditor,ma as isModifierMatch,Dl as isOnlyChildInBlockNode,Nt as isSchemaField,Fc as isSelectionCapturedInDecoratorInput,Dc as isSelectionWithinEditor,Sf as iterStaticNodeConfigChain,pa as keyboardEventMaskForPlatform,kd as makeStepwiseIterator,zd as mergeRegister,Au as mountSlotContainer,re as nodeSchema,Pd as normalizeClassNames,te as nullable,Xt as numberValue,ae as objectValue,ee as optional,le as rawValue,Wo as registerEventListener,Kd as registerEventListeners,Ld as removeClassNamesFromElement,Hc as removeFromParent,wc as resetRandomKey,Fd as safeCast,ri as setDOMStyleFromCSS,oi as setDOMStyleObject,ju as setDOMUnmanaged,Ru as setNodeIndentFromDOM,Mt as setterDefaultOf,Et as setterTableOf,Dd as shallowMergeConfig,br as stopLexicalPropagation,Yt as stringValue,jc as toggleTextFormatType,vs as tokenizeRawText,se as transformValue,oe as unionValue,Fu as unmountSlotContainer,fe as withAccessors,ue 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,$isTextNode as t,$getEditor as n,$isRootNode as o,$getSelection as r,$isRangeSelection as l,$caretRangeFromSelection as i,$isTokenOrSegmented as s,$isElementNode as c,$getCharacterOffsets as f,$cloneWithPropertiesEphemeral as u,$getNodeByKey as g,$getPreviousSelection as a,$createTextNode as d,getStyleObjectFromCSS as p,$caretFromPoint as h,$isExtendableTextPointCaret as y,$findMatchingParent as m,INTERNAL_$isBlock as S,flipDirection as x,$getSlotHost as C,$isTextPointCaret as N,$isTabNode as T,$extendCaretToRange as v,$isChildCaret as w,$isDecoratorNode as P,$getSlotFrame as K,$isRootOrShadowRoot as E,$hasAncestor as I,$isLeafNode as b,$setSelection as B}from\"lexical\";export{$cloneWithProperties,$selectAll}from\"lexical\";function k(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 F(e){return()=>{}}function z(e){let t=e;for(;null!=t;){if(t.nodeType===Node.TEXT_NODE)return t;t=t.firstChild}return null}function A(e){const t=e.parentNode;if(null==t)throw new Error(\"Should never happen\");return[t,Array.from(t.childNodes).indexOf(e)]}function R(n,o,r,l,i){const s=o.getKey(),c=l.getKey(),f=e(n.getRootElement()).createRange();let u=n.getElementByKey(s),g=n.getElementByKey(c),a=r,d=i;if(t(o)&&(u=z(u)),t(l)&&(g=z(g)),void 0===o||void 0===l||null===u||null===g)return null;\"BR\"===u.nodeName&&([u,a]=A(u)),\"BR\"===g.nodeName&&([g,d]=A(g));const p=u.firstChild;u===g&&null!=p&&\"BR\"===p.nodeName&&0===a&&0===d&&(d=1);try{f.setStart(u,a),f.setEnd(g,d)}catch(e){return null}return!f.collapsed||a===d&&s===c||(f.setStart(g,d),f.setEnd(u,a)),f}function O(e,t){const n=e.getRootElement();if(null===n)return[];const o=n.getBoundingClientRect(),r=getComputedStyle(n),l=parseFloat(r.paddingLeft)+parseFloat(r.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,r=t.width+l===o.width;n||r?(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 L(e){const t=n().getElementByKey(e.getKey());if(null===t)return null;const o=t.ownerDocument.defaultView;return null===o?null:o.getComputedStyle(t)}function M(e){const t=o(e)?e:e.getParent();return t&&L(t)}function $(e){const t=M(e);return null!==t&&\"rtl\"===t.direction}function D(e,t,n=\"self\"){const o=e.getStartEndPoints();if(t.isSelected(e)&&!s(t)&&null!==o){const[r,l]=o,i=e.isBackward(),s=r.getNode(),c=l.getNode(),g=t.is(s),a=t.is(c);if(g||a){const[o,r]=f(e),l=s.is(c),g=t.is(i?c:s),a=t.is(i?s:c);let d,p=0;l?(p=o>r?r:o,d=o>r?o:r):g?(p=i?r:o,d=void 0):a&&(p=0,d=i?o:r);const h=t.__text.slice(p,d);h!==t.__text&&(\"clone\"===n&&(t=u(t)),t.__text=h)}}return t}function U(e){if(\"text\"===e.type)return e.offset===e.getNode().getTextContentSize();const t=e.getNode();return c(t)||k(177),e.offset===t.getChildrenSize()}function j(e,n,r){let i=n.getNode(),s=r;if(c(i)){const e=i.getDescendantByIndex(n.offset);null!==e&&(i=e)}for(;s>0&&null!==i;){if(c(i)){const e=i.getLastDescendant();null!==e&&(i=e)}let r=i.getPreviousSibling(),f=0;if(null===r){let e=i.getParentOrThrow(),t=e.getPreviousSibling();for(;null===t;){if(e=e.getParent(),null===e){r=null;break}t=e.getPreviousSibling()}null!==e&&(f=e.isInline()?0:2,r=t)}let u=i.getTextContent();\"\"===u&&c(i)&&!i.isInline()&&(u=\"\\n\\n\");const p=u.length;if(!t(i)||s>=p){const e=i.getParent();i.remove(),null==e||0!==e.getChildrenSize()||o(e)||e.remove(),s-=p+f,i=r}else{const o=i.getKey(),r=e.read(\"latest\",()=>{const e=g(o);return t(e)&&e.isSimpleText()?e.getTextContent():null}),c=p-s,f=u.slice(0,c);if(null!==r&&r!==u){const e=a();let t=i;if(i.isSimpleText())i.setTextContent(r);else{const e=d(r);i.replace(e),t=e}if(l(e)&&e.isCollapsed()){const n=e.anchor.offset;t.select(n,n)}}else if(i.isSimpleText()){const e=n.key===o;let t=n.offset;t<s&&(t=p);const r=e?t-s:0,l=e?t:c;if(e&&0===r){const[e]=i.splitText(r,l);e.remove()}else{const[,e]=i.splitText(r,l);e.remove()}}else{const e=d(f);i.replace(e)}s=0}}}const H=/* @__PURE__ */F();function V(e,n){(l(e)?e.isCollapsed():t(e)||c(e))||k(280);const o=p(l(e)?e.style:t(e)?e.getStyle():e.getTextStyle()),r=_(Object.entries(n).reduce((t,[n,r])=>(\"function\"==typeof r?t[n]=r(o[n],e):null===r?delete t[n]:t[n]=r,t),{...o}));l(e)||t(e)?e.setStyle(r):e.setTextStyle(r)}function W(e,t){const n=new Set;if(l(e)&&e.isCollapsed()){V(e,t);const o=e.anchor.getNode();c(o)&&o.isEmpty()&&(n.add(o.getKey()),V(o,t))}X(e=>{V(e,t)});const o=e.getNodes();if(o.length>0)for(const e of o){if(!c(e)||!e.canBeEmpty()||0!==e.getChildrenSize())continue;const o=e.getKey();n.has(o)||(n.add(o),V(e,t))}}function X(e){const n=r();if(!n)return;const o=new Map,c=e=>o.get(e.getKey())||[0,e.getTextContentSize()];if(l(n))for(const e of i(n).getTextSlices())e&&o.set(e.caret.origin.getKey(),e.getSliceIndices());const f=n.getNodes();for(const n of f){if(!t(n)||!n.canHaveFormat())continue;const[o,r]=c(n);r!==o&&(s(n)||0===o&&r===n.getTextContentSize()?e(n):e(n.splitText(o,r)[0===o?0:1]))}l(n)&&\"text\"===n.anchor.type&&\"text\"===n.focus.type&&n.anchor.key===n.focus.key&&q(n)}function q(e){if(e.isBackward()){const{anchor:t,focus:n}=e,{key:o,offset:r,type:l}=t;t.set(n.key,n.offset,n.type),n.set(o,r,l)}}function G(e,t){const n=e.getFormatType(),o=e.getIndent();n!==t.getFormatType()&&t.setFormat(n),o!==t.getIndent()&&t.setIndent(o)}function J(e,t,n){let o=h(e,n);if(y(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 Q(e,t,n=G){if(!e)return;const o=e.getStartEndPoints();let r=!1,l=null;const i=new Map;if(o){const[t,n]=o,s=m(t.getNode(),S);l=m(n.getNode(),S);const f=e.isBackward()?\"previous\":\"next\";r=c(l)&&!l.is(s)&&function(e,t,n){const o=e.getNode();return(!c(o)||!o.isEmpty())&&J(e,t,n)}(n,l,x(f)),c(s)&&i.set(s.getKey(),s),c(l)&&!r&&i.set(l.getKey(),l)}for(const t of e.getNodes())if(c(t)&&S(t)){if(r&&t.is(l))continue;i.set(t.getKey(),t)}else if(!o){const e=m(t,S);c(e)&&i.set(e.getKey(),e)}for(const e of i.values()){if(null!==C(e))continue;const o=t();n(e,o),e.replace(o,!0)}}function Y(e){return e.getNode().isAttached()}function Z(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 ee(e,t,n=null){const o=e.getStartEndPoints(),r=o?o[0]:null,l=e.getNodes(),i=l.length;if(null!==r){const e=K(r.getNode());if(null!==e&&!E(e))return}if(null!==r&&(0===i||1===i&&\"element\"===r.type&&0===r.getNode().getChildrenSize())){const e=\"text\"===r.type?r.getNode().getParentOrThrow():r.getNode(),o=e.getChildren();let l=t();return l.setFormat(e.getFormatType()),l.setIndent(e.getIndent()),o.forEach(e=>l.append(e)),n&&(l=n.append(l)),void e.replace(l)}let s=null,c=[];for(let o=0;o<i;o++){const r=l[o];E(r)?(te(e,c,c.length,t,n),c=[],s=r):null===s||null!==s&&I(r,s)?c.push(r):(te(e,c,c.length,t,n),c=[r])}te(e,c,c.length,t,n)}function te(e,t,n,o,r=null){if(0===t.length)return;const i=t[0],s=new Map,f=[],u=c(i)?i:i.getParentOrThrow();let g=u.isInline()?u.getParentOrThrow():u,d=!1;for(;null!==g;){const e=g.getPreviousSibling();if(null!==e){g=e,d=!0;break}if(g=g.getParentOrThrow(),E(g))break}const p=new Set;for(let e=0;e<n;e++){const n=t[e];c(n)&&0===n.getChildrenSize()&&p.add(n.getKey())}const h=new Set;for(let e=0;e<n;e++){const n=t[e];let r=n.getParent();if(null!==r&&r.isInline()&&(r=r.getParent()),null!==r&&b(n)&&!h.has(n.getKey())){const e=r.getKey();if(void 0===s.get(e)){const t=o();t.setFormat(r.getFormatType()),t.setIndent(r.getIndent()),f.push(t),s.set(e,t);const n=r.getChildren();t.splice(t.getChildrenSize(),0,n);for(const e of n)if(h.add(e.getKey()),c(e))for(const t of e.getChildrenKeys())h.add(t);Z(r)}}else if(p.has(n.getKey())){c(n)||k(179);const e=o();e.setFormat(n.getFormatType()),e.setIndent(n.getIndent()),f.push(e),n.remove(!0)}}if(null!==r)for(let e=0;e<f.length;e++){const t=f[e];r.append(t)}let y=null;if(E(g))if(d)if(null!==r)g.insertAfter(r);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(c(t)&&(g=t),null===t)if(r)e.append(r);else for(let t=0;t<f.length;t++){const n=f[t];e.append(n),y=n}else if(null!==r)t.insertBefore(r);else for(let e=0;e<f.length;e++){const n=f[e];t.insertBefore(n),y=n}}else if(r)g.insertAfter(r);else for(let e=f.length-1;e>=0;e--){const t=f[e];g.insertAfter(t),y=t}const m=a();l(m)&&Y(m.anchor)&&Y(m.focus)?B(m.clone()):null!==y?y.selectEnd():e.dirty=!0}function ne(e){const t=oe(e);return null!==t&&\"vertical-rl\"===t.writingMode}function oe(e){const t=e.anchor.getNode();return c(t)?L(t):M(t)}function re(e,n){let o=ne(e)?!n:n;ie(e)&&(o=!o);const r=h(e.focus,o?\"previous\":\"next\");if(y(r))return!1;if(N(r)&&!T(r.origin)&&r.origin.isUnmergeable()){const e=r.getNodeAtCaret();if(t(e)&&!T(e))return!0}for(const e of v(r)){if(w(e))return!e.origin.isInline();if(!c(e.origin)){if(P(e.origin))return!0;break}}return!1}function le(e,t,n,o){e.modify(t?\"extend\":\"move\",n,o)}function ie(e){const t=oe(e);return null!==t&&\"rtl\"===t.direction}function se(e,t,n){const o=ie(e);let r;r=ne(e)||o?!n:n,le(e,t,r,\"character\")}function ce(e,t,n){const o=e.getStyle(),r=p(o);return null!==r&&r[t]||n}function fe(e,n,o=\"\"){let r=null;const i=e.getNodes();let s,c;if(l(e)){if(e.isCollapsed()&&\"\"!==e.style){const t=p(e.style);if(null!==t&&n in t)return t[n]}const{anchor:o,focus:r}=e,l=e.isBackward(),i=l?r.getNode():o.getNode(),f=l?o.getNode():r.getNode(),u=l?r.offset:o.offset,g=l?o.offset:r.offset;t(i)&&u===i.getTextContentSize()&&(s=i),0===g&&(c=f)}for(let e=0;e<i.length;e++){const l=i[e];if(t(l)&&!l.is(0===e?s:c)){const e=ce(l,n,o);if(null===r)r=e;else if(r!==e){r=\"\";break}}}return null===r?o:r}const ue=p,ge=j;export{H as $addNodeStyle,G as $copyBlockFormatIndent,q as $ensureForwardRangeSelection,X as $forEachSelectedTextNode,L as $getComputedStyleForElement,M as $getComputedStyleForParent,fe as $getSelectionStyleValueForProperty,J as $isAtEdgeOfElement,U as $isAtNodeEnd,ie as $isParentElementRTL,$ as $isParentRTL,le as $moveCaretSelection,se as $moveCharacter,W as $patchStyleText,Q as $setBlocksType,re as $shouldOverrideDefaultCharacterSelection,D as $sliceSelectedTextNodeContent,j as $trimTextContentFromAnchor,ee as $wrapNodes,R as createDOMRange,O as createRectsFromDOMRange,_ as getCSSFromStyleObject,ue as getStyleObjectFromCSS,ge 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 C,$getSiblingCaret as S,$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.isConnected||(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),C=t.getElementByKey(v),S=null===n||E!==o||m!==s||h!==n.getKey(),b=null===u||C!==c||w!==f||v!==u.getKey();if((S||b)&&null!==E&&null!==C){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,C);d(),d=et(t,n,e)}n=p,o=E,s=m,u=y,c=C,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(Ct(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(S(t,e));return n&&n[0]}function yt(t,e,n){const o=M(),r=e||o,i=s(r)?v(r,t):S(r,t),l=wt(r),u=n?T(C(S(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(S(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=C(S(t,\"previous\")),n=b(e,\"root\");return n&&n[0].origin}function Ct(t,e){return yt(\"previous\",t,e)}function St(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=S(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(S(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,Ct as $reverseDfsIterator,St 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.52.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 n=t.t;void 0!==n;n=n.x)if(n.i===i.i)n.i=t.i;i=i.o}}();while(void 0!==h){var n=h;h=void 0;s++;while(void 0!==n){var r=n.u;n.u=void 0;n.f&=-3;if(!(8&n.f)&&w(n))try{n.c()}catch(n){if(!t){i=n;t=!0}}n=r}}s=0;v--;if(t)throw i}else v--}function n(i){if(v>0)return i();e=++u;v++;try{return i()}finally{t()}}var r,o=void 0;function f(i){var t=o,n=r;o=void 0;r=void 0;try{return i()}finally{o=t;r=n}}var h=void 0,v=0,s=0,u=0,e=0,c=void 0,d=0;function a(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,n=this.t;if(n!==i&&void 0===i.e){i.x=n;this.t=i;if(void 0!==n)n.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 n=i.e,r=i.x;if(void 0!==n){n.x=r;i.e=void 0}if(void 0!==r){r.e=n;i.x=void 0}if(i===this.t){this.t=r;if(void 0===r)f(function(){var i;null==(i=t.Z)||i.call(t)})}}};l.prototype.subscribe=function(i){var t=this;return j(function(){var n=t.value;f(function(){return i(n)})},{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=a(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!==e){i.l=e;c={S:i,v:i.v,i:i.i,o:c}}}(this);this.v=i;this.i++;d++;v++;try{for(var n=this.t;void 0!==n;n=n.x)n.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 _(i){for(var t=i.s;void 0!==t;t=t.n){var n=t.S.n;if(void 0!==n)t.r=n;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break}}}function b(i){var t=i.s,n=void 0;while(void 0!==t){var r=t.p;if(-1===t.i){t.S.U(t);if(void 0!==r)r.n=t.n;if(void 0!==t.n)t.n.p=r}else n=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=r}i.s=n}function p(i,t){l.call(this,void 0,t);this.x=i;this.s=void 0;this.g=d-1;this.f=4}p.prototype=new l;p.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===d)return!0;this.g=d;this.f|=1;if(this.i>0&&!w(this)){this.f&=-2;return!0}var i=o;try{_(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;b(this);this.f&=-2;return!0};p.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)};p.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)}}};p.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(p.prototype,\"value\",{get:function(){if(1&this.f)throw new Error(\"Cycle detected\");var i=a(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v}});function g(i,t){return new p(i,t)}function S(i){var n=i.m;i.m=void 0;if(\"function\"==typeof n){v++;var r=o;o=void 0;try{n()}catch(t){i.f&=-2;i.f|=8;m(i);throw t}finally{o=r;t()}}}function m(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;S(i)}function x(i){if(o!==this)throw new Error(\"Out-of-order effect\");b(this);o=i;this.f&=-2;if(8&this.f)m(this);t()}function E(i,t){this.x=i;this.m=void 0;this.s=void 0;this.u=void 0;this.f=32;this.name=null==t?void 0:t.name;if(r)r.push(this)}E.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.m=t}finally{i()}};E.prototype.S=function(){if(1&this.f)throw new Error(\"Cycle detected\");this.f|=1;this.f&=-9;S(this);_(this);v++;var i=o;o=this;return x.bind(this,i)};E.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.u=h;h=this}};E.prototype.d=function(){this.f|=8;if(!(1&this.f))m(this)};E.prototype.dispose=function(){this.d()};function j(i,t){var n=new E(i,t);try{n.c()}catch(i){n.d();throw i}var r=n.d.bind(n);r[Symbol.dispose]=r;return r}function C(i){return function(){var t=arguments,r=this;return n(function(){return f(function(){return i.apply(r,[].slice.call(t))})})}}function O(){var i=r;r=[];return function(){var t=r;if(r&&i)i=i.concat(r);r=i;return t}}var k=function(i){for(var t in i){var n=i[t];if(\"function\"==typeof n)i[t]=C(n);else if(\"object\"==typeof n&&null!==n&&!(\"brand\"in n))k(n)}};function T(i){return function(){var t,n,o=O();try{n=i.apply(void 0,[].slice.call(arguments))}catch(i){r=void 0;throw i}finally{t=o()}k(n);n[Symbol.dispose]=C(function(){if(t)for(var i=0;i<t.length;i++)t[i].dispose();t=void 0});return n}}export{p as Computed,E as Effect,l as Signal,C as action,n as batch,g as computed,T as createModel,j 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{$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{$getEditor as e,createState as n,isDOMDocumentNode as o,isHTMLElement as r,$getEditorDOMRenderConfig as s,DEFAULT_EDITOR_DOM_CONFIG as i,getRegisteredSubtypeMap as c,$isLexicalNode as l,iterStaticNodeConfigChain as u,$fullReconcile as a,shallowMergeConfig as f,RootNode as p,$getDocument as d,isDOMTextNode as h,isBlockDomNode as m,isInlineDomNode as g,$isElementNode as y,$isBlockElementNode as x,$isDecoratorNode as S,$isLineBreakNode as $,$createParagraphNode as v,$setFormatFromDOM as C,setNodeIndentFromDOM as b,$setDirectionFromDOM as k,$generateNodesFromRawText as w,$createTextNode as D,isOnlyChildInBlockNode as O,isLastChildInBlockNode as A,$createLineBreakNode as M,$isTextNode as E,IS_BOLD as N,IS_ITALIC as I,IS_UNDERLINE as W,IS_STRIKETHROUGH as R,TEXT_TYPE_TO_FORMAT as T,IS_SUBSCRIPT as F,IS_SUPERSCRIPT as z,IS_HIGHLIGHT as P,IS_CODE 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,HorizontalRuleExtension as Z}from\"@lexical/extension/HorizontalRuleExtension\";import{$getExtensionOutput as X}from\"@lexical/extension/getExtensionDependency\";function tt(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)}let et;function nt(t,e){const{key:n}=e;return t&&n in t?t[n]:e.defaultValue}function ot(t){return et&&et.editor===t?et:void 0}function rt(t,e){const n=ot(e);return n&&n[t]}function st(t,e){if(\"cfg\"in e){const{cfg:n,updater:o}=e;return[n,o(nt(t,n))]}return e}function it(t,e){let n=e;for(const o of t){const[t,r]=st(n,o),s=t.key;if(n===e&&nt(n,t)===r)continue;const i=n===e||void 0===n?ct(e):n;i[s]=r,n=i}return n}function ct(t){return Object.create(t||null)}function lt(t,e){return[t,e]}function ut(t,e){return{cfg:t,updater:e}}function at(t,n,o,r=e()){const s=et,i=ot(r);try{return et={...i,editor:r,[t]:n},o()}finally{et=s}}function ft(t,n=()=>{}){return(o,r=e())=>e=>{const s=ot(r),i=s&&s[t],c=it(o,i||n(r));return c&&c!==i?at(t,c,e,r):e()}}function pt(t,e,o,r){return Object.assign(n(Symbol(e),{isEqual:r,parse:o}),{[t]:!0})}const dt=(t,e,n)=>{ht(t),n()};function ht(t){if(!o(t))return;const e=t;if(null===e.querySelector(\"style\"))return;const n=new Map;function s(t){let e=n.get(t);if(void 0===e){e=new Set;for(let n=0;n<t.style.length;n++)e.add(t.style[n]);n.set(t,e)}return e}try{for(const t of Array.from(e.styleSheets)){let n;try{n=t.cssRules}catch{continue}for(const t of Array.from(n)){if(!H(t,CSSStyleRule))continue;let n;try{n=e.querySelectorAll(t.selectorText)}catch{continue}for(const e of Array.from(n)){if(!r(e))continue;const n=s(e);for(let o=0;o<t.style.length;o++){const r=t.style[o];n.has(r)||e.style.setProperty(r,t.style.getPropertyValue(r),t.style.getPropertyPriority(r))}}}}}catch{}}const mt=\"@lexical/html/DOM\",gt=Symbol.for(\"@lexical/html/DOMExportContext\"),yt=\"@lexical/html/DOMImport\",xt=Symbol.for(\"@lexical/html/DOMImportContext\"),St=()=>!0;function $t(t,e,n){return pt(gt,t,e,n)}const vt=/* @__PURE__ */$t(\"root\",Boolean),Ct=/* @__PURE__ */$t(\"isExport\",Boolean);function bt(t){const e=J(t,mt);return e?e.output.defaults:void 0}function kt(t,n=e()){return nt(function(t){return rt(gt,t)||bt(t)}(n),t)}function wt(t){const e=J(t,mt);return e?e.output.runtime:void 0}function Dt(t,n,o=e()){const r=wt(o);r&&r.setContextValue(t,n)}function Ot(t,n,o=e()){const r=wt(o);r&&r.setContextValue(t,n(nt(r.editorContext,t)))}function At(t=e()){const n=wt(t);return n?n.getSessionConfig():s(t)}const Mt=/* @__PURE__ */ft(gt,bt);function Et(t,e,n){return{...e,...n,nodes:t}}function Nt(t){return e=>e instanceof t}function It(t,{nodes:e}){if(\"*\"===e)return St;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&&tt(339,r.name,e);for(const t of o)n[t]=!0}o.push(Nt(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 Wt(t){return(e,n,o)=>t(e,o)}function Rt(t){return(e,n,o,r)=>t(e,n,r)}function Tt(t){return(e,n,o,r,s)=>t(e,n,o,s)}function Ft(t){return(e,n,o,r,s,i)=>t(e,n,o,r,i)}function zt(t,e){return(n,o)=>{const r=()=>t(n,o),s=e(n);return s?s(n,r,o):r()}}function Pt(t,e){return(n,o,r)=>{const s=()=>t(n,o,r),i=e(n);return i?i(n,o,s,r):s()}}const jt=Pt,_t=Rt;function Lt(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 Bt(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 Ut(t,e){return(n,o,r,s)=>{t(n,o,r,s);const i=e(n);i&&i(n,o,r,s)}}function Vt(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 qt(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 Gt(t){return\"*\"===t.nodes}function Ht(t){return t}function Jt(t,{overrides:e}){const n=function(t,e){const n=c(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(Gt(r))e.push(r);else if(Array.isArray(r.nodes))for(const t of r.nodes)l(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 u(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=It(n,t);for(const n in o)qt(o,n,e,t[n])}return o}(t,e),o={...i,...t.dom};return Vt(n,\"$createDOM\",o,zt,Wt),Vt(n,\"$exportDOM\",o,zt,Wt),Vt(n,\"$extractWithChild\",o,Bt,Ft),Vt(n,\"$getDOMSlot\",o,jt,_t),Vt(n,\"$shouldExclude\",o,Pt,Rt),Vt(n,\"$shouldInclude\",o,Pt,Rt),Vt(n,\"$getSlotTargetElement\",o,Lt,Tt),Vt(n,\"$updateDOM\",o,Lt,Tt),Vt(n,\"$decorateDOM\",o,Ut,Ht),o}function Qt(t){return{get:e=>nt(t,e)}}function Kt(t){const e=Object.create(null);return it(t,e)||e}function Yt(t,e){const n=Qt(e);return t.filter(t=>!(t.disabledForEditor&&t.disabledForEditor(n)))}function Zt(t){if(\"*\"===t.nodes)return()=>!0;const e=t.nodes.map(t=>{const e=t;return l(e.prototype)?t=>t instanceof e:t});return t=>e.some(e=>e(t))}class Xt{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=Yt(n,o),this.hasSessionGates=n.some(t=>t.disabledForSession)}setContextValue(t,e){const n=this.installed;this.editorContext[t.key]=e;const o=Yt(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=Jt(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(Zt(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(a,{discrete:!0}),s.$updateDOM=c}getSessionConfig(){const t=this.editor._config.dom||i;if(!this.hasSessionGates)return t;const e=Qt(rt(gt,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=Jt(this.initialEditorConfig,{overrides:o}),this.sessionCache.set(r,s)),s}}const te={build(t,e,n){const{initialEditorConfig:o}=n.getInitResult(),r=Kt(e.contextDefaults);return{defaults:r,runtime:new Xt(t,o,e.overrides,r)}},config:{contextDefaults:[],overrides:[]},html:{export:new Map([[p,()=>{const t=d().createElement(\"div\");return t.role=\"textbox\",{element:t}}]])},init(t,e){const n={dom:t.dom,nodes:t.nodes},o=Kt(e.contextDefaults),r=Yt(e.overrides,o);return t.dom=Jt(t,{overrides:r}),{initialEditorConfig:n}},mergeConfig(t,e){const n=f(t,e);for(const o of[\"overrides\",\"contextDefaults\"])e[o]&&(n[o]=[...t[o],...e[o]]);return n},name:mt},ee=Symbol.for(\"@lexical/html/SelectorImpl\");function ne(t,e){const n={kind:\"element\",predicate:(o=e,0===o.length?r:1===o.length?o[0]:(t,e)=>{for(const n of o)if(!n(t,e))return!1;return!0}),tags:t};var o;const s=n=>ne(t,[...e,n]);return{[ee]:n,attr:(t,e,n)=>s(se(t,e,n)),classAll:(...t)=>s(re(t)),classAny:(...t)=>s(function(t){const e=oe(t);return 0===e.length?()=>!1:t=>{if(!r(t))return!1;const n=t.classList;for(const t of e)if(n.contains(t))return!0;return!1}}(t)),styleAny:(t,e,n)=>s(function(t,e,n){if(\"string\"==typeof e)return n=>r(n)&&n.style.getPropertyValue(t)===e;if(e instanceof RegExp){const o=n&&n.capture,s=e;return(e,n)=>{if(!r(e))return!1;const i=e.style.getPropertyValue(t);if(!i)return!1;const c=i.match(s);return null!==c&&(void 0!==o&&(n[o]=c),!0)}}tt(362,JSON.stringify(t))}(t,e,n))}}function oe(t){const e=[];for(const n of t)n&&e.push(n);return e}function re(t){const e=oe(t);return 0===e.length?()=>!0:t=>{if(!r(t))return!1;const n=t.classList;for(const t of e)if(!n.contains(t))return!1;return!0}}function se(t,e,n){if(!0===e)return e=>r(e)&&e.hasAttribute(t);if(\"string\"==typeof e)return n=>r(n)&&n.getAttribute(t)===e;if(e instanceof RegExp){const o=n&&n.capture,s=e;return(e,n)=>{if(!r(e))return!1;const i=e.getAttribute(t);if(null==i)return!1;const c=i.match(s);return null!==c&&(void 0!==o&&(n[o]=c),!0)}}tt(361,JSON.stringify(t))}function ie(t){return{[ee]:t}}const ce=/* @__PURE__ */ie({kind:\"text\",predicate:h,tags:new Set}),le=/* @__PURE__ */ie({kind:\"comment\",predicate:t=>8===t.nodeType,tags:new Set});function ue(){return ne(new Set,[])}function ae(){return le}function fe(...t){t.length>0||tt(363);const e=new Set;for(const n of t)e.add(n.toUpperCase());return ne(e,[])}function pe(){return ce}const de={any:ue,comment:ae,tag:fe,text:pe};function he(t,e){return r(t)&&t.nodeName===e.toUpperCase()}const me=/[A-Za-z0-9_-]/;class ge{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()&&me.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||tt(364,String(this.pos+1),e,this.source)}}function ye(t){const e=new Set,n=[],o=[];let r=!1;if(t.skipWhitespace(),\"*\"===t.peek())t.consume(),r=!0;else if(me.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(se(\"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(se(e,o))}}}return o.length>0&&n.push(re(o)),t.assert(r||e.size>0||n.length>0,\"expected a selector\"),{predicates:n,tags:e}}function xe(t){const e=new ge(t,0),n=[];for(;n.push(ye(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 ne(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 ne(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 Se(t,e,n){return pt(xt,t,e,n)}const $e=/* @__PURE__ */Se(\"importSource\",()=>\"unknown\"),ve=/* @__PURE__ */Se(\"importSourceDataTransfer\",()=>null),Ce=/* @__PURE__ */Se(\"textFormat\",()=>0),be=/* @__PURE__ */Se(\"textStyle\",()=>({}));function ke(t){if(!r(t))return!1;if(\"PRE\"===t.nodeName)return!0;const e=t.style.whiteSpace;return\"string\"==typeof e&&e.startsWith(\"pre\")}function we(t){if(h(t))return!0;if(!r(t))return!1;const e=t.style.display;return e?e.startsWith(\"inline\"):!m(t)&&g(t)}const De=/* @__PURE__ */Se(\"whitespaceConfig\",()=>({isInline:we,preservesWhitespace:ke})),Oe=/* @__PURE__ */Se(\"importOverlays\",()=>[]);class Ae{constructor(t){this.record=t}get(t){return nt(this.record,t)}set(t,e){this.record[t.key]=e}update(t,e){this.record[t.key]=e(nt(this.record,t))}has(t){return Object.prototype.hasOwnProperty.call(this.record,t.key)}}function Me(t){const e=J(t,yt);return e?e.output.defaults:void 0}function Ee(t,n=e()){return nt(function(t){return rt(xt,t)||Me(t)}(n),t)}const Ne=/* @__PURE__ */ft(xt,Me);function Ie(t){return x(t)||S(t)&&!t.isInline()}function We(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(),y(s)){const t=We(s.getChildren(),e);s.splice(0,s.getChildrenSize(),t)}n.push(s)}else o.push(s);return r(),n}function Re(t,e){if(!r(e))return t;const n=e.style.textAlign;if(!Be(n))return t;for(const e of t)x(e)&&\"\"===e.getFormatType()&&e.setFormat(n);return t}function Te(t,e,n){1===t.length&&$(t[0])&&(t=[]);const o=v();if(r(n)){const t=n.style.textAlign;Be(t)&&o.setFormat(t)}return[o.splice(0,0,t)]}const Fe={$accepts:Ie,$packageRun:Te,name:\"BlockSchema\"},ze={$accepts:t=>!Ie(t),name:\"InlineSchema\"},Pe={$accepts:Ie,$packageRun:t=>t,name:\"NestedBlockSchema\"},je={$accepts:Ie,$packageRun:Te,name:\"RootSchema\"},_e=de,Le=new Set([\"center\",\"end\",\"justify\",\"left\",\"right\",\"start\"]);function Be(t){return Le.has(t)}const Ue={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\"}},Ve={CODE:j,MARK:P},qe=new Set([\"font-weight\",\"font-style\",\"text-decoration\",\"text-transform\",\"vertical-align\"]),Ge={$import:(t,e)=>{const n=t.get(Ce),o=Ue[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|=N:\"normal\"!==o&&\"400\"!==o||(n|=N),\"italic\"===r?e|=I:\"normal\"===r&&(n|=I),s){const t=s.split(\" \");t.includes(\"underline\")&&(e|=W),t.includes(\"line-through\")&&(e|=R),t.includes(\"none\")&&(n|=W|R)}return\"lowercase\"===i?(e|=T.lowercase,n|=T.uppercase|T.capitalize):\"uppercase\"===i?(e|=T.uppercase,n|=T.lowercase|T.capitalize):\"capitalize\"===i?(e|=T.capitalize,n|=T.lowercase|T.uppercase):\"none\"===i&&(n|=T.lowercase|T.uppercase|T.capitalize),\"sub\"===c?(e|=F,n|=z):\"super\"===c?(e|=z,n|=F):\"baseline\"===c&&(n|=F|z),{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=Ve[e.nodeName];return u&&(c|=u),c===n?t.$importChildren(e):t.$importChildren(e,{context:[lt(Ce,c)]})},match:/* @__PURE__ */_e.tag(\"b\",\"strong\",\"em\",\"i\",\"code\",\"mark\",\"s\",\"sub\",\"sup\",\"u\",\"span\"),name:\"@lexical/html/inline-format\"};function He(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(h(o))return o;if(\"BR\"===o.nodeName)return null}}function Je(t,e){return 0!==e&&E(t)?t.setFormat(e):t}function Qe(t,e){if(E(t)){const n=function(t){let e=\"\";for(const n in t)qe.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(Ce),o=t.get(be),r=t.get(De);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=w(e.textContent||\"\");for(const e of t)Je(e,n),Qe(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=He(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=He(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=D(s);return Je(i,n),Qe(i,o),[i]},match:/* @__PURE__ */_e.text(),name:\"@lexical/html/#text\"},Ye={$import:()=>[],match:/* @__PURE__ */_e.tag(\"script\",\"style\"),name:\"@lexical/html/script-style-ignore\"},Ze={$import:(t,e)=>O(e)||A(e)?[]:[M()],match:/* @__PURE__ */_e.tag(\"br\"),name:\"@lexical/html/br\"},Xe={$import:(t,e)=>{const n=v();if(C(n,e),b(e,n),\"\"===n.getFormatType()){const t=e.getAttribute(\"align\");t&&Be(t)&&n.setFormat(t)}return k(n,e),[n.splice(0,0,t.$importChildren(e))]},match:/* @__PURE__ */_e.tag(\"p\"),name:\"@lexical/html/p\"},tn={$import:(t,n,o)=>e().hasNode(K)?[Y()]:o(),match:/* @__PURE__ */_e.tag(\"hr\"),name:\"@lexical/html/hr\"},en=[Ye,Xe,tn,{$import:(t,e,n)=>m(e)?Re(t.$importChildren(e,{schema:Fe}),e):n(),match:/* @__PURE__ */_e.any(),name:\"@lexical/html/transparent-block\"},Ke,Ze,Ge];function nn(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 on(t){const e=[],n=new Map,o=[],r=[],s=[],i=new Set;t.forEach((t,c)=>{const l=function(t){const e=t[ee];return void 0===e&&tt(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,nn(e,o));return{byTag:c,commentIndices:s,rules:e,textIndices:r,wildcardIndices:o}}function rn(t,e){return h(e)?t.textIndices:8===e.nodeType?t.commentIndices:r(e)?t.byTag.get(e.nodeName)||t.wildcardIndices:sn}const sn=/* @__PURE__ */Object.freeze([]);function cn(t){const e=[];for(const n of t)if(ln(n))for(const t of n.rules)e.push(t);else e.push(n);return e}function ln(t){return\"object\"==typeof t&&null!==t&&\"__type\"in t&&\"CompiledOverlayRules\"===t.__type}function un(t){const e=cn(t);return{__type:\"CompiledOverlayRules\",dispatch:on(e),rules:e}}const an=/* @__PURE__ */Object.freeze({});function fn(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=()=>pn(t,e,n);return n&&n.context?Ne(n.context,t.editor)(o):o()}finally{o&&t.overlays.pop()}}(t,e,n),$importOne:(e,n)=>dn(t,e,n),captures:e,get:e=>Ee(e,t.editor),session:t.session};return n}function pn(t,e,n){const o=n&&n.$onChild,r=[];for(const n of Array.from(e.childNodes)){const e=dn(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 dn(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=rn(r,e);s.length>0&&n.push({dispatch:r,indices:s})}const o=rn(t.dispatch,e);return o.length>0&&n.push({dispatch:t.dispatch,indices:o}),n}(t,e);if(0===n.length)return hn(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=fn(t,0===Object.keys(l).length?an:l);try{return o.$import(n,e,s)}catch(t){throw t}}}o++,r=0}return hn(t,e)};return s()}(t,e);return n&&n.context?Ne(n.context,t.editor)(o):o()}function hn(t,e){if(0===e.childNodes.length)return[];const n=[];for(const o of Array.from(e.childNodes)){const e=dn(t,o,void 0);for(const t of e)n.push(t)}return n}const mn={$import:(t,e)=>t.$importChildren(e),match:/* @__PURE__ */de.any(),name:\"@lexical/html/default-hoist\"},gn={build(t,e){const n=on(cn(e.rules)),r=it(e.contextDefaults,void 0),s=e.preprocess;return{$generateNodesFromDOM:(e,i)=>{const c=rt(xt,t)||r,l=i&&i.context?it(i.context,c):c,u=void 0!==l&&l!==c?l:Object.create(c||null),a=new Ae(u),f={session:a};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,e,f),at(xt,u,()=>function(t,e,n,r){return pn({dispatch:t,editor:e,overlays:r.get(Oe).map(t=>t.dispatch),session:r},o(n)?n.body:n,{schema:je})}(n,t,e,a),t)},defaults:r}},config:{contextDefaults:[],preprocess:[dt],rules:[mn]},mergeConfig:(t,e)=>f(t,{...e,...e.contextDefaults&&{contextDefaults:[...t.contextDefaults,...e.contextDefaults]},...e.preprocess&&{preprocess:[...t.preprocess,...e.preprocess]},...e.rules&&{rules:[...e.rules,...t.rules]}}),name:yt};function yn(t,e){return X(gn).$generateNodesFromDOM(t,e)}const xn={dependencies:[[gn,{rules:en}]],name:\"@lexical/html/CoreImport\"};function Sn(t){return t}const $n=[tn],vn={dependencies:[Z,xn],name:\"@lexical/html/HorizontalRuleImport\"},Cn={any:ue,comment:ae,css:xe,tag:fe,text:pe},bn=new Set([\"STYLE\",\"SCRIPT\"]);function kn(t,e){ht(e);const n=o(e)?e.body.childNodes:e.childNodes,r=[],s=[];for(const e of n)if(!bn.has(e.nodeName)){const n=En(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(M());for(const e of t){const t=e.getParent();t&&t.splice(e.getIndexWithinParent(),1,e.getChildren())}}(s),r}function wn(t,n=null,o=e()){return Mt([lt(Ct,!0)],o)(()=>{const e=_(),r=At(o),s=L(n),i=t.append.bind(t);for(const t of(y(s)?s:e).getChildren())An(o,t,i,n,r);return t})}function Dn(t,n=_()){const o=e();return Mt([lt(Ct,!0),lt(vt,!0)],o)(()=>{const e=At(o),r=t.append.bind(t);return An(o,n,r,null,e),t})}function On(t,e=null){return(\"undefined\"==typeof document||\"undefined\"==typeof window&&void 0===global.window)&&tt(338),B(t),wn(d().createElement(\"div\"),e,t).innerHTML}function An(e,n,o,i=null,c=s(e)){let l=c.$shouldInclude(n,i,e);const u=c.$shouldExclude(n,i,e);let a=n;null!==i&&E(n)&&(a=t(i,n,\"clone\"));const f=c.$exportDOM(a,e),{element:p,after:h,append:g,$getChildNodes:x}=f;if(!p)return!1;const S=d().createDocumentFragment(),v=x?x():y(a)?a.getChildren():[],C=l&&U(i)&&y(n)?null:i,b=S.append.bind(S);let k=null;for(const t of v){const o=An(e,t,b,C,c);o&&(k=t),!l&&o&&c.$extractWithChild(n,t,i,\"html\",e)&&(l=!0)}if(l&&!u){if((r(p)||V(p))&&(g?g(S):p.append(S),function(t,e){const n=t.lastChild;if($(e)&&r(t)&&m(t)&&null!==n&&\"BR\"===n.nodeName){const e=d().createElement(\"br\");e.setAttribute(\"data-lexical-managed-linebreak\",\"true\"),t.append(e)}}(p,k)),V(p)){if(h){const t=h.call(a,p);t&&p.replaceChildren(t)}o(p)}else if(o(p),h){const t=h.call(a,p);t&&p.replaceWith(t)}}else o(S);return l}function Mn(t,e,n,o=null){return An(t,e,n.append.bind(n),o,At(t))}function En(t,e,n,o,r=new Map,s){const i=[];if(bn.has(t.nodeName))return i;let c=null;const l=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),u=l?l(t):null;let a=null;if(null!==u){a=u.after;const e=u.node;if(c=Array.isArray(e)?e[e.length-1]:e,null!==c){for(const[,t]of r)if(c=t(c,s),!c)break;c&&i.push(...Array.isArray(e)?e:[c])}null!=u.forChild&&r.set(t.nodeName,u.forChild)}const f=t.childNodes;let p=[];const d=(null==c||!q(c))&&(null!=c&&x(c)||o);for(let t=0;t<f.length;t++)p.push(...En(f[t],e,n,d,new Map(r),c));if(null!=a&&(p=a(p)),m(t)&&(p=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(x(i))o&&!i.getFormat()&&i.setFormat(o),r.push(i);else if(s.push(i),t===e.length-1||t<e.length-1&&x(e[t+1])){const t=n();t.setFormat(o),t.append(...s),r.push(t),s=[]}}return r}(t,p,d?()=>{const t=new G;return n.push(t),t}:v)),null==c)if(p.length>0)for(const t of p)i.push(t);else m(t)&&function(t){return null!=t.nextSibling&&null!=t.previousSibling&&(g(t.nextSibling)&&g(t.previousSibling))}(t)&&i.push(M());else y(c)&&c.append(...p);return i}export{Mn as $appendNodeToHTML,We as $distributeInlineWrapper,wn as $generateDOMFromNodes,Dn as $generateDOMFromRoot,On as $generateHtmlFromNodes,kn as $generateNodesFromDOM,yn as $generateNodesFromDOMViaExtension,Ee as $getImportContextValue,kt as $getRenderContextValue,At as $getSessionDOMRenderConfig,dt as $inlineStylesFromStyleSheets,Ie as $isBlockLevel,Re as $propagateTextAlignToBlockChildren,Dt as $setRenderContextValue,Ot as $updateRenderContextValue,Ne as $withImportContext,Mt as $withRenderContext,Fe as BlockSchema,xn as CoreImportExtension,en as CoreImportRules,gn as DOMImportExtension,te as DOMRenderExtension,vn as HorizontalRuleImportExtension,$n as HorizontalRuleImportRules,Oe as ImportOverlays,$e as ImportSource,ve as ImportSourceDataTransfer,Ce as ImportTextFormat,be as ImportTextStyle,De as ImportWhitespaceConfig,ze as InlineSchema,Pe as NestedBlockSchema,Ct as RenderContextExport,vt as RenderContextRoot,je as RootSchema,ut as contextUpdater,lt as contextValue,Se as createImportState,$t as createRenderState,we as defaultIsInline,ke as defaultPreservesWhitespace,Sn as defineImportRule,un as defineOverlayRules,Et as domOverride,he as isElementOfTag,xe as parseSelector,Cn 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{sel as t,ImportOverlays as e,defineOverlayRules as n,CoreImportExtension as r,DOMImportExtension as i}from\"@lexical/html\";import{getTextDirection as o,$isElementNode as s,$isTabNode as l,$isLineBreakNode as c,tokenizeRawText as u,$createTabNode as a,$createLineBreakNode as g,$getSiblingCaret as f,getterTableOf as h,setterTableOf as d,setterDefaultOf as p,aliasTableOf as m,$create as _,ElementNode as x,$getDocument as y,addClassNamesToElement as S,setDOMStyleFromCSS as b,$getEditor as v,$isTextNode as C,$createParagraphNode as T,nodeSchema as N,withAccessors as A,optional as P,stringValue as w,nullable as F,isHTMLElement as O,$applyNodeReplacement as $,TextNode as D,removeClassNamesFromElement as E,isDOMDocumentNode as L,isDOMTextNode as B,$generateNodesFromRawText as H,mergeRegister as k,KEY_ENTER_COMMAND as z,$getSelection as M,$isRangeSelection as K,COMMAND_PRIORITY_LOW as I,TabNode as j,$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 ct}from\"@lexical/extension/signals\";import{namedSignals as ut}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=f(t,e);r&&(Gt(r.origin)||l(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=o(r.getTextContent());if(null!==t)return t}if(r===n)break;r=r.getNextSibling()}const i=e.getParent();if(s(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)||l(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 u=null;if(e<t.getTextContentSize())Gt(t)&&(u=t.getTextContent()[e]);else{const e=t.getNextSibling();Gt(e)&&(u=e.getTextContent()[0])}if(null!==u&&\" \"!==u)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 u(t,{linebreak:()=>e.push(g()),tab:()=>e.push(a()),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,c=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!==c&&n.focus.set(s,Math.max(0,c-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=h(t,\"format\"),n=d(t,\"format\"),r=p(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 c=t.__dir;null!=c&&(o.direction=c);const u=e[t.__format];void 0!==u&&\"\"!==u&&(o.format=u);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 c=e.theme;return t.setTheme(void 0===c?void 0:\"string\"==typeof c?c:\"\"),t}}};function Nt(t,e){t.__highlightType=e.__highlightType}const At=t=>{const e=h(t,\"mode\"),n=m(t,\"detail\",0),r=m(t,\"format\",0),i=d(t,\"mode\"),o=p(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 c=t.__text;return void 0!==c&&\"\"!==c&&(n.text=c),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 c=e.mode;t.__mode=\"string\"==typeof c&&c in i?i[c]:o;const u=e.style;t.__style=\"string\"==typeof u?u:\"\";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__ */N()({language:/* @__PURE__ */A(/* @__PURE__ */P(/* @__PURE__ */F(/* @__PURE__ */w())),{getter:{field:\"__language\"}}),theme:/* @__PURE__ */A(/* @__PURE__ */P(/* @__PURE__ */w()),{getter:{field:\"__theme\"}})}),wt=\"javascript\",Ft=()=>wt;function Ot(t,e){for(const n of t.childNodes){if(O(n)&&n.tagName===e)return!0;if(Ot(n,e))return!0}return!1}const $t=\"data-language\",Dt=\"data-highlight-language\",Et=\"data-theme\",Lt=/* @__PURE__ */ft();class Bt extends x{__language;__theme;__isSyntaxHighlightSupported;$config(){return this.config(\"code\",{extends:x,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:It,priority:3}:null},tr:t=>{const e=t.closest(\"table\");return e&&Rt(e)?{conversion:It,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=y().createElement(\"code\");S(e,t.theme.code),e.setAttribute(\"spellcheck\",\"false\");const n=this.getLanguage();n&&(e.setAttribute($t,n),this.getIsSyntaxHighlightSupported()&&e.setAttribute(Dt,n));const r=this.getTheme();r&&e.setAttribute(Et,r);const i=this.getStyle();return i&&b(e.style,i),e}updateDOM(t,e,n){const r=this.__language,i=t.__language;r?r!==i&&e.setAttribute($t,r):i&&e.removeAttribute($t);const o=this.__isSyntaxHighlightSupported;t.__isSyntaxHighlightSupported&&i?o&&r?r!==i&&e.setAttribute(Dt,r):e.removeAttribute(Dt):o&&r&&e.setAttribute(Dt,r);const s=this.__theme,l=t.__theme;s?s!==l&&e.setAttribute(Et,s):l&&e.removeAttribute(Et);const c=this.__style,u=t.__style;return c!==u&&b(e.style,c,u),!1}exportDOM(t){const e=y().createElement(\"pre\");S(e,t._config.theme.code),e.setAttribute(\"spellcheck\",\"false\");const n=this.getLanguage();n&&(e.setAttribute($t,n),this.getIsSyntaxHighlightSupported()&&e.setAttribute(Dt,n));const r=this.getTheme();r&&e.setAttribute(Et,r);const i=this.getStyle();return i&&b(e.style,i),{element:e}}insertNewAfter(t,e=!0){if(!lt(v(),\"@lexical/code\")){Lt();const e=Wt(t);if(e)return e}const{anchor:n,focus:r}=t,i=(n.isBefore(r)?n:r).getNode();if(C(i)){let t=pt(i);const e=[];for(;;)if(l(t))e.push(a()),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,c=i.getParentOrThrow(),u=[g(),...e];c.splice(s,0,u);const f=e[e.length-1];f?f.select():0===n.offset?r.selectPrevious():r.getNextSibling().selectNext(0,0)}if(kt(i)){const{offset:e}=t.anchor;i.splice(e,0,[g()]),i.select(e+1,e+1)}return null}canIndent(){return!1}collapseAtStart(){const t=T();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 _(Bt).setLanguage(t).setTheme(e)}function kt(t){return t instanceof Bt}function zt(t){return{node:Ht(t.getAttribute($t),t.getAttribute(Et))}}function Mt(t){const e=t,n=jt(e);return n||function(t){let e=t.parentElement;for(;null!==e;){if(jt(e))return!0;e=e.parentElement}return!1}(e)?{node:n?Ht():null}:{node:null}}function Kt(){return{node:Ht()}}function It(){return{node:null}}function jt(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=T();return t.splice(n-2,2,[]).insertAfter(e,!1),e.select(),e}}}}return null}const Jt=/* @__PURE__ */N()({highlightType:/* @__PURE__ */A(/* @__PURE__ */P(/* @__PURE__ */F(/* @__PURE__ */w())),{getter:{field:\"__highlightType\"}})});class qt extends D{__highlightType;constructor(t=\"\",e,n){super(t,n),this.__highlightType=e}$config(){return this.config(\"code-highlight\",{extends:D,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 S(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(e,i),o&&S(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 $(new qt(t,e))}function Gt(t){return t instanceof qt}const Qt=\"data-language\",Xt=\"data-theme\";function Yt(t){return null!==t.style.fontFamily.match(\"monospace\")}function Zt(t){let e=t.parentElement;for(;null!==e;){if(Yt(e))return!0;e=e.parentElement}return!1}const te=/* @__PURE__ */n([{$import:(t,e)=>t.$importChildren(e),match:/* @__PURE__ */t.tag(\"tr\",\"td\"),name:\"@lexical/code/github-code-table/unwrap\"}]),ee={$import:(t,e)=>[Ht(e.getAttribute(Qt),e.getAttribute(Xt)).splice(0,0,t.$importChildren(e))],match:/* @__PURE__ */t.tag(\"pre\"),name:\"@lexical/code/pre\"},ne={$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,t.$importChildren(e))]:n()},match:/* @__PURE__ */t.tag(\"code\"),name:\"@lexical/code/code-multiline\"};function re(t){if(!O(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 ie(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(O(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(B(s)){const t=s.textContent||\"\";t.length>0&&(r+=t,i=!0)}return o(),e?n:null}function oe(t){for(const e of Array.from(t.children)){if(O(e)&&re(e)){if(null!==ie(e))return!0;const t=e.nextElementSibling;if(t&&re(t))return!0;continue}if(oe(e))return!0}return!1}const se=/* @__PURE__ */n([{$import:(t,e,n)=>{if(!re(e)||Zt(e))return n();const r=ie(e);return null===r||0===r.length?n():[Ht().splice(0,0,H(r.join(\"\\n\")))]},match:/* @__PURE__ */t.tag(\"div\"),name:\"@lexical/code/vscode-wrapper\"},{$import:(t,e,n)=>{if(!re(e)||Zt(e))return n();const r=e.previousElementSibling;if(r&&re(r))return[];const i=[];let o=e;for(;o&&re(o);)i.push(\"BR\"===o.tagName?\"\":o.textContent||\"\"),o=o.nextElementSibling;return i.length<2?n():[Ht().splice(0,0,H(i.join(\"\\n\")))]},match:/* @__PURE__ */t.tag(\"div\",\"br\"),name:\"@lexical/code/vscode-line-run\"}]),le={$import:(t,e,n)=>Yt(e)?[Ht().splice(0,0,t.$importChildren(e))]:Zt(e)?t.$importChildren(e):n(),match:/* @__PURE__ */t.tag(\"div\"),name:\"@lexical/code/div\"},ce=[{$import:(t,e)=>[Ht().splice(0,0,t.$importChildren(e,{rules:te}))],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\"},ne,ee,le],ue={dependencies:[r,[i,{preprocess:[(t,n,r)=>{oe(L(t)?t.body:t)&&n.session.update(e,t=>[...t,se]),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))},I),t.registerNodeTransform(j,t=>{0!==t.getFormat()&&kt(t.getParent())&&t.setFormat(0)}))},ae={dependencies:[ue],name:\"@lexical/code/Import\"};function ge(t){const e=v().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)||l(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([a()]):function(t,e){const n=t.anchor.getNode();if(!Gt(n)&&!l(n))return;const r=pt(n);l(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=a(),e=g(),r=n.isBackward()?\"previous\":\"next\";return n.insertNodes([t,e]),nt(rt(it(ot(t,\"next\",0),st(f(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=a();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 l(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,u=r.getNode(),a=i.getNode(),g=t===q;if(!he(n)||!Gt(u)&&!l(u)||!Gt(a)&&!l(a))return!1;if(!e.altKey){if(n.isCollapsed()){const t=u.getParentOrThrow();if(g&&0===o&&null===u.getPreviousSibling()){if(null===t.getPreviousSibling())return t.selectPrevious(),e.preventDefault(),!1}else if(!g&&o===u.getTextContentSize()&&null===u.getNextSibling()&&null===t.getNextSibling())return t.selectNext(),e.preventDefault(),!1}return!1}let f,h;if(u.isBefore(a)?(f=pt(u),h=mt(a)):(f=pt(a),h=mt(u)),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)&&!l(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)&&!l(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(u,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(),u=t===Z;if(!he(n)||!Gt(o)&&!l(o)||!Gt(s)&&!l(s))return!1;const a=s,g=\"rtl\"===_t(a)?!u:u,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),I),t.registerCommand(J,t=>at(kt,t),I),t.registerCommand(q,t=>!t.altKey&&gt(kt,t),I),t.registerCommand(U,t=>gt(kt,t),I)]:[],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 c,u;0===l.length&&ht(285),e.isBackward()?(c=o,u=i):(c=i,u=o);const a=pt(l[0]),g=mt(l[0]),f=et(a.getKey(),0,\"text\"),h=et(g.getKey(),g.getTextContentSize(),\"text\");return c.isBefore(f)||h.isBefore(u)?n:f.isBefore(c)||u.isBefore(h)?r:n}(e.shiftKey);return null!==n&&(e.preventDefault(),t.dispatchCommand(n),!0)},I),t.registerCommand(G,()=>!!he(M())&&(Q([a()]),!0),I),t.registerCommand(X,()=>pe(X),I),t.registerCommand(Y,()=>pe(Y,e),I),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)},I),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))},I),t.registerCommand(Z,t=>_e(Z,t),I),t.registerCommand(tt,t=>_e(tt,t),I))}const ye={build:(t,e)=>ut(e),config:{disabled:!1,escapeWithArrows:!1,tabSize:void 0},dependencies:[ue],name:\"@lexical/code-indent\",register:(t,e,n)=>{const r=n.getOutput();return ct(()=>{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,ue as CodeExtension,qt as CodeHighlightNode,ae as CodeImportExtension,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}from\"@lexical/extension/signals\";import{namedSignals as n}from\"@lexical/extension/namedSignals\";import{getterTableOf as r,setterTableOf as i,setterDefaultOf as l,ElementNode as o,$getDocument as s,addClassNamesToElement as u,isHTMLAnchorElement as a,$copyNode as c,$isRangeSelection as g,$applyNodeReplacement as f,createCommand as d,$getSelection as _,$isNodeSelection as p,$findMatchingParent as h,nodeSchema as m,withField as x,stringValue as y,nullable as v,booleanValue as k,$normalizeSelection__EXPERIMENTAL as b,$setSelection as U,$getChildCaret as S,$isElementNode as T,$insertNodeToNearestRootAtCaret as L,$rewindSiblingCaret as C,$caretFromPoint as A,$normalizeCaret as N,$isSiblingCaret as R,$setPointFromCaret as P,shallowMergeConfig as O,mergeRegister as I,COMMAND_PRIORITY_EDITOR as w,PASTE_COMMAND as F,$isTextNode as D,COMMAND_PRIORITY_LOW as M,registerEventListeners as E,isDOMNode as z,getNearestEditorFromDOMNode as $,$getNearestNodeFromDOMNode as W,TextNode as K,$isLineBreakNode as B,$createTextNode as j}from\"lexical\";import{sel as J,$distributeInlineWrapper as Z,CoreImportExtension as H,DOMImportExtension as G}from\"@lexical/html\";import{objectKlassEquals as q}from\"@lexical/utils\";const Q=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function V(t,e){if(\"number\"==typeof t)return Number.isFinite(t)?t:e;if(\"string\"!=typeof t||!Q.test(t))return e;const n=Number(t);return Number.isFinite(n)?n:e}function X(t,e,n,r,i){const l=V(t,e);return l>=n&&l<=r&&Number.isInteger(l)?l:e}function Y(t,e){t.__rel=e.__rel,t.__target=e.__target,t.__title=e.__title,t.__url=e.__url}const tt=t=>{const e=r(t,\"format\"),n=i(t,\"format\"),o=l(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 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=X(e.indent,0,0,Infinity),t.__textFormat=V(e.textFormat,0);const l=e.textStyle;t.__textStyle=\"string\"==typeof l?l:\"\";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:Y}};function et(t,e){t.__isUnlinked=e.__isUnlinked}const nt=t=>{const e=r(t,\"format\"),n=i(t,\"format\"),o=l(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 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=X(e.indent,0,0,Infinity),t.__textFormat=V(e.textFormat,0);const l=e.textStyle;t.__textStyle=\"string\"==typeof l?l:\"\";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:et}},rt=new Set([\"http:\",\"https:\",\"mailto:\",\"sms:\",\"tel:\"]),it=/* @__PURE__ */m()({rel:/* @__PURE__ */x(/* @__PURE__ */v(/* @__PURE__ */y(),{defaultAsNull:!0}),{field:\"__rel\"}),target:/* @__PURE__ */x(/* @__PURE__ */v(/* @__PURE__ */y(),{defaultAsNull:!0}),{field:\"__target\"}),title:/* @__PURE__ */x(/* @__PURE__ */v(/* @__PURE__ */y(),{defaultAsNull:!0}),{field:\"__title\"}),url:/* @__PURE__ */x(/* @__PURE__ */y(),{field:\"__url\",getter:\"getURL\",setter:\"setURL\"})});class lt extends o{__url;__target;__rel;__title;$config(){return this.config(\"link\",{extends:o,generated:tt,importDOM:{a:()=>({conversion:at,priority:1})},json:it})}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=s().createElement(\"a\");return this.updateLinkDOM(null,e,t),u(e,t.theme.link),e}updateLinkDOM(t,e,n){if(a(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=vt(t);try{const e=new URL(vt(t));if(!rt.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&&!rt.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=c(this);return this.insertAfter(n,e),n}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}canBeEmpty(){return!1}isInline(){return!0}extractWithChild(t,e,n){if(!g(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 ot(t){const e=A(t,\"next\");return[e,e.getFlipped()]}function st(t,e){for(const n of e)if(n.origin.isAttached()){const e=N(n);return void P(t,e)}}function ut(t){const e=_();let n=null,r=null;function i(){g(e)&&(st(e.anchor,n),st(e.focus,r),b(e))}g(e)&&(n=ot(e.anchor),r=ot(e.focus));let l=!1;for(const e of S(t,\"next\")){const n=e.origin;if(T(n)&&!n.isInline()){const r=n.getChildren();if(r.length>0){const e=c(t);e.append(...r),n.append(e),l=!0}L(n,C(e),{$shouldSplit:()=>!1})}}function o(t,e,n){const[r,i]=t,l=t=>R(t)&&t.origin.is(e);if(!l(r)&&!l(i))return t;const o=N(S(n,\"next\"));return[o,o.getFlipped()]}if(t.isAttached()){const e=t.getPreviousSibling();if(gt(e)&&e.shouldMergeAdjacentLink(t))return n&&(n=o(n,e,t)),r&&(r=o(r,e,t)),e.append(...t.getChildren()),t.remove(),void i();const s=t.getNextSibling();gt(s)&&t.shouldMergeAdjacentLink(s)&&(n&&(n=o(n,t,s)),r&&(r=o(r,t,s)),t.append(...s.getChildren()),s.remove(),l=!0)}if(l){if(!t.canBeEmpty()&&t.isEmpty()){const e=t.getParent();t.remove(),e&&e.isEmpty()&&e.remove()}i()}}function at(t){let e=null;if(a(t)){const n=t.textContent;(null!==n&&\"\"!==n||t.children.length>0)&&(e=ct(t.getAttribute(\"href\")||\"\",{rel:t.getAttribute(\"rel\"),target:t.getAttribute(\"target\"),title:t.getAttribute(\"title\")}))}return{node:e}}function ct(t=\"\",e){return f(new lt(t,e))}function gt(t){return t instanceof lt}const ft=/* @__PURE__ */m()({isUnlinked:/* @__PURE__ */x(/* @__PURE__ */k(),{field:\"__isUnlinked\"})});class dt extends lt{__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:lt,generated:nt,json:ft})}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?s().createElement(\"span\"):super.createDOM(t)}updateDOM(t,e,n){return super.updateDOM(t,e,n)||t.__isUnlinked!==this.__isUnlinked}}function _t(t=\"\",e){return f(new dt(t,e))}function pt(t){return t instanceof dt}const ht=/* @__PURE__ */d(\"TOGGLE_LINK_COMMAND\");function mt(t,e){if(\"element\"===t.type){const n=t.getNode();return T(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 xt(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=_();if(null===o||!g(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=h(t,t=>!pt(t)&&gt(t));e&&(e.insertBefore(t),0===e.getChildren().length&&e.remove())}else{const e=h(t,t=>!pt(t)&&gt(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=ct(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=h(t,t=>!pt(t)&&gt(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=h(e,t=>!pt(t)&&gt(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())||T(r)&&e.some(e=>t.isParentOf(e)&&r.isParentOf(e)),l=r.filter(i);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=c(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=h(t,gt);if(null!==e)return a(e)}!function(t){const e=_();if(!g(e))return t();const n=b(e),r=n.isBackward(),i=mt(n.anchor,r?-1:0),l=mt(n.focus,r?0:-1);t();if(i||l){const t=_();if(g(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\")}U(b(e))}}}(()=>{let t=null;for(const e of s){if(!e.isAttached())continue;const o=h(e,gt);if(o){a(o);continue}if(T(e)){if(!e.isInline())continue;if(gt(e)){if(!(pt(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();gt(s)&&s.is(t)?s.append(e):(t=ct(n,{rel:l,target:r,title:i}),e.insertAfter(t),t.append(e))}})}const yt=/^\\+?[0-9\\s()-]{5,}$/;function vt(t){return t.match(/^[a-z][a-z0-9+.-]*:/i)||t.match(/^[/#.]/)?t:t.includes(\"@\")?`mailto:${t}`:yt.test(t)?`tel:${t}`:`https://${t}`}const kt={build:(t,e)=>n(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(dt,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}))}},bt=[{$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 Z(t.$importChildren(e),()=>ct(n,r))},match:/* @__PURE__ */J.tag(\"a\"),name:\"@lexical/link/a\"}];function Ut(t,n){return I(t.registerNodeTransform(lt,ut),t.registerCommand(ht,t=>{const e=n.validateUrl.peek(),r=n.attributes.peek();if(null===t)return xt(null),!0;if(\"string\"==typeof t)return!(void 0!==e&&!e(t)||(xt(t,r),0));{const{url:n,...i}=t;return!(void 0!==e&&!e(n)||(xt(n,{...r,...i}),0))}},w),e(()=>{const e=n.validateUrl.value;if(!e)return;const r=n.attributes.value;return t.registerCommand(F,n=>{const i=_();if(!g(i)||i.isCollapsed()||!q(n,ClipboardEvent))return!1;if(null===n.clipboardData)return!1;const l=n.clipboardData.getData(\"text\");return!!e(l)&&(!i.getNodes().some(t=>T(t)||D(t)&&!t.isSimpleText())&&(t.dispatchCommand(ht,{...r,url:l}),n.preventDefault(),!0))},M)}))}const St={build:(t,e,r)=>n(e),config:{attributes:void 0,validateUrl:void 0},dependencies:[H,[G,{rules:bt}]],mergeConfig(t,e){const n=O(t,e);return t.attributes&&(n.attributes=O(t.attributes,n.attributes)),n},name:\"@lexical/link/Link\",nodes:()=>[lt],register:(t,e,n)=>Ut(t,n.getOutput())},Tt={dependencies:[St],name:\"@lexical/link/Import\"};function Lt(t,e,n={}){const r=n=>{const r=1===n.button;if(\"auxclick\"===n.type&&!r)return;const i=n.target;if(!z(i))return;const l=$(i);if(null===l)return;let o=null,s=null,u=!1;if(l.update(()=>{const t=W(i);if(null!==t){const n=h(t,T);if(!e.disabled.peek())if(gt(n))u=pt(n)&&n.getIsUnlinked(),o=n.sanitizeUrl(n.getURL()),s=n.getTarget();else{const t=function(t,e){let n=t;for(;null!=n;){if(e(n))return n;n=n.parentNode}return null}(i,a);null!==t&&(o=t.href,s=t.target)}}}),null===o||\"\"===o||u)return;const c=t.read(\"latest\",_);!g(c)||c.isCollapsed()?(window.open(o,e.newTab.peek()||r||n.metaKey||n.ctrlKey||\"_blank\"===s?\"_blank\":\"_self\"),n.preventDefault()):n.preventDefault()};return t.registerRootListener(t=>{if(t)return E(t,{auxclick:r,click:r},n)})}const Ct={build:(t,e,r)=>n(e),config:{disabled:!1,newTab:!1},dependencies:[St],name:\"@lexical/link/ClickableLink\",register:(t,e,n)=>Lt(t,n.getOutput())};function At(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 Nt=/((https?:\\/\\/(www\\.)?)|(www\\.))[-\\p{L}\\p{N}@:%._+~#=]{1,256}\\.[\\p{L}\\p{N}]{1,6}(?:[-\\p{L}\\p{N}()@:%_+.~#?&//=]*[\\p{L}\\p{N}()@_~#?&//=])?/u,Rt=t=>{const e=Nt.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}`}},Pt=/* @__PURE__ */At(/(([^<>()[\\]\\\\.,;:\\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 Ot(t,e){for(let n=0;n<e.length;n++){const r=e[n](t);if(r)return r}return null}const It=/[.,;\\s]/;function wt(t,e){return e.test(t)}function Ft(t,e){return wt(t[t.length-1],e)}function Dt(t,e){return wt(t[0],e)}function Mt(t,e){let n=t.getPreviousSibling();return T(n)&&(n=n.getLastDescendant()),null===n||B(n)||D(n)&&Ft(n.getTextContent(),e)}function Et(t,e){let n=t.getNextSibling();return T(n)&&(n=n.getFirstDescendant()),null===n||B(n)||D(n)&&Dt(n.getTextContent(),e)}function zt(t,e,n,r,i){return!!(t>0?wt(r[t-1],n):Mt(i[0],n))&&(e<r.length?wt(r[e],n):Et(i[i.length-1],n))}function $t(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 Wt(t,e,n,r){const i=_t(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=j(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=_(),c=a?a.getNodes().find(D):void 0,f=j(l.getTextContent());return f.setFormat(l.getFormat()),f.setDetail(l.getDetail()),f.setStyle(l.getStyle()),i.append(f,...s),c&&c===l&&(g(a)?f.select(a.anchor.offset,a.focus.offset):p(a)&&f.select(0,f.getTextContent().length)),l.replace(i),u}}function Kt(t,e,n,r){const i=t.getChildren(),l=i.length;for(let e=0;e<l;e++){const r=i[e];if(!D(r)||!r.isSimpleText())return Bt(t),void n(null,t.getURL())}const o=t.getTextContent(),s=Ot(o,e);if(null===s||s.text!==o)return Bt(t),void n(null,t.getURL());if(!Mt(t,r)||!Et(t,r))return Bt(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 Bt(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 jt={changeHandlers:[],excludeParents:[],matchers:[],separatorRegex:It};function Jt(t,e=jt){const{matchers:n,changeHandlers:r,excludeParents:i,separatorRegex:l=It}=e,o=(t,e)=>{for(const n of r)n(t,e)};return I(t.registerNodeTransform(K,t=>{const e=t.getParentOrThrow(),r=t.getPreviousSibling();if(pt(e))Kt(e,n,o,l);else if(!gt(e)&&!i.some(t=>t(e))){if(t.isSimpleText()&&(Dt(t.getTextContent(),l)||!pt(r))){const e=function(t){const e=[t];let n=t.getNextSibling();for(;null!==n&&D(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(pt(t)&&!t.getIsUnlinked())return}let i=[...t];const l=i.map(t=>t.getTextContent()).join(\"\");let o,s=l,u=0;for(;(o=Ot(s,e))&&null!==o;){const t=o.index,e=t+o.length;if(zt(u+t,u+e,r,l,i)){const[r,,l,a]=$t(i,u+t,u+e);let c=!1;for(const t of l){const e=t.getParent();if(pt(e)&&!e.getIsUnlinked()){c=!0;break}}if(c){u+=e,s=s.substring(e);continue}const g=Wt(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(!pt(i)||i.getIsUnlinked()){if(pt(l)&&!l.getIsUnlinked()&&l.is(t.getPreviousSibling())&&t.getParent()===l.getParent()){if(!Dt(s,r))return Bt(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=Ot(i,e);null!==o&&o.text===i&&(l.append(t),Kt(l,e,n,r),n(null,l.getURL()))}}var u;!pt(o)||o.getIsUnlinked()||Ft(s,r)||o.is(t.getNextSibling())&&t.getParent()===o.getParent()&&(Bt(o),n(null,o.getURL()))}}(t,n,o,l)}}),t.registerCommand(ht,t=>{const e=_();return!(null!==t||!g(e))&&(e.extract().forEach(t=>{const e=t.getParent();pt(e)&&(e.setIsUnlinked(!e.getIsUnlinked()),e.markDirty())}),!1)},M))}const Zt={config:jt,dependencies:[kt,St],mergeConfig(t,e){const n=O(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:[dt],register:Jt};export{_t as $createAutoLinkNode,ct as $createLinkNode,pt as $isAutoLinkNode,gt as $isLinkNode,xt as $toggleLink,kt as AutoLinkAnnounceExtension,Zt as AutoLinkExtension,dt as AutoLinkNode,Ct as ClickableLinkExtension,St as LinkExtension,Tt as LinkImportExtension,bt as LinkImportRules,lt as LinkNode,ht as TOGGLE_LINK_COMMAND,Pt as autoLinkEmailMatcher,Rt as autoLinkUrlMatcher,At as createLinkMatcherWithRegExp,vt as formatUrl,Jt as registerAutoLink,Lt as registerClickableLink,Ut 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 g,$normalizeCaret as d,$getChildCaret as f,getterTableOf as h,setterTableOf as p,setterDefaultOf as m,aliasTableOf as _,$applyNodeReplacement as y,ElementNode as C,buildImportMap as v,$getSiblingCaret as x,$insertNodeToNearestRootAtCaret as S,$rewindSiblingCaret as b,$getDocument as k,setDOMStyleFromCSS as T,isHTMLElement as L,$isParagraphNode as N,nodeSchema as F,withField as P,numberValue as A,withAccessors as I,optional as O,booleanValue as E,$setFormatFromDOM as w,$setDirectionFromDOM as M,normalizeClassNames as D,removeClassNamesFromElement as $,addClassNamesToElement as R,getStyleObjectFromCSS as K,enumValue as W,aliasedValue as B,createCommand as U,mergeRegister as z,COMMAND_PRIORITY_LOW as q,KEY_ARROW_DOWN_COMMAND as V,KEY_ARROW_UP_COMMAND as J,KEY_ESCAPE_COMMAND as j,KEY_SPACE_COMMAND as H,$getNearestNodeFromDOMNode as X,KEY_ARROW_LEFT_COMMAND as G,$findMatchingParent as Z,getActiveElement as Q,registerEventListeners as Y,IS_FIREFOX as tt,registerEventListener as et,getNearestEditorFromDOMNode as nt,$addUpdateTag as rt,SKIP_SELECTION_FOCUS_TAG as it,SKIP_DOM_SELECTION_TAG as st,$createLineBreakNode as ot,$getNodeByKey as lt,INSERT_PARAGRAPH_COMMAND as ct,KEY_BACKSPACE_COMMAND as at,COMMAND_PRIORITY_BEFORE_EDITOR as ut,TextNode as gt}from\"lexical\";import{effect as dt}from\"@lexical/extension/signals\";import{namedSignals as ft}from\"@lexical/extension/namedSignals\";import{sel as ht,isElementOfTag as pt,$propagateTextAlignToBlockChildren as mt,$isBlockLevel as _t,CoreImportExtension as yt,DOMImportExtension as Ct,ImportOverlays as vt,defineOverlayRules as xt,createImportState as St,InlineSchema as bt}from\"@lexical/html\";function kt(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 Tt(t){let e=1,n=t.getParent();for(;null!=n;){if(Yt(n)){const t=n.getParent();if(oe(t)){e++,n=t.getParent();continue}kt(40)}return e}return e}function Lt(t){const e=t.getParent();oe(e)||kt(40);let n=e,r=e;for(;null!==r;)r=r.getParent(),oe(r)&&(n=r);return n}function Nt(t){let e=[];const n=t.getChildren().filter(Yt);for(let t=0;t<n.length;t++){const r=n[t],i=r.getFirstChild();oe(i)?e=e.concat(Nt(i)):e.push(r)}return e}function Ft(t){return Yt(t)&&oe(t.getFirstChild())}function Pt(t,e){return e.getValue()}function At(t,e){return Yt(t)&&(0===e.length||1===e.length&&t.is(e[0])&&0===t.getChildrenSize())}function It(t,e){return oe(t)?l(t).setListType(e):se(e)}function Ot(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(At(i,n)){if(s(l)){const e=se(t);i.replace(e);const n=Qt();c(i)&&(n.setFormat(i.getFormatType()),n.setIndent(i.getIndent())),e.append(n)}else if(Yt(i)){const e=i.getParentOrThrow();if(null===a(e)){const n=It(e,t);Et(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()&&!Yt(r)&&null===a(r)&&!i.has(r.getKey())){wt(r,t);continue}let o=u(r)?r.getParent():Yt(r)&&r.isEmpty()?r:null;for(;null!=o;){const e=o.getKey();if(oe(o)){if(!i.has(e)&&null===a(o)){const n=It(o,t);Et(n,o.getChildren()),o.replace(n),i.add(e)}break}{const n=o.getParent();if(s(n)&&!i.has(e)){i.add(e),wt(o,t);break}o=n}}}}}function Et(t,e){t.splice(t.getChildrenSize(),0,e)}function wt(t,e){if(oe(t))return t;const i=t.getPreviousSibling(),s=t.getNextSibling(),o=Qt();let l;if(Et(o,t.getChildren()),oe(i)&&e===i.getListType())i.append(o),oe(s)&&e===s.getListType()&&(Et(i,s.getChildren()),s.remove()),l=i;else if(oe(s)&&e===s.getListType())s.getFirstChildOrThrow().insertBefore(o),l=s;else{const n=se(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 Mt(t,e){const n=t.getLastChild(),r=e.getFirstChild();n&&r&&Ft(n)&&Ft(r)&&n.getFirstChild().getListType()===r.getFirstChild().getListType()&&(Mt(n.getFirstChild(),r.getFirstChild()),r.remove());const i=e.getChildren();i.length>0&&t.append(...i),e.remove()}function Dt(){const e=n();if(r(e)){const n=new Set,r=e.getNodes(),i=e.anchor.getNode();if(At(i,r))n.add(Lt(i));else for(let e=0;e<r.length;e++){const i=r[e];if(u(i)){const e=t(i,Ht);null!=e&&n.add(Lt(e))}}for(const t of n){if(null!==a(t))continue;let n=t;const r=Nt(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()),Et(r,t.getChildren()),n.insertAfter(r),n=r,t.__key===e.anchor.key&&g(e.anchor,d(f(r,\"next\"))),t.__key===e.focus.key&&g(e.focus,d(f(r,\"next\"))),t.remove()}t.remove()}}}function $t(t){const e=\"check\"!==t.getListType();let n=t.getStart();for(const r of t.getChildren())Yt(r)&&(r.getValue()!==n&&r.setValue(n),e&&null!=r.getLatest().__checked&&r.setChecked(void 0),oe(r.getFirstChild())||n++)}function Rt(t){const e=new Set;if(Ft(t)||e.has(t.getKey()))return;const n=t.getParent(),r=t.getNextSibling(),i=t.getPreviousSibling();if(Ft(r)&&Ft(i)){const n=i.getFirstChild();if(oe(n)){n.append(t);const i=r.getFirstChild();oe(i)&&n.getListType()===i.getListType()&&(Et(n,i.getChildren()),r.remove(),e.add(r.getKey()))}}else if(Ft(r)){const e=r.getFirstChild();if(oe(e)){const n=e.getFirstChild();null!==n&&n.insertBefore(t)}}else if(Ft(i)){const e=i.getFirstChild();oe(e)&&e.append(t)}else if(oe(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 Kt(t){if(Ft(t))return;const e=t.getParent(),n=e?e.getParent():void 0;if(oe(n?n.getParent():void 0)&&Yt(n)&&oe(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),Et(o,t.getNextSiblings()),n.insertBefore(r),n.insertAfter(s),n.replace(t)}}}function Wt(t=!1){const e=n();if(!r(e)||!e.isCollapsed())return!1;const c=e.anchor.getNode();let a=null;if(Yt(c)&&0===c.getChildrenSize())a=c;else if(i(c)){const t=c.getParent();Yt(t)&&t.getChildren().every(t=>i(t)&&\"\"===t.getTextContent().trim())&&(a=t)}if(null===a)return!1;const u=Lt(a),g=a.getParent();oe(g)||kt(40);const d=g.getParent();let f;if(s(d))f=o(),u.insertAfter(f);else{if(!Yt(d))return!1;f=l(d),d.insertAfter(f)}f.setTextStyle(e.style).setTextFormat(e.format).select();const h=a.getNextSiblings();if(h.length>0){const e=t?Pt(0,a):1,n=l(g).setStart(e);if(Yt(f)){const t=l(f);t.append(n),f.insertAfter(t)}else f.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||!Yt(t)&&!oe(t))break;e=t}e.remove()}(a),!0}const Bt=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function Ut(t,e){if(\"number\"==typeof t)return Number.isFinite(t)?t:e;if(\"string\"!=typeof t||!Bt.test(t))return e;const n=Number(t);return Number.isFinite(n)?n:e}function zt(t,e){t.__listType=e.__listType,t.__start=e.__start,t.__tag=e.__tag}const qt=t=>{const e=h(t,\"format\"),n=p(t,\"format\"),r=m(t,\"format\"),i=_(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=Ut(t,0);return e>=0&&e<=Infinity&&Number.isInteger(e)?e:0}(e.indent),t.__textFormat=Ut(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=Ut(e.start,1),t},afterCloneFrom:zt}};function Vt(t,e){t.__checked=e.__checked,t.__value=e.__value}const Jt=t=>{const e=h(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:[],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=Ut(t,NaN);return Number.isFinite(e)&&Number.isInteger(e)?e<0?0:e>128?128:e:0}(e.indent)),t.__textFormat=Ut(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=Ut(e.value,1),t},afterCloneFrom:Vt}},jt=/* @__PURE__ */F()({checked:/* @__PURE__ */I(/* @__PURE__ */O(/* @__PURE__ */E()),{setter:{field:\"__checked\"}}),indent:/* @__PURE__ */A(0,{clamp:!0,integer:!0,max:128,min:0}),value:/* @__PURE__ */P(/* @__PURE__ */A(1),{field:\"__value\"})});class Ht extends C{__value;__checked;$config(){return this.config(\"listitem\",{$transform:t=>{const e=t.getParent();if(oe(e))\"check\"!==e.getListType()&&null!=t.getChecked()&&t.setChecked(void 0);else if(e){const n=t.createParentElementNode();oe(n)||kt(340);const r=[t];for(const e of[\"previous\",\"next\"]){r.reverse();for(const{origin:n}of x(t,e)){if(!Yt(n))break;r.push(n)}}t.insertBefore(n),n.splice(0,0,r),s(e)||(S(n,b(x(n,\"next\")),{$shouldSplit:()=>!1,removeEmptyDestination:!0}),e.isEmpty()&&e.isAttached()&&e.remove())}},extends:C,generated:Jt,importDOM:v({li:()=>({conversion:Xt,priority:0})}),json:jt})}constructor(t=1,e=void 0,n){super(n),this.__value=void 0===t?1:t,this.__checked=e}createDOM(t){const e=k().createElement(\"li\");return this.updateListItemDOM(null,e,t),e}updateListItemDOM(t,e,n){!function(t,e){const n=e.getParent();!oe(n)||\"check\"!==n.getListType()||oe(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=oe(o)&&\"check\"===o.getListType(),c=n.getChecked(),a=n.getChildren().some(t=>oe(t)),u=[];void 0!==r.listitemChecked&&u.push(r.listitemChecked),void 0!==r.listitemUnchecked&&u.push(r.listitemUnchecked),void 0!==s&&u.push(...D(s)),u.length>0&&$(t,...u);const g=[];if(void 0!==i&&g.push(...D(i)),l){const t=c?r.listitemChecked:r.listitemUnchecked;void 0!==t&&g.push(t)}void 0!==s&&a&&g.push(...D(s)),g.length>0&&R(t,...g)}(e,n.theme,this);const r=t?t.__style:\"\",i=this.__style;r!==i&&T(e.style,i,r),function(t,e,n){const r=e.__textStyle,i=n?n.__textStyle:\"\";if(null!==n&&i===r)return;const s=K(r);for(const e in s)t.style.setProperty(`--listitem-marker-${e}`,s[e]);if(\"\"!==i)for(const e in K(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),Ft(this)?{after(t){if(L(t)){const e=t.previousElementSibling;if(L(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(Yt(t))return super.replace(t);this.setIndent(0);const i=this.getParentOrThrow();if(!oe(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)||kt(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(oe(n)||kt(39),Yt(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()&&Yt(s)&&i.setStart(Pt(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&&Ft(e)&&Ft(n)&&e.getFirstChild().getListType()===n.getFirstChild().getListType()&&(Mt(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(Ft(this))return!1;const e=this.getParentOrThrow();if(Yt(e.getParentOrThrow()))return Kt(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 oe(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(;Yt(e);)e=e.getParentOrThrow().getParentOrThrow(),n++;return n}setIndent(t){\"number\"!=typeof t&&kt(117),(t=Math.floor(t))>=0||kt(199);const e=t;let n=this.getIndent();for(;n!==e;)n<e?(Rt(this),n++):(Kt(this),n--);return this}canInsertAfter(t){return Yt(t)}canReplaceWith(t){return Yt(t)}canMergeWith(t){return Yt(t)||N(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 se(\"bullet\")}canMergeWhenEmpty(){return!0}}function Xt(t){if(t.classList.contains(\"task-list-item\"))for(const e of t.children)if(\"INPUT\"===e.tagName)return Gt(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 Gt(e.children[0]);const e=t.getAttribute(\"aria-checked\"),n=Qt(\"true\"===e||\"false\"!==e&&void 0);return w(n,t),{after:Zt.bind(null,n),node:M(n,t)}}function Gt(t){if(\"checkbox\"!==t.getAttribute(\"type\"))return{node:null};const e=Qt(t.hasAttribute(\"checked\"));return{after:Zt.bind(null,e),node:e}}function Zt(t,e){const n=e[0];return 1===e.length&&N(n)&&!t.getFormatType()&&n.getFormatType()?(t.setFormat(n.getFormatType()),n.getChildren()):e}function Qt(t){return y(new Ht(void 0,t))}function Yt(t){return t instanceof Ht}const te={ol:\"number\",ul:\"bullet\"},ee=/* @__PURE__ */F()({listType:/* @__PURE__ */I(/* @__PURE__ */B(/* @__PURE__ */W([\"number\",\"bullet\",\"check\"]),te),{getter:{field:\"__listType\"}}),start:/* @__PURE__ */P(/* @__PURE__ */A(1),{field:\"__start\"}),tag:/* @__PURE__ */I(/* @__PURE__ */W([\"ul\",\"ol\"]),{getter:{field:\"__tag\"},setter:null})});class ne extends C{__tag;__start;__listType;$config(){return this.config(\"list\",{$transform:t=>{!function(t){const e=t.getNextSibling();oe(e)&&t.getListType()===e.getListType()&&Mt(t,e)}(t),$t(t)},extends:C,generated:qt,importDOM:v({ol:()=>({conversion:ie,priority:0}),ul:()=>({conversion:ie,priority:0})}),json:ee})}constructor(t=\"number\",e=1,n){super(n);const r=te[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=k().createElement(n);return 1!==this.__start&&r.setAttribute(\"start\",String(this.__start)),r.__lexicalListType=this.__listType,re(r,t.theme,this),r}updateDOM(t,e,n){return t.__tag!==this.__tag||t.__listType!==this.__listType||(re(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(L(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}canIndent(){return!1}splice(t,e,n){let r=n;for(let t=0;t<n.length;t++){const e=n[t];if(!Yt(e)){r===n&&(r=[...n]);const i=this.createListItemNode();!c(e)||oe(e)||e.isInline()?i.append(e):i.append(...e.getChildren()),r[t]=i}}return super.splice(t,e,r)}extractWithChild(t){return Yt(t)}createListItemNode(){return Qt()}}function re(t,e,n){const r=[],i=[],s=e.list;if(void 0!==s){const t=s[`${n.__tag}Depth`]||[],e=Tt(n)-1,o=e%t.length,l=t[o],c=s[n.__tag];let a;const u=s.nested,g=s.checklist;if(void 0!==u&&u.list&&(a=u.list),void 0!==c&&r.push(c),void 0!==g&&\"check\"===n.__listType&&r.push(g),void 0!==l){r.push(...D(l));for(let e=0;e<t.length;e++)e!==o&&i.push(...D(t[e]))}if(void 0!==a){const t=D(a);e>1?r.push(...t):i.push(...t)}}i.length>0&&$(t,...i),r.length>0&&R(t,...r)}function ie(t){let e;if(function(t){return L(t)&&\"ol\"===t.nodeName.toLowerCase()}(t)){const n=t.start;e=se(\"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(L(e)&&e.hasAttribute(\"aria-checked\"))return!0;return!1}(t)?se(\"check\"):se(\"bullet\");return M(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(Yt(i)){r.push(i);const t=i.getChildren();t.length>1&&t.forEach(t=>{oe(t)&&r.push(n().append(t))})}else r.push(n().append(i))}return r}(t,e),node:e}}function se(t=\"number\",e=1){return y(new ne(t,e))}function oe(t){return t instanceof ne}const le=new Set([\" \",\"Alt\",\"ArrowDown\",\"ArrowLeft\",\"ArrowUp\",\"CapsLock\",\"Control\",\"Escape\",\"Meta\",\"Shift\"]),ce=/* @__PURE__ */U(\"INSERT_CHECK_LIST_COMMAND\");function ae(t,e){const i=e&&e.disableTakeFocusOnClick||!1,s=\"boolean\"==typeof i?()=>i:i.peek.bind(i),o=t=>{const e=t.target;if(!L(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 ue(t,()=>{n=!0,t.preventDefault(),e&&t.stopPropagation()}),n}(t,s())?\"checkMark\":\"content\"},u=()=>{\"content\"===l&&de(t),l=\"none\"};return z(t.registerCommand(ce,()=>(Ot(\"check\"),!0),q),t.registerCommand(V,e=>pe(e,t,!1),q),t.registerCommand(J,e=>pe(e,t,!0),q),t.registerCommand(j,()=>{if(null!=he(t)){const e=t.getRootElement();return null!=e&&e.focus(),!0}return!1},q),t.registerCommand(H,e=>{const n=he(t);return!(null==n||!t.isEditable()||(t.update(()=>{const t=X(n);Yt(t)&&(e.preventDefault(),t.toggleChecked())}),0))},q),t.registerCommand(G,e=>null!==he(t)?(de(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=Z(i,t=>c(t)&&!t.isInline());if(Yt(s)){const n=s.getParent();if(oe(n)&&\"check\"===n.getListType()&&(r||s.getFirstDescendant()===i)){const n=t.getElementByKey(s.__key);if(null!=n&&Q(n)!==n)return n.focus(),e.preventDefault(),!0}}}}return!1}),q),t.registerRootListener(e=>{if(null!==e)return z(Y(e,{click:t=>{u(),(t=>{o(t)||ge(t,s())})(t)},pointerup:t=>{u(),(t=>{\"touch\"===t.pointerType&&(o(t)||((t=>{const e=t.target;L(e)&&(e.__lexicalCheckListLastHandled=t.timeStamp)})(t),ge(t,s())))})(t)}}),Y(e,{beforeinput:()=>de(t),focusin:()=>{tt&&\"content\"===l&&de(t)},keydown:e=>{le.has(e.key)||de(t)},mousedown:a,pointerdown:a},{capture:!0}),et(e,\"touchstart\",a,{capture:!0,passive:!1}))}))}function ue(t,n){const r=t.target;if(!L(r))return;const i=r.firstChild;if(L(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,g=u?u.getComputedStyle(r,\"::before\"):{width:\"0px\"},d=parseFloat(g.width),f=\"touch\"===l||\"pointerType\"in t&&\"touch\"===t.pointerType?32:0;(\"rtl\"===r.dir?a<c.right+f&&a>c.right-d-f:a>c.left-f&&a<c.left+d+f)&&n()}function ge(t,e){ue(t,()=>{if(L(t.target)){const n=t.target,r=nt(n);null!=r&&r.isEditable()&&r.update(()=>{const t=X(n);Yt(t)&&(e?(rt(it),rt(st)):n.focus(),t.toggleChecked())})}})}function de(t){const e=t.getRootElement(),n=e?Q(e):null;null!==e&&L(n)&&fe(n)&&e.focus({preventScroll:!0})}function fe(t){const e=t.parentNode;return\"LI\"===t.tagName&&null!=e&&\"check\"===e.__lexicalListType}function he(t){const e=t.getRootElement(),n=e?Q(e):null;return L(n)&&fe(n)?n:null}function pe(t,e,n){const r=he(e);if(null!=r){let i=null;e.update(()=>{const s=X(r);if(!Yt(s))return;const o=function(t,e){let n=e?t.getPreviousSibling():t.getNextSibling(),r=t;for(;null==n&&Yt(r);)r=r.getParentOrThrow().getParent(),null!=r&&(n=e?r.getPreviousSibling():r.getNextSibling());for(;Yt(n);){const t=e?n.getLastChild():n.getFirstChild();if(!oe(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 me(t,e){const n=[];for(const r of t)if(Yt(r)){n.push(r);const t=r.getChildren();if(t.length>1)for(const r of t)oe(r)&&n.push(e.createListItemNode().append(r))}else n.push(e.createListItemNode().append(r));return n}const _e={$import:(t,e)=>{let n;var r;return n=pt(e,\"ol\")?se(\"number\",e.start):(r=e).matches('[__lexicallisttype=\"check\"], .contains-task-list, [data-is-checklist=\"1\"]')||null!==r.querySelector(\":scope > [aria-checked]\")?se(\"check\"):se(\"bullet\"),M(n,e),[n.splice(0,0,mt(me(t.$importChildren(e),n),e))]},match:/* @__PURE__ */ht.tag(\"ol\",\"ul\"),name:\"@lexical/list/list\"};function ye(t,e){if(1!==e.length)return e;const n=e[0];return N(n)&&!t.getFormatType()&&n.getFormatType()?(t.setFormat(n.getFormatType()),n.getChildren()):e}function Ce(t){const e=t=>_t(t)&&!oe(t);if(!t.some(e))return t;const n=[];let r=[];const i=()=>{r.length>0&&(n.push(r),r=[])};for(const s of t)e(s)?(i(),n.push(c(s)?s.getChildren():[s])):r.push(s);i();const s=[];for(const t of n)s.length>0&&s.push(ot()),s.push(...t);return s}const ve={$import:(t,e)=>{const n=e.getAttribute(\"aria-checked\"),r=Qt(\"true\"===n||\"false\"!==n&&void 0);return w(r,e),M(r,e),[r.splice(0,0,Ce(ye(r,t.$importChildren(e))))]},match:/* @__PURE__ */ht.tag(\"li\"),name:\"@lexical/list/li\"};function xe(t,e,n){const r=pt(n,\"input\")?n:n.querySelector('input[type=\"checkbox\"]');if(!r||\"checkbox\"!==r.getAttribute(\"type\"))return[];const i=Qt(r.hasAttribute(\"checked\"));return w(i,e),M(i,e),[i.splice(0,0,Ce(ye(i,t.$importChildren(e))))]}const Se={$accepts:t=>Yt(t)||oe(t),$packageRun:t=>[Qt().splice(0,0,t)],name:\"ListSchema\"},be=[{$import:(t,e,n)=>{const r=e.querySelector(':scope > input[type=\"checkbox\"]');return r?xe(t,e,r):n()},match:/* @__PURE__ */ht.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?xe(t,e,i):n()},match:/* @__PURE__ */ht.tag(\"li\").classAll(\"joplin-checkbox\"),name:\"@lexical/list/li-joplin-checkbox\"},_e,ve],ke=/* @__PURE__ */U(\"UPDATE_LIST_START_COMMAND\"),Te=/* @__PURE__ */U(\"INSERT_UNORDERED_LIST_COMMAND\"),Le=/* @__PURE__ */U(\"INSERT_ORDERED_LIST_COMMAND\"),Ne=/* @__PURE__ */U(\"REMOVE_LIST_COMMAND\");function Fe(t,e){return z(t.registerCommand(Le,()=>(Ot(\"number\"),!0),q),t.registerCommand(ke,t=>{const{listNodeKey:e,newStart:n}=t,r=lt(e);return!!oe(r)&&(\"number\"===r.getListType()&&(r.setStart(n),$t(r)),!0)},q),t.registerCommand(Te,()=>(Ot(\"bullet\"),!0),q),t.registerCommand(Ne,()=>(Dt(),!0),q),t.registerCommand(ct,()=>Wt(!(!e||!e.restoreNumbering)),q),t.registerCommand(at,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(;!Yt(s);){if(null!==s.getPreviousSibling())return!1;const t=s.getParent();if(null===t)return!1;s=t}return!(!Yt(s)||!s.collapseAtStart(e)||(t.preventDefault(),0))},ut),t.registerNodeTransform(Ht,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(gt,t=>{const e=t.getParent();if(Yt(e)&&t.is(e.getFirstChild())){const n=t.getStyle(),r=t.getFormat();n===e.getTextStyle()&&r===e.getTextFormat()||e.setTextStyle(n).setTextFormat(r)}}))}function Pe(t){const e=t=>{const e=t.getParent();if(oe(t.getFirstChild())||!oe(e))return;const n=Z(t,t=>Yt(t)&&oe(t.getParent())&&Yt(t.getPreviousSibling()));if(null===n&&t.getIndent()>0)t.setIndent(0);else if(Yt(n)){const r=n.getPreviousSibling();if(Yt(r)){const n=function(t){let e=t,n=e.getFirstChild();for(;oe(n);){const t=n.getLastChild();if(!Yt(t))break;e=t,n=e.getFirstChild()}return e}(r),i=n.getParent();if(oe(i)){const n=Tt(i);n+1<Tt(e)&&t.setIndent(n)}}}};return t.registerNodeTransform(ne,t=>{const n=[t];for(;n.length>0;){const t=n.shift();if(oe(t))for(const r of t.getChildren())if(Yt(r)){e(r);const t=r.getFirstChild();oe(t)&&n.push(t)}}})}const Ae={build:(t,e,n)=>ft(e),config:{hasStrictIndent:!1,shouldPreserveNumbering:!1},dependencies:[yt,[Ct,{rules:be}]],name:\"@lexical/list/List\",nodes:()=>[ne,Ht],register(t,e,n){const r=n.getOutput();return z(dt(()=>Fe(t,{restoreNumbering:r.shouldPreserveNumbering.value})),dt(()=>r.hasStrictIndent.value?Pe(t):void 0))}},Ie={build:(t,e)=>ft(e),config:{disableTakeFocusOnClick:!1},dependencies:[Ae],name:\"@lexical/list/CheckList\",register:(t,e,n)=>ae(t,n.getOutput())},Oe={dependencies:[Ae],name:\"@lexical/list/Import\"},Ee=/^MsoListParagraph(CxSp(First|Middle|Last))?$/,we=/^[A-Za-z0-9]+[.)]/,Me=/Microsoft Word/i,De=\"data-mso-list\";function $e(t){const e=(t.getAttribute(De)||\"\").match(/level(\\d+)/);return e?parseInt(e[1],10):1}function Re(t){return t.querySelector(`span[${De}=\"Ignore\"]`)}function Ke(t){const e=Re(t);return e?(e.textContent||\"\").trim():\"\"}function We(t){return we.test(t)?\"number\":\"bullet\"}function Be(t){const e=Re(t);if(!e)return;let n=e;for(;n.parentElement&&n.parentElement!==t&&\"SPAN\"===n.parentElement.nodeName;)n=n.parentElement;n.remove()}function Ue(t){return L(t)&&Ee.test(t.className)}function ze(t,e){const n=se(We(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=se(We(n.marker));r[r.length-1].list.append(Qt().append(t)),r.push({level:n.level,list:t})}Be(n.el),r[r.length-1].list.append(Qt().splice(0,0,t.$importChildren(n.el,{schema:bt})))}return n}const qe=/* @__PURE__ */St(\"@lexical/list/word-consumed-list-items\",()=>null),Ve={$import:(t,e)=>{let n=t.session.get(qe);if(null===n&&(n=new WeakSet,t.session.set(qe,n)),n.has(e))return[];const r=[];let i=e;for(;i&&Ue(i)&&(n.add(i),r.push({el:i,level:$e(i),marker:Ke(i)}),!i.classList.contains(\"MsoListParagraphCxSpLast\")&&\"MsoListParagraph\"!==i.className);)i=i.nextElementSibling;return[ze(t,r)]},match:/* @__PURE__ */ht.tag(\"p\").classAny(\"MsoListParagraph\",\"MsoListParagraphCxSpFirst\",\"MsoListParagraphCxSpMiddle\",\"MsoListParagraphCxSpLast\"),name:\"@lexical/list/word-list-paragraph\"},Je=/* @__PURE__ */xt([{$import:()=>[],match:/* @__PURE__ */ht.tag(\"o:p\"),name:\"@lexical/list/word-o-p\"},Ve]),je={dependencies:[Ae,[Ct,{preprocess:[(t,e,n)=>{const r=t.querySelector('meta[name=\"Generator\"]');if(r&&Me.test(r.getAttribute(\"content\")||\"\")){for(const e of Array.from(t.querySelectorAll('[style*=\"mso-list\"]'))){const t=K(e.getAttribute(\"style\")||\"\")[\"mso-list\"];t&&e.setAttribute(De,t)}e.session.update(vt,t=>[...t,Je])}n()}]}]],name:\"@lexical/list/WordListImport\"};export{Qt as $createListItemNode,se as $createListNode,Tt as $getListDepth,Wt as $handleListInsertParagraph,Ot as $insertList,Yt as $isListItemNode,oe as $isListNode,Dt as $removeList,Ie as CheckListExtension,ce as INSERT_CHECK_LIST_COMMAND,Le as INSERT_ORDERED_LIST_COMMAND,Te as INSERT_UNORDERED_LIST_COMMAND,Ae as ListExtension,Oe as ListImportExtension,be as ListImportRules,Ht as ListItemNode,ne as ListNode,Se as ListSchema,Ne as REMOVE_LIST_COMMAND,ke as UPDATE_LIST_START_COMMAND,je as WordListImportExtension,ae as registerCheckList,Fe as registerList,Pe 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 x,COPY_COMMAND as y,COMMAND_PRIORITY_CRITICAL as h,$isTextNode as T,$exportNodeJSON as b,$isNodeSelection as C,$getSlotNames as w,$getSlot as M,$normalizeCaret as $,$isTextPointCaret as v,$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,$getChildCaretAtIndex as A,$getCaretRangeInDirection as j,$caretRangeFromSelection as k,$comparePointCaretNext as L,findAllLexicalElementsDeep as _,getEditorPropertyFromDOMNode as J,isLexicalEditor as W,isHTMLElement as H,$rewindSiblingCaret as z,$isChildCaret as B,$getSiblingCaret as U}from\"lexical\";import{getPeerDependencyFromEditor as X}from\"@lexical/extension/getPeerDependencyFromEditor\";import{CoreImportExtension as G,$generateNodesFromDOMViaExtension as Y,contextValue as q,ImportSource as Q,ImportSourceDataTransfer as V,$generateNodesFromDOM as Z,$generateHtmlFromNodes as tt}from\"@lexical/html\";import{$sliceSelectedTextNodeContent as et}from\"@lexical/selection\";import{objectKlassEquals as nt}from\"@lexical/utils\";import{$getPeerDependency as ot}from\"@lexical/extension/getExtensionDependency\";function rt(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 it(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 lt={\"application/x-lexical-editor\":0,\"text/html\":10,\"text/plain\":20,\"text/uri-list\":30};function ct(t){return window.trustedTypes&&window.trustedTypes.createPolicy?window.trustedTypes.createPolicy(\"lexical\",{createHTML:t=>t}).createHTML(t):t}const st=(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},ut={\"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 vt(n,Nt(o.nodes),e),!0}catch(t){console.error(t)}return n()}],\"text/html\":[(t,e,n)=>{try{const n=r(),o=(new DOMParser).parseFromString(ct(t),\"text/html\");return vt(n,Z(n,o),e),!0}catch(t){return console.error(t),n()}}],\"text/plain\":[st],\"text/uri-list\":[st]};function ft(t,e,n,o){if(!t)return!1;const r=i=>!!t[i]&&t[i](e,n,r.bind(null,i-1),o);return r(t.length-1)}function at(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)&&ft(t.$importMimeType[r],i,n,e))return!0}return!1}const pt={$importMimeType:ut,$insertDataTransfer:(t,e)=>at({$importMimeType:ut,priority:lt},t,e),priority:lt},dt={build:(t,e)=>({$importMimeType:e.$importMimeType,$insertDataTransfer:(t,n)=>at(e,t,n),priority:e.priority}),config:{$importMimeType:ut,priority:lt},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\"},mt={dependencies:[G,[dt,{$importMimeType:{\"text/html\":[(t,e,n,o)=>{const i=(new DOMParser).parseFromString(ct(t),\"text/html\"),l=Y(i,{context:[q(Q,\"paste\"),q(V,o)]});return vt(r(),l,e),!0}]}}]],name:\"@lexical/clipboard/DOMImport\"};function gt(t,e=c()){return null==e&&it(166),l(e)&&e.isCollapsed()||0===e.getNodes().length?\"\":tt(t,e)}function xt(t,e=c()){return null==e&&it(166),l(e)&&e.isCollapsed()||0===e.getNodes().length?null:JSON.stringify(Pt(t,e))}function yt(t,e){const n=t.getData(\"text/plain\")||t.getData(\"text/uri-list\");null!=n&&e.insertRawText(n)}function ht(t,e,n){(function(){const t=ot(dt.name);return t?t.output:pt})().$insertDataTransfer(t,e)}const Tt=\"application/x-lexical-drag\";function bt(t,e){const n={editorKey:e.getKey()};t.setData(Tt,JSON.stringify(n))}function Ct(t){let e=t;if(v(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(B(e))e=z(U(t,\"next\"));else{if(null!==e.getNodeAtCaret())return e;e=U(t,\"next\")}}}function wt(t,e,n){const o=t.dataTransfer;if(null===o)return!1;const r=function(t){const e=t.getData(Tt);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=rt(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);if(d(o))return A(o,n.offset,\"next\");const r=o.getParent();return null===r?null:A(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}=j(k(e),\"next\"),r=Ct(t);return L(Ct(n),r)<=0&&L(r,Ct(o))<=0}(i,u))return t.preventDefault(),!0}const f=$(i),a=v(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()||it(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 _(e)){const e=J(n);if(W(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 Mt(t,e){return wt(t,e,ht)}function $t(t,e){return wt(t,e,(t,e)=>yt(t,e))}function vt(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(v(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 Dt(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=et(e,l,\"clone\"));const c=b(l),s=d(l)?l.getChildren():[],u=c.children||[];T(l)&&0===l.getTextContentSize()&&(r=!1);const f=r&&C(e)&&d(n)?null:e;for(let o=0;o<s.length;o++){const i=s[o],l=Dt(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&&it(366,l.constructor.name,o);const r=[];Dt(t,null,e,r),(1!==r.length||d(e)&&e.excludeFromCopy(\"clone\"))&&it(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 Pt(t,e){const n=[],o=a(),r=p(e),i=(d(r)?r:o).getChildren();for(let o=0;o<i.length;o++)Dt(t,e,i[o],n);return{namespace:t._config.namespace,nodes:n}}function Nt(t){const e=[];for(const n of t)e.push(m(n));return e}let St=null;async function Rt(t,e,n){if(null!==St)return!1;if(null!==e)return new Promise((o,r)=>{t.update(()=>{o(Ft(t,e,n))})});const o=t.getRootElement(),r=t._window||window,i=r.document,l=x(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(y,o=>(nt(o,ClipboardEvent)&&(l(),null!==St&&(r.clearTimeout(St),St=null),e(Ft(t,o,n))),!0),h);St=r.setTimeout(()=>{l(),St=null,e(!1)},50),i.execCommand(\"copy\"),c.remove()})}function Ft(t,e,n){if(void 0===n){const e=x(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=Ot(o)}e.preventDefault();const o=e.clipboardData;return null!==o&&(It(o,n),!0)}const Et=[[\"text/html\",gt],[\"application/x-lexical-editor\",xt]];function Ot(t=c()){return function(t,e){const n={\"text/plain\":\"\"};for(const[o,r]of Object.entries(t))if(r){const t=jt(r,e);null!==t&&(n[o]=t)}return n}(Kt(),t)}function It(t,e){for(const[n]of Et)void 0===e[n]&&t.setData(n,\"\");for(const n in e){const o=e[n];void 0!==o&&t.setData(n,o)}}function Kt(t=r()){const e=X(t,Lt.name);return e?e.output:At}const At={\"application/x-lexical-editor\":[(t,e)=>t?xt(r(),t):e()],\"text/html\":[(t,e)=>t?gt(r(),t):e()],\"text/plain\":[(t,e)=>t?t.getTextContent():e()]};function jt(t,e){const n=o=>t[o]?t[o](e,n.bind(null,o-1)):null;return n(t.length-1)}function kt(t,e=c()){return jt(Kt()[t]||[],e)}const Lt={build:(t,e,n)=>e.$exportMimeType,config:{$exportMimeType:At},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{kt as $exportMimeTypeFromSelection,Pt as $generateJSONFromSelectedNodes,Nt as $generateNodesFromSerializedNodes,Ot as $getClipboardDataFromSelection,gt as $getHtmlContent,xt as $getLexicalContent,$t as $handlePlainTextDrop,Mt as $handleRichTextDrop,yt as $insertDataTransferForPlainText,ht as $insertDataTransferForRichText,vt as $insertGeneratedNodes,bt as $writeDragSourceToDataTransfer,mt as ClipboardDOMImportExtension,dt as ClipboardImportExtension,ut as DEFAULT_IMPORT_MIME_TYPE,lt as DEFAULT_IMPORT_MIME_TYPE_PRIORITY,Lt as GetClipboardDataExtension,rt as caretFromPoint,Rt as copyToClipboard,It 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{$handleIndentAndOutdent as d,eventFiles as g,objectKlassEquals as m,$getNearestBlockElementAncestorOrThrow as p}from\"@lexical/utils\";export{eventFiles}from\"@lexical/utils\";import{getterTableOf as h,setterTableOf as y,setterDefaultOf as x,$getNodeByKey as _,setNodeIndentFromDOM as C,$setFormatFromDOM as v,$setDirectionFromDOM as S,isHTMLElement as D,shallowMergeConfig as N,$applyNodeReplacement as b,createCommand as F,ElementNode as T,$getDocument as K,addClassNamesToElement as E,$createParagraphNode as k,$getState as w,$setState as I,createState as O,booleanValue as A,mergeRegister as z,CLICK_COMMAND as R,$getSelection as P,$isNodeSelection as M,$isRangeSelection as $,COMMAND_PRIORITY_EDITOR as L,DELETE_CHARACTER_COMMAND as B,DELETE_WORD_COMMAND as q,DELETE_LINE_COMMAND as J,CONTROLLED_TEXT_INSERTION_COMMAND as W,REMOVE_TEXT_COMMAND as H,FORMAT_TEXT_COMMAND as j,$formatText as V,SET_TEXT_FORMAT_COMMAND as X,$setTextFormat as Y,FORMAT_ELEMENT_COMMAND as G,$findMatchingParent as Q,$isElementNode as U,INSERT_LINE_BREAK_COMMAND as Z,INSERT_PARAGRAPH_COMMAND as ee,INSERT_TAB_COMMAND as te,$createTabNode as ne,$insertNodes as re,INDENT_CONTENT_COMMAND as oe,OUTDENT_CONTENT_COMMAND as ie,KEY_ARROW_UP_COMMAND as se,KEY_ARROW_DOWN_COMMAND as le,KEY_ARROW_LEFT_COMMAND as ae,KEY_ARROW_RIGHT_COMMAND as ce,KEY_BACKSPACE_COMMAND as ue,IS_IOS as fe,CAN_USE_BEFORE_INPUT as de,KEY_DELETE_COMMAND as ge,KEY_ENTER_COMMAND as me,$isDecoratorNode as pe,IS_SAFARI as he,IS_APPLE_WEBKIT as ye,KEY_ESCAPE_COMMAND as xe,DROP_COMMAND as _e,$getNearestNodeFromDOMNode as Ce,$createRangeSelection as ve,$isTextNode as Se,$normalizeSelection__EXPERIMENTAL as De,$setSelection as Ne,DRAGSTART_COMMAND as be,DRAGOVER_COMMAND as Fe,SELECT_ALL_COMMAND as Te,$selectAll as Ke,$getSlotFrame as Ee,COPY_COMMAND as ke,CUT_COMMAND as we,PASTE_COMMAND as Ie,isDOMNode as Oe,$isSelectionCapturedInDecoratorInput as Ae,KEY_SPACE_COMMAND as ze,KEY_TAB_COMMAND as Re,MOVE_TO_END as Pe,MOVE_TO_START as Me,nodeSchema as $e,withField as Le,enumValue as Be,$getSiblingCaret as qe,$comparePointCaretNext as Je,$setSelectionFromCaretRange as We,$getCaretRangeInDirection as He,$getCaretRange as je,$rewindSiblingCaret as Ve,$flushSyncAfterUpdate as Xe,$getCollapsedCaretRange as Ye,$caretFromPoint as Ge,$isRootOrShadowRoot as Qe,$getEditor as Ue,getDOMSelection as Ze,$hasAncestor as et,$getRoot as tt,$needsBlockCursorBeside as nt,$isRootNode as rt,INTERNAL_$expandSelectionToWholeDocument as ot,CUT_TAG as it,PASTE_TAG as st,$isShadowRootNode as lt,$isSiblingCaret as at,$extendCaretToRange as ct,$normalizeCaret as ut,$getChildCaret as ft,$createNodeSelection as dt}from\"lexical\";import{AriaLiveRegionExtension as gt}from\"@lexical/a11y\";import{namedSignals as mt}from\"@lexical/extension/namedSignals\";import{DragonExtension as pt}from\"@lexical/dragon\";import{NormalizeInlineElementsExtension as ht}from\"@lexical/extension/NormalizeInlineElementsExtension\";import{NormalizeTripleClickSelectionExtension as yt}from\"@lexical/extension/NormalizeTripleClickSelectionExtension\";import{sel as xt,BlockSchema as _t,CoreImportExtension as Ct,DOMImportExtension as vt}from\"@lexical/html\";const St=/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/;function Dt(e,t){if(\"number\"==typeof e)return Number.isFinite(e)?e:t;if(\"string\"!=typeof e||!St.test(e))return t;const n=Number(e);return Number.isFinite(n)?n:t}function Nt(e,t,n,r,o){const i=Dt(e,t);return i>=n&&i<=r&&Number.isInteger(i)?i:t}function bt(e,t){e.__tag=t.__tag}const Ft=e=>{const t=h(e,\"format\"),n=y(e,\"format\"),r=x(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=Nt(t.indent,0,0,Infinity),e.__textFormat=Dt(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:bt}},Tt=e=>{const t=h(e,\"format\"),n=y(e,\"format\"),r=x(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=Nt(t.indent,0,0,Infinity),e.__textFormat=Dt(t.textFormat,0);const s=t.textStyle;return e.__textStyle=\"string\"==typeof s?s:\"\",e}}};function Kt(e){const t=_(e);return Xt(t)?t.getTag():null}const Et={build:(e,t)=>mt(t),config:{created:\"Heading level %s\",destroyed:\"Heading level %s removed\",disabled:!1},dependencies:[gt],name:\"@lexical/rich-text/HeadingAnnounce\",register(e,t,n){const{created:r,destroyed:o,disabled:i}=n.getOutput(),{announce:s}=n.getDependency(gt).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 C(t,n),v(n,t),S(n,t),[n.splice(0,0,e.$importChildren(t))]},match:/* @__PURE__ */xt.tag(\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\"),name:\"@lexical/rich-text/heading\"},wt={$import:(e,t)=>{const n=Lt();return v(n,t),C(t,n),S(n,t),[n.splice(0,0,e.$importChildren(t))]},match:/* @__PURE__ */xt.tag(\"blockquote\"),name:\"@lexical/rich-text/blockquote\"},It={$import:(e,t)=>{const n=Lt({shadowRoot:!0});return v(n,t),C(t,n),S(n,t),[n.splice(0,0,e.$importChildren(t,{schema:_t}))]},match:/* @__PURE__ */xt.tag(\"blockquote\"),name:\"@lexical/rich-text/blockquote-shadow-root\"},Ot=[kt,wt,{$import:(e,t,n)=>{const r=t.firstChild;return r&&D(o=r)&&\"SPAN\"===o.nodeName&&\"26pt\"===o.style.fontSize?e.$importChildren(t):n();var o},match:/* @__PURE__ */xt.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__ */xt.tag(\"span\"),name:\"@lexical/rich-text/google-docs-title-span\"}];function At(e,t){return e&&null!==t?N(e,t):t}const zt={build:(e,t)=>mt(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:[Et,pt,ht,yt,Ct,[vt,{rules:Ot}]],mergeConfig:function(e,t){const n=N(e,t);return t.escapeFormatTriggers&&(n.escapeFormatTriggers=function(e,t){const n=N(e,t);for(const r of Object.keys(t))n[r]=At(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)})},Rt={dependencies:[zt],name:\"@lexical/rich-text/Import\"},Pt=/* @__PURE__ */F(\"DRAG_DROP_PASTE_FILE\"),Mt=/* @__PURE__ */O(\"shadowRoot\",{parse:/* @__PURE__ */A()});class $t extends T{$config(){return this.config(\"quote\",{extends:T,generated:Tt,importDOM:{blockquote:()=>({conversion:jt,priority:0})},stateConfigs:[{flat:!0,stateConfig:Mt}]})}isShadowRoot(){return w(this,Mt)}setIsShadowRoot(e){return I(this,Mt,e)}createDOM(e){const t=K().createElement(\"blockquote\");return E(t,e.theme.quote),t}updateDOM(e,t,n){return!1}exportDOM(e){const{element:t}=super.exportDOM(e);if(D(t)){this.isEmpty()&&t.append(K().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=k();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=k();return this.getChildren().forEach(t=>e.append(t)),this.replace(e),!0}canMergeWhenEmpty(){return!0}}function Lt(e){const t=b(new $t);return e&&e.shadowRoot?t.setIsShadowRoot(!0):t}function Bt(e){return e instanceof $t}const qt=/* @__PURE__ */$e()({tag:/* @__PURE__ */Le(/* @__PURE__ */Be([\"h1\",\"h2\",\"h3\",\"h4\",\"h5\",\"h6\"]),{field:\"__tag\"})});class Jt extends T{__tag;$config(){return this.config(\"heading\",{extends:T,generated:Ft,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=K().createElement(t),r=e.theme.heading;if(void 0!==r){const e=r[t];E(n,e)}return n}updateDOM(e,t,n){return e.__tag!==this.__tag}exportDOM(e){const{element:t}=super.exportDOM(e);if(D(t)){this.isEmpty()&&t.append(K().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=e?e.anchor.offset:0,r=this.getLastDescendant(),o=!r||e&&e.anchor.key===r.getKey()&&n===r.getTextContentSize()||!e?k():Vt(this.getTag()).setFormat(this.getFormatType()).setStyle(this.getStyle()),i=this.getDirection();if(o.setDirection(i),this.insertAfter(o,t),0===n&&!this.isEmpty()&&e){const e=k();e.select(),this.replace(e,!0)}return o}collapseAtStart(){if(this.isEmpty()){const e=k();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),C(e,n),v(n,e),S(n,e)),{node:n}}function jt(e){const t=Lt();return v(t,e),C(e,t),S(t,e),{node:t}}function Vt(e=\"h1\"){return b(new Jt(e))}function Xt(e){return e instanceof Jt}function Yt(e){const t=Ce(e);return pe(t)}function Gt(e){const t=e.focus;return\"root\"===t.key&&t.offset===tt().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 nt(tt().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(Se(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&&Se(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=Ge(e.focus,t),r=Q(n.origin,lt);if(!r)return!1;const o=e.focus.getNode();if(!r.is(o)&&!et(o,r))return!1;const i=je(n,qe(r,t));if(i.getTextSlices().some(e=>e&&e.getTextContentSize()>0))return!1;const s=je(i.anchor.getSiblingCaret(),i.focus);let l=s.anchor.origin;for(const e of s){if(!at(e)||!e.origin.is(l.getParent()))return!1;l=e.origin}let a=r;for(const e of ct(qe(r,t))){if(!e.origin.is(a.getParent())){if(nt(e.origin)){const e=qe(a,t);return We(je(e,e)),!0}break}if(!lt(e.origin))break;a=e.origin}return!1}(e,t)||function(e,t){if(!e.isCollapsed()||\"element\"!==e.anchor.type)return!1;const n=Ge(e.anchor,t).getNodeAtCaret();return!(!lt(n)||n.isInline()||(We(Ye(ut(ft(n,t)))),0))}(e,t)}function nn(e){return pe(e)&&!e.isInline()&&!e.isIsolated()&&e.isKeyboardSelectable()}function rn(e){const t=dt();t.add(e),Ne(t)}function on(e,t){if(!e.isCollapsed())return!1;const n=e.focus,r=n.getNode(),o=t?\"previous\":\"next\",i=Ge(n,o);if(\"element\"===n.type&&U(r)&&Qe(r)){const e=i.getNodeAtCaret();return!(null===e||!nn(e)||(rn(e.__key),0))}const s=Q(U(r)?r:r.getParentOrThrow(),e=>U(e)&&!e.isInline()&&Qe(e.getParent()));if(null===s)return!1;const l=qe(s,o).getNodeAtCaret();if(null===l||!nn(l))return!1;if(0===s.getTextContentSize())return rn(l.__key),!0;const a=Ue().getRootElement();if(null===a)return!1;const c=Ze(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=Ce(m);return sn(c,u,f,d,g),null!==h&&((m===u&&p===f||!h.is(s)&&!et(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=Q(U(r)?r:r.getParentOrThrow(),e=>U(e)&&!e.isInline());if(null===o)return!1;const i=Ue(),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(U(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=qe(o,n?\"previous\":\"next\").getNodeAtCaret();if(null===c||!U(c)){if(n){const e=o.getFirstDescendant();Se(e)?e.select(0,0):o.select(0,0)}else{const e=o.getLastDescendant();if(Se(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=Ze(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(Se(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=qe(e,t),r=n.getAdjacentCaret();null!==r&&U(r.origin)&&!r.origin.isInline()&&r.origin.isShadowRoot()?We(Ye(n)):\"next\"===t?e.selectNext(0,0):e.selectPrevious()}function cn(e,t){const n=e.getNodes().map(e=>qe(e,\"next\")).sort(Je),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 We(He(je(Ve(r),o),t)),Xe(),!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=>qe(e,\"next\")).sort(Je),i=(t?o[0]:o[o.length-1]).origin,s=Q(i,e=>e!==i&&U(e)&&!e.isInline())??tt(),l=t?0:s.getChildrenSize();return s.select(l,l),!0}function fn(e,t){return e.length>0&&!t}function dn(l,h=a(en),y=a(fn)){return z(l.registerCommand(R,e=>{const t=P();if(M(t)){const n=e.target;if(D(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 $(t)&&Zt(t,\"click\",\"both\",h.peek()),!1},L),l.registerCommand(B,e=>{const t=P();return $(t)?(t.deleteCharacter(e),!0):!!M(t)&&(t.deleteNodes(),!0)},L),l.registerCommand(q,e=>{const t=P();return!!$(t)&&(t.deleteWord(e),!0)},L),l.registerCommand(J,e=>{const t=P();return!!$(t)&&(t.deleteLine(e),!0)},L),l.registerCommand(W,t=>{const n=P();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($(n)){const e=t.data;return e&&n.insertText(e),!0}}return!0},L),l.registerCommand(H,()=>{const e=P();return!!$(e)&&(e.removeText(),!0)},L),l.registerCommand(j,e=>{const t=P();return!(!$(t)&&!M(t)||(V(t,e),0))},L),l.registerCommand(X,e=>{const t=P();return!(!$(t)&&!M(t)||(Y(t,e),0))},L),l.registerCommand(G,e=>{const t=P();if(!$(t)&&!M(t))return!1;const n=t.getNodes();for(const t of n){const n=Q(t,e=>U(e)&&!e.isInline());null!==n&&n.setFormat(e)}return!0},L),l.registerCommand(Z,e=>{const t=P();return!!$(t)&&(t.insertLineBreak(e),!0)},L),l.registerCommand(ee,()=>{const e=P();return!!$(e)&&(e.insertParagraph(),!0)},L),l.registerCommand(te,()=>{const e=ne(),t=P();return $(t)&&(e.setFormat(t.format),e.setStyle(t.style)),re([e]),!0},L),l.registerCommand(oe,()=>d(e=>{const t=e.getIndent();e.setIndent(t+1)}),L),l.registerCommand(ie,()=>d(e=>{const t=e.getIndent();t>0&&e.setIndent(Math.max(0,t-1))}),L),l.registerCommand(se,e=>{let t=P();if(M(t)){const n=t.getNodes();if(n.length>0){if(!e.shiftKey||!cn(t,\"previous\"))return e.preventDefault(),an(n[0],\"previous\"),!0;t=P()}}if($(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},L),l.registerCommand(le,e=>{let t=P();if(M(t)){const n=t.getNodes();if(n.length>0){if(!e.shiftKey||!cn(t,\"next\"))return e.preventDefault(),an(n[0],\"next\"),!0;t=P()}}if($(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},L),l.registerCommand(ae,e=>{let t=P();if(M(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=P()}}if(!$(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\",h.peek()),u(t,!0)){const n=e.shiftKey;return e.preventDefault(),f(t,n,!0),!0}return!1},L),l.registerCommand(ce,e=>{let t=P();if(M(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=P()}}if(!$(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\",h.peek()),u(t,!1)){const n=e.shiftKey;return e.preventDefault(),f(t,n,!1),!0}return!1},L),l.registerCommand(ue,e=>{const t=P();if(!M(t)&&Yt(e.target))return!1;if($(t)){if(function(e){if(!e.isCollapsed())return!1;const{anchor:t}=e;if(0!==t.offset)return!1;const n=t.getNode();if(rt(n))return!1;const r=p(n);return r.getIndent()>0&&(r.is(n)||n.is(r.getFirstDescendant()))}(t))return e.preventDefault(),l.dispatchCommand(ie);if(fe&&de)return!1}else if(!M(t))return!1;return e.preventDefault(),l.dispatchCommand(B,!0)},L),l.registerCommand(ge,e=>{const t=P();return!(!M(t)&&Yt(e.target))&&!(!$(t)&&!M(t))&&(e.preventDefault(),l.dispatchCommand(B,!1))},L),l.registerCommand(me,e=>{let t=P();if(M(t)){const e=t.getNodes();1===e.length&&pe(e[0])&&!e[0].isInline()&&(t=e[0].selectNext())}if(!$(t))return!1;if(Zt(t,\"enter\",\"both\",h.peek()),null!==e){if((fe||he||ye)&&de)return!1;if(e.preventDefault(),e.shiftKey)return l.dispatchCommand(Z,!1)}return l.dispatchCommand(ee)},L),l.registerCommand(xe,()=>{const e=P();return!!$(e)&&(l.blur(),!0)},L),l.registerCommand(_e,e=>{const[,r]=g(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=Ce(t);if(null!==n){const t=ve();if(Se(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=De(t);Ne(r)}}return l.dispatchCommand(Pt,r),e.preventDefault(),!0}return n(e,l)},L),l.registerCommand(be,e=>{const[t]=g(e),n=P();return!(t&&!$(n)||($(n)&&!n.isCollapsed()&&null!==e.dataTransfer&&(r(e.dataTransfer,o(n)),i(e.dataTransfer,l)),0))},L),l.registerCommand(Fe,e=>{const[n]=g(e),r=P();if(n&&!$(r))return!1;const o=e.clientX,i=e.clientY,s=t(o,i,l.getRootElement());if(null!==s){const t=Ce(s.node);pe(t)&&e.preventDefault()}return!0},L),l.registerCommand(Te,()=>{const e=P();return Ke($(e)&&null!==Ee(e.anchor.getNode())?e:null),!0},L),l.registerCommand(ke,e=>(s(l,m(e,ClipboardEvent)?e:null),!0),L),l.registerCommand(we,e=>(async function(e,t){t.update(()=>{const e=P();$(e)&&!e.isCollapsed()&&ot(e)},{discrete:!0,tag:it}),await s(t,m(e,ClipboardEvent)?e:null),t.update(()=>{const e=P();$(e)?e.removeText():M(e)&&e.getNodes().forEach(e=>e.remove())},{tag:it})}(e,l),!0),L),l.registerCommand(Ie,t=>{const[,n,r]=g(t);return!(!y.peek()(n,r)||!l.dispatchCommand(Pt,n))||(!Oe(t.target)||!Ae(t.target))&&(null!==P()&&(function(t,n){t.preventDefault(),n.update(()=>{const r=P(),o=m(t,InputEvent)||m(t,KeyboardEvent)?null:t.clipboardData;null!=o&&null!==r&&e(o,r,n)},{tag:st})}(t,l),!0))},L),l.registerCommand(ze,()=>{const e=P();return $(e)&&Zt(e,\"space\",\"both\",h.peek()),!1},L),l.registerCommand(Re,()=>{const e=P();return $(e)&&Zt(e,\"tab\",\"both\",h.peek()),!1},L),l.registerCommand(Pe,e=>{const t=P();if(M(t))return un(t,!1,e);if(!$(t))return!1;const{anchor:n}=t;if(\"element\"!==n.type||0!==n.offset)return!1;const r=n.getNode();if(!U(r))return!1;const o=r.getFirstChild();if(!pe(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},L),l.registerCommand(Me,e=>{const t=P();if(M(t))return un(t,!0,e);if(!$(t))return!1;const{anchor:n,focus:r}=t,o=Q(r.getNode(),e=>U(e)&&!e.isInline());if(null===o)return!1;const i=o.getFirstChild();if(!pe(i)||!i.isInline())return!1;if(Q(n.getNode(),e=>U(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)},L))}export{Vt as $createHeadingNode,Lt as $createQuoteNode,Xt as $isHeadingNode,Bt as $isQuoteNode,Pt as DRAG_DROP_PASTE,Et as HeadingAnnounceExtension,Jt as HeadingNode,$t as QuoteNode,zt as RichTextExtension,Rt as RichTextImportExtension,Ot as RichTextImportRules,It 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 r,$getState as o,$findMatchingParent as s,$createLineBreakNode as i,createState as l,$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 m,HISTORIC_TAG as x,COMPOSITION_END_TAG as C,$getSelection as T,$isRangeSelection as I,$addUpdateTag as $,HISTORY_PUSH_TAG as v,KEY_ENTER_COMMAND as y,COMMAND_PRIORITY_LOW as S,$isRootOrShadowRoot as E,$createRangeSelection as b,$setSelection as w,TEXT_TYPE_TO_FORMAT as k,ArtificialNode__DO_NOT_USE as N}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 B,$isLinkNode as L,$createLinkNode as _,$isAutoLinkNode as R}from\"@lexical/link\";import{ListNode as j,ListItemNode as z,$isListNode as A,$createListItemNode as W,$createListNode as U,$isListItemNode as D}from\"@lexical/list\";import{HeadingNode as Z,QuoteNode as H,$isHeadingNode as K,$isQuoteNode as X,$createQuoteNode as q,$createHeadingNode as G}from\"@lexical/rich-text\";function J(t,e){const n={};for(const r of t){const t=e(r);t&&(n[t]?n[t].push(r):n[t]=[r])}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 r=n.getFirstChild();return null==r||1===n.getChildrenSize()&&e(r)&&et.test(r.getTextContent())}function rt(t){return t.replace(/\\\\([!-/:-@[-`{-~])/g,\"$1\").replace(/&#(\\d+);/g,(t,e)=>String.fromCodePoint(Number(e)))}const ot=/^(\\s*)(\\d{1,})\\.\\s/,st=/^(\\s*)[-*+]\\s/,it=/^(\\s*)(?:[-*+]\\s)?\\s?(\\[(\\s|x)?\\])\\s/i,lt=/^(#{1,6})\\s/,ct=/^>\\s/,ft=/^([ \\t]*`{3,})([\\w-]+)?[ \\t]?/,ut=/^[ \\t]*`{3,}$/,at=/^[ \\t]*```[^`]+(?:(?:`{1,2}|`{4,})[^`]+)*```(?:[^`]|$)/,dt=/^(?:\\|)(.+)(?:\\|)\\s?$/;function gt(t){if(\"|\"!==t[0])return!1;const{length:e}=t;let n=1,r=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;r++,n=e+1}return r>0&&(n===e||n===e-1&&/\\s/.test(t[n]))}const ht=/^<[a-z_][\\w-]*(?:\\s[^<>]*)?\\/?>/i,pt=/^<\\/[a-z_][\\w-]*\\s*>/i,mt=t=>new RegExp(`(?:${t.source})$`,t.flags),xt=/* @__PURE__ */l(\"mdListMarker\",{parse:t=>\"string\"==typeof t&&/^[-*+]$/.test(t)?t:\"-\",resetOnCopyNode:!0}),Ct=/* @__PURE__ */l(\"mdCodeFence\",{parse:t=>\"string\"==typeof t&&/^`{3,}$/.test(t)?t:\"```\",resetOnCopyNode:!0}),Tt=/* @__PURE__ */l(\"mdCodeMeta\",{parse:t=>\"string\"==typeof t?t:\"\",resetOnCopyNode:!0}),It=/* @__PURE__ */l(\"mdHardLineBreak\",{parse:t=>\"string\"==typeof t&&/^(\\\\| {2,})$/.test(t)?t:\"\",resetOnCopyNode:!0});function $t(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 vt(t){const r=i(),o=function(t){const n=t.getChildren(),r=n.length-1,o=n[r];if(!e(o))return null;const s=o.getTextContent(),i=$t(s);if(null!==i){const[t,e]=i;return o.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,r)?(o.setTextContent(\"\"),s):null}(t);return null!==o&&n(r,It,o),r}function yt(t){return X(t)}function St(t,e){let n=0;for(;n<e&&(\" \"===t[n]||\"\\t\"===t[n]);)n++;return t.slice(n)}function Et(t,e){const r=t.getLastChild();e&&M(r)&&n(r,Tt,e)}const bt=t=>(e,n,r,o)=>{const s=t(r);s.append(...n),e.replace(s),o||s.select(0,0)};function wt(t){let e=0;for(const n of t)e+=\"\\t\"===n?4-e%4:1;return e}let kt=null,Nt=!1;const Ft=t=>(e,r,o,s)=>{if(K(e)||!s&&yt(e))return!1;const i=e.getPreviousSibling(),l=e.getNextSibling(),c=W(\"check\"===t?/^x$/i.test(o[3]||\"\"):void 0),f=o[0].trim()[0],u=\"bullet\"!==t&&\"check\"!==t||f!==xt.parse(f)?void 0:f,a=kt;let d=i;if(null!==a){if(Nt)for(;null!==d&&nt(d);)d=d.getPreviousSibling();A(d)||(a.length=0)}const g=null===a||0===a.length?function(t){const e=t.match(/\\t/g),n=t.match(/ /g);let r=0;return e&&(r+=e.length),n&&(r+=Math.floor(n.length/4)),r}(o[1]):function(t,e){const n=wt(e);for(let e=t.length-1;e>=0;e--)if(n>=t[e])return e+1;return 0}(a,o[1]);if(A(l)&&l.getListType()===t){const n=l.getFirstChild();null!==n?n.insertBefore(c):l.append(c),\"number\"===t&&0===g&&l.setStart(Number(o[2])),e.remove()}else if(A(d)&&(d.getListType()===t||g>0))d.append(c),e.remove();else{const n=U(t,\"number\"===t?Number(o[2]):void 0);n.append(c),e.replace(n)}c.append(...r),s||c.select(0,0),g&&(c.setIndent(g),function(t,e,n){const r=t.getParent();if(!A(r)||r.getListType()===e)return;const o=r.getParent();if(!D(o))return;const s=U(e,\"number\"===e?Number(n[2]):void 0),i=null===t.getPreviousSibling();s.append(t);const l=W();l.append(s),i?o.insertBefore(l):o.insertAfter(l),0===r.getChildrenSize()&&o.remove()}(c,t,o));const h=c.getParent();u&&A(h)&&n(h,xt,u),null!==a&&function(t,e,n,r){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(wt(n),wt(t[1])+4)}(n,r)}(a,g,o,t)},Ot=(t,e,n,r)=>{const s=[],i=t.getChildren();let l=0;for(const c of i)if(D(c)){if(1===c.getChildrenSize()){const t=c.getFirstChild();if(A(t)){const o=Ot(t,e,n+1,r);o&&s.push(o);continue}}if(r&&!c.getChildren().some(t=>t.isSelected(r)))continue;const i=\" \".repeat(4*n),f=t.getListType(),u=o(t,xt),a=\"number\"===f?`${t.getStart()+l}. `:\"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(i+a+d),l++}return s.join(\"\\n\")},Pt=/* @__PURE__ */bt(t=>{const e=\"h\"+t[1].length;return G(e)}),Mt={dependencies:[Z],export:(t,e)=>{if(!K(t))return null;const n=Number(t.getTag().slice(1));return\"#\".repeat(n)+\" \"+e(t)},regExp:lt,replace:(t,e,n,r)=>!(!r&&yt(t))&&Pt(t,e,n,r),triggerOnEnter:!0,type:\"element\"},Bt={dependencies:[H],export:(t,e)=>{if(!X(t))return null;const n=e(t).split(\"\\n\"),r=[];for(const t of n)r.push(\"> \"+t);return r.join(\"\\n\")},regExp:ct,replace:(t,e,n,r)=>{if(r){const n=t.getPreviousSibling();if(X(n))return n.splice(n.getChildrenSize(),0,[vt(n),...e]),void t.remove()}const o=q();o.append(...e),t.replace(o),r||o.select(0,0)},triggerOnEnter:!0,type:\"element\"},Lt={dependencies:[O],export:t=>{if(!M(t))return null;const e=t.getTextContent();let n=o(t,Ct);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 r=t.getLanguage()||\"\",s=r?o(t,Tt):\"\";return n+r+(s?\" \"+s:\"\")+(e?\"\\n\"+e:\"\")+\"\\n\"+n},handleImportAfterStartMatch:({lines:t,rootNode:e,startLineIndex:n,startMatch:r})=>{const o=r[1],s=o.trim().length,i=t[n],l=r.index+o.length,c=i.slice(l),f=new RegExp(`\\`{${s},}$`);if(f.test(c)){const t=c.match(f),o=c.slice(0,c.lastIndexOf(t[0])),s=[...r];return s[2]=\"\",Lt.replace(e,null,s,t,[o],!0),[!0,n]}const u=new RegExp(`^[ \\\\t]*\\`{${s},}$`);for(let o=n+1;o<t.length;o++){const s=t[o];if(u.test(s)){const l=s.match(u),c=t.slice(n+1,o),f=r[2]?i.slice(r[0].length).trim():\"\";return c.unshift(f?\"\":i.slice(r[0].length)),Lt.replace(e,null,r,l,c,!0),Et(e,f),[!0,o]}}const a=t.slice(n+1);return a.unshift(i.slice(r[0].length)),Lt.replace(e,null,r,null,a,!0),[!0,t.length-1]},regExpEnd:{optional:!0,regExp:ut},regExpStart:ft,replace:(t,e,o,s,i,l)=>{let c,f;const u=o[1]?o[1].trim():\"```\",a=o[2]||void 0,d=o[1]?o[1].length-o[1].trimStart().length:0;if(!e&&i){if(1===i.length)s?(c=P(a),f=St(i[0],d)):(c=P(a),f=i[0].startsWith(\" \")?i[0].slice(1):i[0]);else{for(c=P(a),i.length>0&&(0===i[0].trim().length?i.shift():i[0].startsWith(\" \")&&(i[0]=i[0].slice(1)));i.length>0&&!i[i.length-1].length;)i.pop();f=i.map(t=>St(t,d)).join(\"\\n\")}n(c,Ct,u);const e=r(f);c.append(e),t.append(c)}else if(e){if(!l&&yt(t))return!1;bt(t=>P(t?t[2]:void 0))(t,e,o,l)}},type:\"multiline-element\"},_t={dependencies:[j,z],export:(t,e,n)=>A(t)?Ot(t,e,0,n):null,regExp:st,replace:/* @__PURE__ */Ft(\"bullet\"),triggerOnEnter:!0,type:\"element\"},Rt={dependencies:[j,z],export:(t,e,n)=>A(t)?Ot(t,e,0,n):null,regExp:it,replace:/* @__PURE__ */Ft(\"check\"),triggerOnEnter:!0,type:\"element\"},jt={dependencies:[j,z],export:(t,e,n)=>A(t)?Ot(t,e,0,n):null,regExp:ot,replace:/* @__PURE__ */Ft(\"number\"),triggerOnEnter:!0,type:\"element\"},zt={format:[\"code\"],tag:\"`\",type:\"text-format\"},At={format:[\"highlight\"],tag:\"==\",type:\"text-format\"},Wt={format:[\"bold\",\"italic\"],tag:\"***\",type:\"text-format\"},Ut={format:[\"bold\",\"italic\"],intraword:!1,tag:\"___\",type:\"text-format\"},Dt={format:[\"bold\"],tag:\"**\",type:\"text-format\"},Zt={format:[\"bold\"],intraword:!1,tag:\"__\",type:\"text-format\"},Ht={format:[\"strikethrough\"],tag:\"~~\",type:\"text-format\"},Kt={format:[\"italic\"],tag:\"*\",type:\"text-format\"},Xt={format:[\"italic\"],intraword:!1,tag:\"_\",type:\"text-format\"};function qt(t){return t.replace(/&(?=#\\d+;|#[Xx][\\dA-Fa-f]+;|[A-Za-z][\\dA-Za-z]*;)/g,\"&#38;\")}const Gt={dependencies:[B],export:(t,e,n)=>{if(!L(t)||R(t))return null;const r=e(t);let o=t.getTitle();null!=o&&(o=qt(o).replace(/([\\\\\"])/g,\"\\\\$1\"));const s=t.getURL(),i=qt(s),l=\"\"===s||/\\s/.test(s)?`<${i.replace(/([\\\\<>])/g,\"\\\\$1\").replace(/\\r/g,\"&#13;\").replace(/\\n/g,\"&#10;\")}>`:i.replace(/([\\\\()])/g,\"\\\\$1\").replace(/^</,\"\\\\<\");return o?`[${r}](${l} \"${o}\")`:`[${r}](${l})`},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)=>{if(s(t,L))return;const[,n,o,i,l,c,f]=e,u=rt(o??i??\"\"),a=l??c??f,d=null!=a?rt(a):void 0,g=_(u,{title:d}),h=n.split(\"[\").length-1,p=n.split(\"]\").length-1;let m=n,x=\"\";if(h<p)return;if(h>p){const t=n.split(\"[\");x=\"[\"+t[0],m=t.slice(1).join(\"[\")}const C=t.getFormat(),T=r(m);return T.setFormat(C),g.append(T),t.replace(g),x&&g.insertBefore(r(x).setFormat(C)),T},trigger:\")\",type:\"text-match\"},Jt=[Mt,Bt,_t,jt],Qt=[Lt],Vt=[zt,Wt,Ut,Dt,Zt,At,Kt,Xt,Ht],Yt=[Gt];function te(...t){return t.flat()}const ee=/* @__PURE__ */te(Jt,Qt,Vt,Yt);function ne(t,e=!1){const n=t.split(\"\\n\");let r=0;const o=[];for(let t=0;t<n.length;t++){const s=n[t],i=s.trimEnd(),l=o[o.length-1],c=t<n.length-1?$t(s):null,f=void 0!==l&&null!==$t(l);if(at.test(i))o.push(i);else if(0===r){{const t=i.match(ft);if(t){r=t[1].trim().length,o.push(i);continue}}\"\"===i||\"\"===l||!l||lt.test(l)||lt.test(i)||ct.test(i)||ot.test(i)||st.test(i)||it.test(i)||dt.test(i)||gt(i)||f||!e||ht.test(i)||pt.test(i)||mt(pt).test(l)||mt(ht).test(l)||ut.test(l)?o.push(!e&&\"\"!==i||null!==c?s:i):o[o.length-1]=l+\" \"+(null===c?i:s).trimStart()}else{if(ut.test(i)&&i.trim().length>=r){r=0,o.push(i);continue}o.push(s)}}return o.join(\"\\n\")}function re(t,e,n,r,o,s){let i=t.isSelected(e);for(const l of n){if(!l.export)continue;const n=l.export(t,t=>oe(t,e,r,o,s).markdown,e);if(null!=n)return!i&&u(t)&&oe(t,e,r,o,s).shouldInclude&&(i=!0),{markdown:n,shouldInclude:i}}if(u(t)){const n=oe(t,e,r,o,s);return{markdown:n.markdown,shouldInclude:i||n.shouldInclude}}return a(t)?{markdown:t.getTextContent(),shouldInclude:i}:{markdown:null,shouldInclude:i}}function oe(t,n,r,o,s,i,l){const f=[],d=t.getChildren();let g=!1;i||(i=[]),l||(l=[]);t:for(const t of d){let d=t.isSelected(n);for(const e of o){if(!e.export)continue;const c=e.export(t,t=>oe(t,n,r,o,s,i,[...l,...i]).markdown,(t,e)=>ce(t,F(n,t,\"clone\").getTextContent(),r,i,l,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(le(t)),g=!0);else if(e(t)){if(d){const e=F(n,t,\"clone\");f.push(ce(t,e.getTextContent(),r,i,l,s)),g=!0}}else if(u(t)){const e=oe(t,n,r,o,s,i,l);!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 se(t,e,n,r,o){for(const s of e){if(!s.export)continue;const e=s.export(t,t=>ie(t,n,r,void 0,void 0,o));if(null!=e)return e}return u(t)?ie(t,n,r,void 0,void 0,o):a(t)?t.getTextContent():null}function ie(t,n,r,o,s,i=!1){const l=[],f=t.getChildren();o||(o=[]),s||(s=[]);t:for(const t of f){for(const e of r){if(!e.export)continue;const c=e.export(t,t=>ie(t,n,r,o,[...s,...o],i),(t,e)=>ce(t,e,n,o,s,i));if(null!=c){l.push(c);continue t}}c(t)?l.push(le(t)):e(t)?l.push(ce(t,t.getTextContent(),n,o,s,i)):u(t)?l.push(ie(t,n,r,o,s,i)):a(t)&&l.push(t.getTextContent())}return l.join(\"\")}function le(t){return o(t,It)+\"\\n\"}function ce(t,e,n,r,o,s=!1){const i=t.hasFormat(\"code\");let l,c,f,u,a=e;if(i||(a=s?a.replace(/([*_`~])/g,\"\\\\$1\"):a.replace(/([*_`~\\\\])/g,\"\\\\$1\")),i){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);l=\"\",f=\"\",c=t+n+t,u=!1}else{const t=a.match(/^(\\s*)(.*?)(\\s*)$/s)||[\"\",\"\",a,\"\"];l=t[1],c=t[2],f=t[3],u=\"\"===c}let d=\"\",g=\"\",h=\"\";const p=fe(t,!0),m=fe(t,!1),x=new Set;for(const e of n){const n=e.format[0],o=e.tag;\"code\"!==n&&(u||!ae(t,n)||x.has(n)||(x.add(n),ae(p,n)&&r.find(t=>t.tag===o)||(r.push({format:n,tag:o}),d+=o)))}for(let e=0;e<r.length;e++){const n=ue(t,r[e].format),s=ue(m,r[e].format);if(n&&s)continue;const i=[...r];for(;i.length>e;){const t=i.pop();o&&t&&o.find(e=>e.tag===t.tag)||(t&&\"string\"==typeof t.tag&&(n?s||(h+=t.tag):g+=t.tag),r.pop())}break}return u&&!t.hasFormat(\"code\")?g+a:g+l+d+c+h+f}function fe(t,n){const r=n?t.getPreviousSibling():t.getNextSibling();return e(r)?r:null}function ue(t,n){return e(t)&&t.hasFormat(n)}function ae(t,e){return!(!ue(t,e)||\"code\"!==e&&t&&/^\\s*$/.test(t.getTextContent()))}function de(t,e,n,r,o){if(!ge(e,n,r,o))return!1;if(\"*\"===t)return!0;if(\"_\"===t){if(!ge(e,n,r,!o))return!0;const t=o?e[n-1]:e[n+r];return void 0!==t&&tt.test(t)}return!0}function ge(t,e,n,r){const o=t[e-1],s=t[e+n],[i,l]=r?[s,o]:[o,s];return void 0!==i&&!Y.test(i)&&(!tt.test(i)||void 0===l||Y.test(l)||tt.test(l))}function he(t){return e(t)&&!t.hasFormat(\"code\")}function pe(t,e,n){let r=function(t,e){const n=t.getTextContent(),r=e.transformersByTag[\"`\"],o=[];let s=null;if(r){const t=function(t){const e=e=>{let n=0;for(let r=e-1;r>=0&&\"\\\\\"===t[r];r--)n++;return n%2==1},n=[];let r=0;for(;r<t.length;)if(\"`\"===t[r]){let e=1;for(;r+e<t.length&&\"`\"===t[r+e];)e++;n.push({index:r,length:e}),r+=e}else r++;const o=[];let s=0;for(;s<n.length;){const r=n[s];if(e(r.index)){s++;continue}let i=-1;for(let t=s+1;t<n.length;t++)if(n[t].length===r.length){i=t;break}if(-1===i){s++;continue}const l=n[i];let c=t.slice(r.index+r.length,l.index);c.length>=2&&c.startsWith(\" \")&&c.endsWith(\" \")&&/[^ ]/.test(c)&&(c=c.slice(1,-1)),o.push({content:c,endIndex:l.index+l.length,startIndex:r.index}),s=i+1}return o}(n);for(const e of t)s||(s={content:e.content,endIndex:e.endIndex,startIndex:e.startIndex,tag:\"`\"}),o.push({end:e.endIndex,start:e.startIndex})}const i=function(t,e,n=[]){const r=[],o=new Set(Object.keys(e.transformersByTag).filter(t=>\"`\"!==t[0]).map(t=>t[0])),s=e=>{let n=0;for(let r=e-1;r>=0&&\"\\\\\"===t[r];r--)n++;return n%2==1},i=t=>n.some(e=>t>=e.start&&t<e.end);let l=0;for(;l<t.length;){const e=t[l];if(!o.has(e)||s(l)||i(l)){l++;continue}let n=1;for(;l+n<t.length&&t[l+n]===e;)n++;const c=de(e,t,l,n,!0),f=de(e,t,l,n,!1);(c||f)&&r.push({active:!0,canClose:f,canOpen:c,char:e,index:l,length:n}),l+=n}return r}(n,e,o),l=i.length>0?function(t,e,n){const r={};let o=0,s=null;for(;o<e.length;){const i=e[o];if(!i.active||!i.canClose||0===i.length){o++;continue}const l=`${i.char}${i.canOpen}${i.length%3}`,c=r[l]??-1;let f=!1;for(let r=o-1;r>c;r--){const l=e[r];if(!l.active||!l.canOpen||0===l.length||l.char!==i.char)continue;if((l.canClose||i.canOpen)&&(l.length+i.length)%3==0&&l.length%3!=0&&i.length%3!=0)continue;const c=Math.min(l.length,i.length),u=Object.keys(n.transformersByTag).filter(t=>t[0]===l.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(l.index+l.length,i.index),endIndex:i.index+a,startIndex:l.index+(l.length-a),tag:u};(!s||d.startIndex<s.startIndex||d.startIndex===s.startIndex&&d.endIndex>s.endIndex)&&(s=d);for(let t=r+1;t<o;t++)e[t].active=!1;l.length-=a,i.length-=a,l.active=l.length>0,i.length>0?i.index+=a:(i.active=!1,o++);break}f||(r[l]=o-1,i.canOpen||(i.active=!1),o++)}return s}(n,i,e):null;let c=null,f=null;if(s&&l?l.startIndex<=s.startIndex&&l.endIndex>=s.endIndex?(c=l,f=e.transformersByTag[l.tag]):(c=s,f=r):s?(c=s,f=r):l&&(c=l,f=e.transformersByTag[l.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===r,match:u,startIndex:c.startIndex,transformer:f}}(t,e),o=function(t,e){const n=t;let r,o,s,i;for(const t of e){if(!t.replace||!t.importRegExp)continue;const e=n.getTextContent().match(t.importRegExp);if(!e)continue;const l=e.index||0,c=t.getEndIndex?t.getEndIndex(n,e):l+e[0].length;!1!==c&&(void 0===r||void 0===o||l<r&&(c>o||c<=r))&&(r=l,o=c,s=t,i=e)}return void 0===r||void 0===o||void 0===s||void 0===i?null:{endIndex:o,match:i,startIndex:r,transformer:s}}(t,n);if(r&&o&&(r.isCodeSpan?o.startIndex<=r.startIndex&&o.endIndex>=r.endIndex?r=null:o=null:r.startIndex<=o.startIndex&&r.endIndex>=o.endIndex||o.startIndex>r.endIndex?o=null:r=null),r){const o=function(t,e,n,r,o){const s=t.getTextContent();let i,l,c;if(o[0]===s?i=t:0===e?[i,l]=t.splitText(n):[c,i,l]=t.splitText(e,n),i.setTextContent(o[2]),r)for(const t of r.format)i.hasFormat(t)||i.toggleFormat(t);return{nodeAfter:l,nodeBefore:c,transformedNode:i}}(t,r.startIndex,r.endIndex,r.transformer,r.match);he(o.nodeAfter)&&pe(o.nodeAfter,e,n),he(o.nodeBefore)&&pe(o.nodeBefore,e,n),he(o.transformedNode)&&pe(o.transformedNode,e,n)}else if(o){const r=function(t,e,n,r,o){let s,i,l;return 0===e?[s,i]=t.splitText(n):[l,s,i]=t.splitText(e,n),r.replace?{nodeAfter:i,nodeBefore:l,transformedNode:r.replace(s,o)||void 0}:null}(t,o.startIndex,o.endIndex,o.transformer,o.match);if(!r)return;he(r.nodeAfter)&&pe(r.nodeAfter,e,n),he(r.nodeBefore)&&pe(r.nodeBefore,e,n),he(r.transformedNode)&&pe(r.transformedNode,e,n)}const s=rt(t.getTextContent());t.setTextContent(s)}function me(t,e,n,r=!1){const o=Q(n),s=function(t){const e={},n={},r=[];for(const o of t){const{tag:t}=o;e[t]=o;const s=t.replace(/(\\*|\\^|\\+)/g,\"\\\\$1\");r.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(`(${r.join(\"|\")})`,\"g\"),transformersByTag:e}}(o.textFormat),i=t.split(\"\\n\"),l=i.length;!function(t){const n=kt,c=Nt;kt=[],Nt=t;try{return(()=>{for(let t=0;t<l;t++){const n=i[t],[l,c]=xe(i,t,o.multilineElement,e);l?t=c:Ce(n,e,o.element,s,o.textMatch,r)}})()}finally{kt=n,Nt=c}}(!r);const c=e.getChildren();for(const t of c)if(!r&&nt(t)&&e.getChildrenSize()>1)t.remove();else if(u(t))for(const e of t.getAllTextNodes())Te(e)}function xe(t,e,n,r){for(const o of n){const{handleImportAfterStartMatch:n,regExpEnd:s,regExpStart:i,replace:l}=o,c=t[e].match(i);if(!c)continue;if(n){const s=n({lines:t,rootNode:r,startLineIndex:e,startMatch:c,transformer:o});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 o=[];if(n&&e===a)o.push(t[e].slice(c[0].length,-n[0].length));else for(let r=e;r<=a;r++)if(r===e){const e=t[r].slice(c[0].length);o.push(e)}else if(r===a&&n){const e=t[r].slice(0,-n[0].length);o.push(e)}else o.push(t[r]);if(!1!==l(r,null,c,n,o,!0))return[!0,a];break}}return[!1,e]}function Ce(e,n,o,i,l,c){const f=r(e),u=h();u.append(f),n.append(u);for(const{regExp:t,replace:n}of o){const r=e.match(t);if(r&&(f.setTextContent(e.slice(r[0].length)),!1!==n(u,[f],r,!0)))break}if(pe(f,i,l),null!==u.getParent()&&e.length>0){const e=u.getPreviousSibling();if(!c&&(t(e)||X(e)||A(e))){let t=e;if(A(e)){const n=e.getLastDescendant();t=null==n?null:s(n,D)}null!=t&&t.getTextContentSize()>0&&(t.splice(t.getChildrenSize(),0,[vt(t),...u.getChildren()]),u.remove())}}}function Te(t){if(d(t))return;const e=t.getTextContent();if(!e.includes(\"\\t\"))return;const n=t.getFormat(),o=t.getStyle(),s=[];let i=0;for(let t=e.indexOf(\"\\t\");-1!==t;t=e.indexOf(\"\\t\",t+1))t>i&&s.push(r(e.slice(i,t)).setFormat(n).setStyle(o)),s.push(g()),i=t+1;i<e.length&&s.push(r(e.slice(i)).setFormat(n).setStyle(o)),t.getParentOrThrow().splice(t.getIndexWithinParent(),1,s)}function Ie(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 $e(t,e,n,r,o){const s=t.getParent();if(!E(s)||t.getFirstChild()!==e)return!1;const i=e.getTextContent();if(!o&&\" \"!==i[n-1])return!1;for(const{regExp:s,replace:l}of r){const r=i.match(s),c=o||r&&r[0].endsWith(\" \")?n:n-1;if(r&&r[0].length===c){const o=e.getNextSiblings(),[s,i]=e.splitText(n);if(!1!==l(t,i?[i,...o]:o,r,!1))return s.remove(),!0}}return!1}function ve(t,e,n,r,o){const s=t.getParent();if(!E(s)||t.getFirstChild()!==e)return!1;const i=e.getTextContent();if(!o&&\" \"!==i[n-1])return!1;for(const{regExpStart:s,replace:l,regExpEnd:c}of r){if(c&&!(\"optional\"in c)||c&&\"optional\"in c&&!c.optional)continue;const r=i.match(s);if(r){const s=o||r[0].endsWith(\" \")?n:n-1;if(r[0].length!==s)continue;const i=e.getNextSiblings(),[c,f]=e.splitText(n);if(!1!==l(t,f?[f,...i]:i,r,null,null,!1))return c.remove(),!0}}return!1}function ye(t,e){let n=0;const r=t.getTextContent();for(let t=0;t<e;t++)\"`\"===r[t]&&n++;return n%2!=0}function Se(t,e,n){const r=n.length;for(let o=e;o>=r;o--){const e=o-r;if(be(t,e,n,0,r)&&\" \"!==t[e+r])return e}return-1}function Ee(t){const n=t.getNode();let r=0;if(e(n))r=t.offset;else if(u(n))for(const e of n.getChildren().slice(0,t.offset))r+=e.getTextContentSize();for(let t=n.getPreviousSibling();null!==t;t=t.getPreviousSibling())r+=t.getTextContentSize();return r}function be(t,e,n,r,o){for(let s=0;s<o;s++)if(t[e+s]!==n[r+s])return!1;return!0}function we(t,n=ee){const r=Q(n),o=r.element.filter(t=>t.triggerOnEnter),s=J(r.textFormat,({tag:t})=>t[t.length-1]),i=J(r.textMatch,({trigger:t})=>t),l=new Set([\" \"]);for(const t of r.textFormat)l.add(t.tag.slice(-1));for(const t of r.textMatch)void 0!==t.trigger&&l.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)||Ie(173,e.getType())}}return p(t.registerUpdateListener(({tags:n,dirtyLeaves:o,editorState:f,prevEditorState:u})=>{if(n.has(m)||n.has(x))return;if(t.isComposing())return;const a=n.has(C),d=f.read(T),g=u.read(T);if(!I(g)||!I(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)&&o.has(h)&&(a||1===p||!(f.read(()=>Ee(d.anchor))>u.read(()=>Ee(g.anchor))+1))){if(a){const t=f.read(()=>y.getTextContent())[p-1];if(!l.has(t))return}t.update(()=>{if(!he(y))return;const t=y.getParent();null===t||M(t)||((t,n,o)=>!!($e(t,n,o,r.element)||ve(t,n,o,r.multilineElement)||function(t,e,n){let r=t.getTextContent();const o=n[r[e-1]];if(null==o)return!1;e<r.length&&(r=r.slice(0,e));for(const e of o){if(!e.replace||!e.regExp)continue;const n=r.match(e.regExp);if(null===n)continue;const o=n.index||0,s=o+n[0].length;let i;return 0===o?[i]=t.splitText(s):[,i]=t.splitText(o,s),i.selectNext(0,0),e.replace(i,n),!0}return!1}(n,o,i)||function(t,n,r){const o=t.getTextContent(),s=n-1,i=o[s],l=r[i];if(!l)return!1;for(const n of l){const{tag:r}=n,l=r.length,f=s-l+1;if(l>1&&!be(o,f,r,0,l))continue;if(\" \"===o[f-1])continue;const u=o[s+1];if(!1===n.intraword&&u&&!V.test(u))continue;const a=t;let d=a,g=Se(o,f,r),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=Se(t,t.length,r)}if(g<0)continue;if(d===a&&g+l===f)continue;const p=d.getTextContent();if(g>0&&p[g-1]===i)continue;const m=p[g-1];if(!1===n.intraword&&m&&!V.test(m))continue;if(!n.format.includes(\"code\")&&ye(d,g))continue;const x=a.getTextContent(),C=x.slice(0,f)+x.slice(s+1);a.setTextContent(C);const $=d===a?C:p;d.setTextContent($.slice(0,g)+$.slice(g+l));const v=T(),y=b();w(y);const S=s-l*(d===a?2:1)+1;y.anchor.set(d.__key,g,\"text\"),y.focus.set(a.__key,S,\"text\");for(const t of n.format)y.formatText(t,k[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 I(v)&&(y.format=v.format),!0}return!1}(n,o,s)))(t,y,d.anchor.offset)&&$(v)})}}),t.registerCommand(y,t=>{if(null!==t&&t.shiftKey)return!1;const n=T();if(!I(n)||!n.isCollapsed())return!1;const s=n.anchor.offset,i=n.anchor.getNode();if(!e(i)||!he(i))return!1;const l=i.getParent();return null!==l&&!M(l)&&!(s!==i.getTextContent().length||!ve(l,i,s,r.multilineElement,!0)&&!$e(l,i,s,o,!0)||(null!==t&&t.preventDefault(),0))},S))}function ke(t,e=ee,n,r=!1,o=!1){const s=r?t:ne(t,o),i=n||f();i.clear(),me(s,i,e,r),null!==T()&&i.selectStart()}function Ne(t,e=ee,n=!1,r=!1){const o=n?t:ne(t,r),s=new N;return me(o,s,e,n),s.getChildren()}function Fe(t=ee,e,n=!1){const r=function(t,e=!1){const n=Q(t),r=[...n.multilineElement,...n.element],o=!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 i=[],l=(t||f()).getChildren();for(let t=0;t<l.length;t++){const c=l[t],f=se(c,r,s,n.textMatch,e);null!=f&&i.push(o&&t>0&&!nt(c)&&!nt(l[t-1])?\"\\n\".concat(f):f)}return i.join(\"\\n\")}}(t,n);return r(e)}function Oe(t=ee,e,n=!1){if(!e||I(e)&&e.isCollapsed())return\"\";const r=function(t,e=!1){const n=Q(t),r=[...n.multilineElement,...n.element],o=!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 i=[];let l=null;for(const c of f().getChildren()){const{shouldInclude:f,markdown:u}=re(c,t,r,s,n.textMatch,e);f&&null!=u&&(i.push(!o||null===l||nt(c)||nt(l)?u:\"\\n\".concat(u)),l=c)}return i.join(\"\\n\")}}(t,n);return r(e)}export{ke as $convertFromMarkdownString,Oe as $convertSelectionToMarkdownString,Fe as $convertToMarkdownString,Ne as $generateNodesFromMarkdownString,Wt as BOLD_ITALIC_STAR,Ut as BOLD_ITALIC_UNDERSCORE,Dt as BOLD_STAR,Zt as BOLD_UNDERSCORE,Rt as CHECK_LIST,Lt as CODE,Jt as ELEMENT_TRANSFORMERS,Mt as HEADING,At as HIGHLIGHT,zt as INLINE_CODE,Kt as ITALIC_STAR,Xt as ITALIC_UNDERSCORE,Gt as LINK,Qt as MULTILINE_ELEMENT_TRANSFORMERS,jt as ORDERED_LIST,Bt as QUOTE,Ht as STRIKETHROUGH,Vt as TEXT_FORMAT_TRANSFORMERS,Yt as TEXT_MATCH_TRANSFORMERS,ee as TRANSFORMERS,_t as UNORDERED_LIST,gt as isTableRowDivider,we as registerMarkdownShortcuts};\n","import { CodeHighlightNode, CodeNode } from '@lexical/code-core';\nimport { LinkNode } from '@lexical/link';\nimport { ListItemNode, ListNode } from '@lexical/list';\nimport {\n  BOLD_ITALIC_STAR,\n  BOLD_ITALIC_UNDERSCORE,\n  BOLD_STAR,\n  BOLD_UNDERSCORE,\n  CODE,\n  HEADING,\n  INLINE_CODE,\n  ITALIC_STAR,\n  ITALIC_UNDERSCORE,\n  LINK,\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\n/**\n * @import { EditorThemeClasses, LexicalCommand } from 'lexical';\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 and strikethrough styling.\n     * @see https://github.com/facebook/lexical/discussions/4381\n     */\n    italic: 'italic',\n    strikethrough: 'strikethrough',\n  },\n  list: {\n    nested: {\n      listitem: 'nested',\n    },\n  },\n  code: 'code-block',\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  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  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};\n\n/**\n * @type {TextEditorFormatType[]}\n */\nexport const TEXT_FORMAT_BUTTON_TYPES = ['bold', 'italic', '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  'blockquote',\n  'code-block',\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  blockquote: [QuoteNode],\n  'code-block': [CodeNode, CodeHighlightNode],\n  link: [LinkNode],\n};\n\n/**\n * Map of Lexical transformers for each block type. The `paragraph` block type is excluded because\n * it is the default block type.\n * @type {Record<Exclude<TextEditorNodeType, 'paragraph'>, 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  '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  code: [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  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.\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 * 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 s,CLEAR_EDITOR_COMMAND as u,CLEAR_HISTORY_COMMAND as d,CAN_REDO_COMMAND as c,CAN_UNDO_COMMAND as p,COMPOSITION_START_TAG as f,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 v,$isRootNode as k}from\"lexical\";function C(t,e,n){let o=n(),r=0,i=o,a=0,l=null;return(s,u,d,c,p,C)=>{const b=n();if(C.has(f)&&(i=o,a=r,l=s),C.has(h))return r=0,o=b,2;C.has(m)&&l&&(o=i,r=a,s=l);const E=C.has(g)||C.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||k(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)&&v(o)&&1===o.__text.length&&1===i.anchor.offset?2:0}const s=l[0],u=t._nodeMap.get(s.__key);if(!v(u)||!v(s)||u.__mode!==s.__mode)return 0;const d=u.__text,c=s.__text;if(d===c)return 0;const p=i.anchor,f=a.anchor;if(p.key!==f.key||\"text\"!==p.type)return 0;const h=p.offset,m=f.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,u,c,p,t.isComposing()),w=(()=>{const n=null===d||d.editor===t,i=C.has(S);if(!i&&n&&C.has(_))return 0;if(1===E)return 2;if(null===s)return 1;const a=u._selection;if(!(c.size>0||p.size>0))return null!==a?0:2;const l=\"number\"==typeof e?e:e.peek();return!1===i&&0!==E&&E===r&&b<o+l&&n||1===c.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||!v(o)||!v(r)||o.__parent!==r.__parent)&&JSON.stringify(e.read(()=>o.exportJSON()))===JSON.stringify(n.read(()=>r.exportJSON()))}(Array.from(c)[0],s,u)?0:1})();return o=b,r=E,w}}function b(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 E(t,e){t.undoStack=[],t.redoStack=[],t.current=null,e&&e(t)}function w(t,e,n,o=Date.now,r,f=null){const m=C(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=b(a,i);null!==e&&(o.push(e),t.dispatchCommand(c,!0))}0===r.length&&t.dispatchCommand(p,!1),e.current=a||null,n&&n(e),a&&a.editor.setEditorState(a.editorState,{tag:h})}}(t,e,r),!0),l),t.registerCommand(s,()=>(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=b(a,i);null!==e&&(r.push(e),t.dispatchCommand(p,!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(u,()=>(E(e,r),!1),l),t.registerCommand(d,()=>(E(e,r),t.dispatchCommand(c,!1),t.dispatchCommand(p,!1),!0),l),t.registerUpdateListener(({editorState:n,prevEditorState:o,dirtyLeaves:r,dirtyElements:i,tags:a})=>{const l=e.current,s=e.redoStack,u=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!==s.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){u.push(n);const e=\"number\"==typeof f||null===f?f:f.peek();null!==e&&u.length>e&&u.splice(0,u.length-e),t.dispatchCommand(p,!0)}}else if(2===h)return;e.current={editor:t,editorState:n},g()}))}function D(){return{current:null,redoStack:[],undoStack:[]}}const M={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:D,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(),s=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 w(e,l.historyState.value,l.delay,()=>l.now.peek()(),s,l.maxDepth);s(null)})}};function O(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:[[M,{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(M);O(e),O(r.value);const a=function(t){return t?o(t,M.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{M as HistoryExtension,z as SharedHistoryExtension,D as createEmptyHistoryState,w 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 d,$applyNodeReplacement as h,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 E,TEXT_TYPE_TO_FORMAT as K,$getEditor as z,$setSelection as M,SELECTION_CHANGE_COMMAND as W,removeClassNamesFromElement as $,getDOMSelection as H,$createRangeSelection as L,$isRootNode as D,INSERT_PARAGRAPH_COMMAND as B,registerEventListener as P,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 de,$isRootOrShadowRoot as he,getDOMSelectionRange as fe,getDOMSelectionPoints as ge,$getPreviousSelection as me,$caretFromPoint as pe,$getChildCaret as _e,$getCommonAncestor as Ce,$comparePointCaretNext as Se,$isExtendableTextPointCaret as ye,$extendCaretToRange as be,$isSiblingCaret as we,$getSiblingCaret as xe,$setPointFromCaret as ve,$normalizeCaret as Ne,$createRangeSelectionFromDom as Te,$isChildCaret as Re,$getAdjacentChildCaret as Fe,IS_FIREFOX as Ae,$getNodeByKeyOrThrow as Oe,registerEventListeners as ke,isDOMDocumentNode as Ee,isDOMShadowRoot as Ke,setDOMStyleFromCSS as ze,setDOMUnmanaged as Me,booleanValue as We,arrayValue as $e,mergeRegister as He,COMMAND_PRIORITY_EDITOR as Le,SELECTION_INSERT_CLIPBOARD_NODES_COMMAND as De,SELECT_ALL_COMMAND as Be,COMMAND_PRIORITY_LOW as Pe,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 dt,$dfs as ht,$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 d=l[e.__format];void 0!==d&&\"\"!==d&&(r.format=d);const h=e.__indent;return void 0!==h&&0!==h&&(r.indent=h),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 d=e.__width;void 0!==d&&(r.width=d);const h=e.__dir;null!=h&&(r.direction=h);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\",{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 h=t.style.backgroundColor;\"\"!==h&&(r.__backgroundColor=h);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=d().append(l),t.push(n))}else t.push(l),o(),n=null;return o(),0===t.length&&t.push(d()),t},node:r}}function kt(e=Tt.NO_STATUS,t=1,n){return h(new Ft(e,t,n))}function Et(e){return e instanceof Ft}const Kt=/* @__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,Et),node:s(Ht(n),t)}}function Ht(e){return h(new Wt(e))}function Lt(e){return e instanceof Wt}function Dt(e,t,n=!0){const o=zo();for(let l=0;l<e;l++){const e=Ht();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=d();i.append(w()),r.append(i),e.append(r)}o.append(e)}return o}function Bt(e){const t=N(e,e=>Et(e));return Et(t)?t:null}function Pt(e){const t=N(e,e=>Lt(e));if(Lt(t))return t;throw new Error(\"Expected table cell to be inside of table row.\")}function It(e){const t=N(e,e=>Mo(e));if(Mo(t))return t;throw new Error(\"Expected table cell to be inside of table.\")}function Ut(e){const t=Pt(e);return It(t).getChildren().findIndex(e=>e.is(t))}function Xt(e){return Pt(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(!Lt(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=Ht();for(let n=0;n<t;n++){const t=e[n];Et(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(d()),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)||Fn(t)||zt(188);const n=t.anchor.getNode(),o=t.focus.getNode(),[l]=_n(n),[r,,i]=_n(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]=_n(e),[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=Ht();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(d()))}else n.setRowSpan(n.__rowSpan+1)}const a=n.getChildAtIndex(t);Lt(a)||zt(256),a.insertAfter(c),s=c}else{const e=i,t=o[e],l=Ht();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(d()))}else o.setRowSpan(o.__rowSpan+1)}const c=n.getChildAtIndex(e);Lt(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(Lt(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];Et(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(d()),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)||Fn(t)||zt(188);const n=t.anchor.getNode(),o=t.focus.getNode(),[l]=_n(n),[r,,i]=_n(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]=_n(e),[l,r]=mn(o,e,e),i=l.length,{startColumn:s}=r,c=t?s+e.__colSpan-1:s-1,a=o.getFirstChild();Lt(a)||zt(120);let u=null;function h(e=Tt.NO_STATUS){const t=kt(e).append(d());return null===u&&(u=t),t}let f=a;for(let e=0;e<i;e++){if(0!==e){const e=f.getNextSibling();Lt(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,h(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,h(o)):n.insertAfter(h(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(Lt(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)||Fn(e)||zt(188);const[t,n]=e.isBackward()?[e.focus.getNode(),e.anchor.getNode()]:[e.anchor.getNode(),e.focus.getNode()],[o,,l]=_n(t),[r]=_n(n),[i,s,c]=mn(l,o,r),{startRow:a}=s,{startRow:u}=c,d=u+r.__rowSpan-1;if(i.length===d-a+1)return l.selectPrevious(),void l.remove();const h=i[0].length,f=i[d+1],g=l.getChildAtIndex(d+1);for(let e=d;e>=a;e--){for(let t=h-1;t>=0;t--){const{cell:n,startRow:o,startColumn:l}=i[e][t];if(l===t){if(o<a||o+n.__rowSpan-1>d){const e=Math.max(o,a),t=Math.min(n.__rowSpan+o-1,d),l=e<=t?t-e+1:0;n.setRowSpan(n.__rowSpan-l)}if(o>=a&&o+n.__rowSpan-1>d&&e===d){Lt(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);Lt(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)||Fn(e)||zt(188);const t=e.anchor.getNode(),n=e.focus.getNode(),[o,,l]=_n(t),[r]=_n(n),[i,s,c]=mn(l,o,r),{startColumn:a}=s,{startRow:u,startColumn:d}=c,h=Math.min(a,d),f=Math.max(a+o.__colSpan-1,d+r.__colSpan-1),g=f-h+1;if(i[0].length===f-h+1)return l.selectPrevious(),void l.remove();const m=i.length;for(let e=0;e<m;e++)for(let t=h;t<=f;t++){const{cell:n,startColumn:o}=i[e][t];if(o<h){if(t===h){const e=h-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>d?p[a+o.__colSpan]:p[d+r.__colSpan];if(void 0!==_){const{cell:e}=_;an(e)}else{const e=d<a?p[d-1]:p[a-1],{cell:t}=e;an(t)}const C=l.getColWidths();if(C){const e=[...C];e.splice(h,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 dn(e){if(0===e.length)return null;const t=It(e[0]),[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 h=u.cell;h.setColSpan(a),h.setRowSpan(c);const f=new Set([h.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),hn(l)||(hn(h)&&h.clear(),h.append(...l.getChildren())),l.remove())}return 0===h.getChildrenSize()&&h.append(d()),h}function hn(e){if(1!==e.getChildrenSize())return!1;const t=e.getFirstChildOrThrow();return!(!T(t)||!t.isEmpty())}function fn(){const e=x();v(e)||Fn(e)||zt(188);const t=e.anchor.getNode(),n=N(t,Et);return Et(n)||zt(148),gn(n)}function gn(e){const[t,n,o]=_n(e),l=t.__colSpan,r=t.__rowSpan;if(1===l&&1===r)return;const[i,s]=mn(o,t,t),{startColumn:c,startRow:a}=s,u=t.__headerState&Tt.COLUMN,h=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(d());if(l>1){for(let e=1;e<l;e++)t.insertAfter(m(h[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(),Lt(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(h[n]|g[t]));else for(let e=l-1;e>=0;e--)s.insertAfter(m(h[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];Lt(o)||zt(209);const c=i(e);for(let a=o.getFirstChild(),u=0;null!=a;a=a.getNextSibling()){for(Et(a)||zt(147);void 0!==c[u];)u++;const o={cell:a,startColumn:u,startRow:e},{__rowSpan:d,__colSpan:h}=a;for(let t=0;t<d&&!(e+t>=s.length);t++){const n=i(e+t);for(let e=0;e<h;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){let t;if(e instanceof Ft)t=e;else if(\"__type\"in e){const n=N(e,Et);Et(n)||zt(148),t=n}else{const n=N(e.getNode(),Et);Et(n)||zt(148),t=n}const n=t.getParent();Lt(n)||zt(149);const o=n.getParent();return Mo(o)||zt(210),[t,n,o]}function Cn(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,d=c.startColumn<=i&&a>=l,h=c.startRow<=s&&u>=r;if(d&&h){const e=Math.min(l,c.startColumn),t=Math.max(i,a),n=Math.min(r,c.startRow),d=Math.max(s,u);e===l&&t===i&&n===r&&d===s||(l=e,i=t,r=n,s=d,o=!0)}}}while(o);return{maxColumn:i,maxRow:s,minColumn:l,minRow:r}}function Sn(e){const t=e.getChildren();let n=null;for(const e of t){if(!Lt(e))return!1;if(null===n&&(n=e.getChildrenSize()),e.getChildrenSize()!==n)return!1;const t=e.getChildren();for(const e of t)if(!Et(e)||1!==e.getRowSpan()||1!==e.getColSpan())return!1}return(n||0)>0}function yn(e,t,n){if(t===n)return;const o=e.getColumnCount();if(t<0||t>=o||n<0||n>=o)return;if(!Sn(e))return;e.getChildren().filter(Lt).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 bn(e,t,n){if(t===n)return;const o=e.getChildren().filter(Lt),l=o.length;if(t<0||t>=l||n<0||n>=l)return;if(!Sn(e))return;const r=o[t],i=o[n];n>t?i.insertAfter(r):i.insertBefore(r)}function wn(e){const[t,,n]=_n(e),o=n.getChildren().filter(Lt),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(Et);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 xn(e,t){const n=t.getStartEndPoints(),o=Fn(t);if(null===n)return!1;const[l,r]=n,[i,s,c]=_n(l),u=N(r.getNode(),e=>Et(e));if(!(Et(i)&&Et(u)&&Lt(s)&&Mo(c)))return!1;const[h,f,g]=mn(c,i,u),[m]=pn(e,null,null),p=h.length,_=p>0?h[0].length:0;let C=f.startRow,S=f.startColumn,y=m.length,b=y>0?m[0].length:0;if(o){const e=Cn(h,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=h[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)}dn(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)?(d().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 vn(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 Nn(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 Tn(e){const[[t,n,o,l],[r,i,s,c]]=[\"anchor\",\"focus\"].map(t=>{const n=e[t].getNode(),o=N(n,Et);Et(o)||zt(238,t,n.getKey(),n.getType());const l=o.getParent();Lt(l)||zt(239,t);const r=l.getParent();return Mo(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 Rn{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 Fn(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 Rn(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=zo();for(const e of t){const t=Ht();for(const n of e){const e=kt(Tt.NO_STATUS),o=d();n&&o.append(w(n)),e.append(o),t.append(e)}n.append(t)}const{anchorCell:o}=Tn(this);xn(n,o.select(0,o.getChildrenSize()))}insertText(){}hasFormat(e){let t=0;this.getNodes().filter(Et).forEach(e=>{const n=e.getFirstChild();T(n)&&(t|=n.getTextFormat())});const n=K[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}=Tn(this),n=wn(e);null===n&&zt(153);const o=wn(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}=Tn(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:d}=Cn(r,i,s),h=new Map([[t.getKey(),t]]);let f=null;for(let e=u;e<=d;e++)for(let t=c;t<=a;t++){const{cell:n}=r[e][t],o=n.getParent();Lt(o)||zt(160),o!==f&&(h.set(o.getKey(),o),f=o),h.has(n.getKey())||kn(n,e=>{h.set(e.getKey(),e)})}const g=Array.from(h.values());return E()||(this._cachedNodes=g),g}getTextContent(){const e=this.getNodes().filter(e=>Et(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 Fn(e){return e instanceof Rn}function An(){const e=F(\"root\",0,\"element\"),t=F(\"root\",0,\"element\");return new Rn(\"root\",e,t)}function On(e,t,n){e.getKey(),t.getKey(),n.getKey();const o=x(),l=Fn(o)?o.clone():new Rn(\"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);Mo(n)||zt(231,e);const o=Dn(n,t.getElementByKey(e));return null===o&&zt(232,e),{tableElement:o,tableNode:n}}class Kn{observers;nextFocus;shouldCheckSelectionForTable;constructor(){this.observers=new Map,this.nextFocus=null,this.shouldCheckSelectionForTable=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);Mo(o)?e.push([o,n]):this.removeObserver(t)}return e}}class zn{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=Qn(n,o)})});this.listenersToRemove.add(()=>e.disconnect()),this.editor.read(\"latest\",()=>{const{tableNode:t,tableElement:n}=this.$lookup();this.table=Qn(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();Zn(t,Qn(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(),Zn(t,this.table,this.tableSelection)}else this.$clearHighlight()}updateDOMSelection(){if(null!==this.anchorCell&&null!==this.focusCell){const e=H(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=Co(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=On(o,t,e),M(this.tableSelection),n.dispatchCommand(W),Zn(n,this.table,this.tableSelection),!0}}}return!1}$getAnchorTableCell(){const e=this.anchorCellNodeKey?A(this.anchorCellNodeKey):null;return Et(e)?e:null}$getAnchorTableCellOrThrow(){const e=this.$getAnchorTableCell();return null===e&&zt(234),e}$getFocusTableCell(){const e=this.focusCellNodeKey?A(this.focusCellNodeKey):null;return Et(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=Co(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=On(t,n,n),this.anchorCellNodeKey=e}}$formatCells(e){const t=x();Fn(t)||zt(236);const n=L(),o=n.anchor,l=n.focus,r=t.getNodes().filter(Et);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(!Mo(t))throw new Error(\"Expected TableNode.\");const n=x();Fn(n)||zt(253);const o=n.getNodes().filter(Et),l=t.getFirstChild(),r=t.getLastChild();if(o.length>0&&null!==l&&null!==r&&Lt(l)&&Lt(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(B))}o.forEach(e=>{if(O(e)){const t=e.getFirstChild(),n=T(t)?R(t):d(),o=w();n.append(o),e.append(n),e.getChildren().forEach(e=>{e!==n&&e.remove()})}}),Zn(e,this.table,null),M(null),e.dispatchCommand(W)}}const Mn=\"__lexicalTableSelection\";function Wn(e){const t=Oe(e);return Mo(t)||zt(386,e),t}const $n=40;function Hn(e,t,n){const o=e=>Math.max(1,Math.ceil(Math.min($n,e)/$n*18));return e<=t+$n?-o(t+$n-e):e>=n-$n?o(e-(n-$n)):0}function Ln(e){return i(e)&&\"TABLE\"===e.nodeName}function Dn(e,t){if(!t)return t;const n=Ln(t)?t:t.querySelector(\"table\");return Ln(n)||zt(341,e.constructor.name,e.getType(),e.getKey(),t.nodeName),n}function Bn(e){return e._window}function Pn(e,t){for(let n=t,o=null;null!==n;n=n.getParent()){if(e.is(n))return o;Et(n)&&(o=n)}return null}const In=[[I,\"down\"],[U,\"up\"],[X,\"backward\"],[Y,\"forward\"]],Un=[j,J,G],Xn=[Q,Z];function Yn(e,t){return e.registerRootListener(n=>{if(null===n)return;const o=e._window;return null!==o?P(o,\"pointerdown\",o=>{const l=ne(o);if(0!==o.button||!oe(l)||!n.contains(l))return;const r=function(e){const t=Jn(e);if(null===t)return null;let n=t.elem;for(;null!=n;){if(\"TABLE\"===n.nodeName&&Mn in n&&n[Mn])return{cellElement:t,tableElement:n,tableObserver:n[Mn]};n=n.parentNode}return null}(l);e.update(()=>{if(Fn(x())){for(const[e]of t.observers.values())e.$clearHighlight(!1);M(null),e.dispatchCommand(W)}if(!r)return;const{tableObserver:n,tableElement:l,cellElement:i}=r;!function(e,t,n,o,l,r){const i=e._window;if(!i)return;l.pointerType=t.pointerType;const s=Wn(l.tableNodeKey),c=me(),a=v(c)||Fn(c)?uo(c.anchor.getNode()):null,u=null!==a&&a.isParentOf(s);if(Ae&&t.shiftKey&&(v(c)||Fn(c))&&(io(c,s)||u)){const e=c.anchor.getNode(),o=Pn(s,c.anchor.getNode());if(o){const e=_o(l,o);e.elem!==n.elem?(l.$setAnchorCellForSelection(e),l.$setFocusCellForSelection(n),go(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),go(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 d=!s;s||null!==l.anchorCell||e.update(()=>{l.$setAnchorCellForSelection(n)});let h=t.clientX,f=t.clientY,g=null,m=null;const p=e=>e.pointerId===c,_=()=>{l.isSelecting=!1,l.isPointerDrag=!1,l.pointerStartCell=null,null!==g&&(i.cancelAnimationFrame(g),g=null),null!==m&&(m(),m=null)},C=(e,t)=>{const n=o.getRootNode();if(!Ee(n)&&!Ke(n))return null;for(const l of n.elementsFromPoint(e,t)){const e=Gn(o,l);if(e)return e}return null},S=(t,o)=>{if(d||l.isPointerDrag&&t.elem!==n.elem){if(null===l.anchorCell||!d){const o=d?t:n;e.update(()=>{l.$setAnchorCellForSelection(o)})}d=!0,null!==l.focusCell&&t.elem===l.focusCell.elem||(r.setNextFocus({focusCell:t,override:o,tableKey:l.tableNodeKey}),e.dispatchCommand(W))}},y=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},b=(e,t,n)=>{let o,l;if(null===e)o=0,l=\"x\"===n?i.innerWidth:i.innerHeight;else{const t=e.getBoundingClientRect();o=\"x\"===n?t.left:t.top,l=\"x\"===n?t.right:t.bottom}const r=Hn(t,o,l);if(0===r)return!1;if(null===e){const e=\"x\"===n?i.scrollX:i.scrollY;return i.scrollBy(\"x\"===n?r:0,\"x\"===n?0:r),(\"x\"===n?i.scrollX:i.scrollY)!==e}if(\"x\"===n){const t=e.scrollLeft;return e.scrollLeft+=r,e.scrollLeft!==t}const s=e.scrollTop;return e.scrollTop+=r,e.scrollTop!==s},w=()=>{if(g=null,!l.isSelecting)return;const e=y(\"x\"),t=y(\"y\"),n=null!==e&&b(e,h,\"x\"),o=b(t,f,\"y\");if(n||o){const[n,o]=((e,t)=>{let n=h,o=f;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]})(e,t),l=C(n,o);l&&S(l,!1),g=i.requestAnimationFrame(w)}},x=()=>{null!==g||s&&!l.isPointerDrag||!(()=>{const e=y(\"x\");if(null!==e){const t=e.getBoundingClientRect();if(0!==Hn(h,t.left,t.right))return!0}const t=y(\"y\"),n=null===t?0:t.getBoundingClientRect().top,o=null===t?i.innerHeight:t.getBoundingClientRect().bottom;return 0!==Hn(f,n,o)})()||(g=i.requestAnimationFrame(w))},v=e=>{p(e)&&_()};m=ke(i,{lostpointercapture:v,pointercancel:v,pointermove:e=>{if(!p(e))return;if(!(e=>!(1&~e.buttons))(e)&&l.isSelecting)return void _();const t=ne(e);if(!oe(t))return;var n,r;h=e.clientX,f=e.clientY,!l.isPointerDrag&&(n=h,r=f,!(Math.abs(n-a)<=10&&Math.abs(r-u)<=10))&&(l.isPointerDrag=!0);let i=null;const s=!(Ae||o.contains(t));i=s?Gn(o,t):C(e.clientX,e.clientY),i&&S(i,s),x()},pointerup:e=>{p(e)&&_()}},l.listenerOptions)})(n)}(e,o,i,l,n,t)})}):void 0})}function qn(e,t,n,o,l){const r=n.getRootElement(),i=Bn(n);null!==r&&null!==i||zt(246);const s=new zn(n,e.getKey()),c=Dn(e,t);!function(e,t){null!==jn(e)&&zt(205),e[Mn]=t}(c,s),s.listenersToRemove.add(()=>function(e,t){jn(e)===t&&delete e[Mn]}(c,s)),s.listenersToRemove.add(P(c,\"mousedown\",e=>{const t=ne(e);e.detail>=3&&oe(t)&&null!==Jn(t)&&e.preventDefault()},s.listenerOptions));for(const[t,o]of In)s.listenersToRemove.add(n.registerCommand(t,t=>fo(n,t,o,e,s,l),q));s.listenersToRemove.add(n.registerCommand(V,t=>{const n=x();if(Fn(n)){const o=Pn(e,n.focus.getNode());if(null!==o)return go(t),o.selectEnd(),!0}return!1},q));const a=()=>{const t=x();return!!io(t,e)&&!!Fn(t)&&(s.$clearText(),!0)};for(const e of Un)s.listenersToRemove.add(n.registerCommand(e,a,q));const u=t=>{const n=x();if(!Fn(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!!io(n,e)&&!!Fn(n)&&(t&&(t.preventDefault(),t.stopPropagation()),s.$clearText(),!0)};for(const e of Xn)s.listenersToRemove.add(n.registerCommand(e,u,q));s.listenersToRemove.add(n.registerCommand(ee,e=>{const t=x();if(t){if(!Fn(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 d=r.ownerDocument;return s.listenersToRemove.add(P(d,\"paste\",t=>{t.defaultPrevented||n.read(\"latest\",()=>{const t=x();return r.contains(d.activeElement)&&Fn(t)&&io(t,e)})&&(t.preventDefault(),n.dispatchCommand(te,t))})),s.listenersToRemove.add(P(d,\"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))&&Fn(t)&&io(t,e)})&&(t.preventDefault(),n.dispatchCommand(re,t))})),s.listenersToRemove.add(n.registerCommand(ie,t=>{const n=x();return!!io(n,e)&&!!Fn(n)&&(s.$formatCells(t),!0)},q)),s.listenersToRemove.add(n.registerCommand(se,t=>{const n=x();if(!Fn(n)||!io(n,e))return!1;const o=n.anchor.getNode(),l=n.focus.getNode();if(!Et(o)||!Et(l))return!1;const[r,i,s]=mn(e,o,l),{minColumn:c,maxColumn:a,minRow:u,maxRow:d}=Cn(r,i,s);if(0===u&&0===c&&d===r.length-1&&a===r[0].length-1)return e.setFormat(t),!0;const h=new Set;for(let e=u;e<=d;e++)for(let n=c;n<=a;n++){const o=r[e][n].cell;if(h.has(o))continue;h.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(!io(o,e))return!1;if(Fn(o))return s.$clearHighlight(),!1;if(v(o)){const l=N(o.anchor.getNode(),e=>Et(e));if(!Et(l))return!1;if(\"string\"==typeof t){const l=po(n,o,e);if(l)return mo(l,e,[w(t)]),!0}}return!1},q)),o&&s.listenersToRemove.add(n.registerCommand(ae,t=>{const n=x();if(!v(n)||!n.isCollapsed()||!io(n,e))return!1;const o=uo(n.anchor.getNode());return!(null===o||!e.is(ho(o))||(go(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,Lt);null===r&&zt(247);for(let e=r[n]();Lt(e);e=e[n]()){const t=e[o]();if(O(t))return t.selectEnd()}const i=N(r,Mo);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(B,()=>{const t=x();if(!v(t)||!t.isCollapsed()||!io(t,e))return!1;const o=po(n,t,e);return!!o&&(mo(o,e),!0)},q)),s}function Vn(e,t,n){const o=x(),l=t.isSelected();if(!(Fn(o)&&o.tableKey===t.getKey()||n.isHighlightingCells||n.hasHijackedSelectionStyles||l))return;const{tableElement:r}=n.$lookup();if(n.table=Qn(t,r),Fn(o)&&o.tableKey===t.getKey()){const e=A(o.anchor.key),t=A(o.focus.key);if(Et(e)&&Et(t)){const o=_o(n,e),l=_o(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(),eo(t.table,t=>{const n=t.elem;t.highlighted=!1,ao(e,t),n.getAttribute(\"style\")||n.removeAttribute(\"style\")})}(e,n):!n.hasHijackedSelectionStyles&&l&&function(e,t){t.$disableHighlightStyle(),eo(t.table,t=>{t.highlighted=!0,co(e,t)})}(e,n)}function jn(e){return e[Mn]||null}function Jn(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 Gn(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 Qn(e,t){const n=[],o={columns:0,domRows:n,rows:0};let l=Dn(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 Zn(e,t,n){const o=new Set(n?n.getNodes():[]);eo(t,(t,n)=>{const l=t.elem;o.has(n)?(t.highlighted=!0,co(e,t)):(t.highlighted=!1,ao(e,t),l.getAttribute(\"style\")||l.removeAttribute(\"style\"))})}function eo(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=de(l.elem);null!==r&&t(l,r,{x:n,y:e})}}}const to=(e,t,n,o,l)=>{const r=\"forward\"===l;switch(l){case\"backward\":case\"forward\":return n!==(r?e.table.columns-1:0)?so(t.getCellNodeFromCordsOrThrow(n+(r?1:-1),o,e.table),r):o!==(r?e.table.rows-1:0)?so(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?so(t.getCellNodeFromCordsOrThrow(n,o-1,e.table),!1):t.selectPrevious(),!0;case\"down\":return o!==e.table.rows-1?so(t.getCellNodeFromCordsOrThrow(n,o+1,e.table),!0):t.selectNext(),!0;default:return!1}};function no(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 oo(e,t,n){const o=no(e,t);if(o)return o;const l=no(e,n);return l?lo(l):[\"minColumn\",\"minRow\"]}function lo([e,t]){return[\"minColumn\"===e?\"maxColumn\":\"minColumn\",\"minRow\"===t?\"maxRow\":\"minRow\"]}function ro(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 io(e,t){if(v(e)||Fn(e)){const n=t.isParentOf(e.anchor.getNode()),o=t.isParentOf(e.focus.getNode());return n&&o}return!1}function so(e,t){t?e.selectStart():e.selectEnd()}function co(e,t){const n=t.elem,o=e._config.theme;Et(de(n))||zt(131),r(n,o.tableCellSelected)}function ao(e,t){const n=t.elem;Et(de(n))||zt(131);const o=e._config.theme;$(n,o.tableCellSelected)}function uo(e){const t=N(e,Et);return Et(t)?t:null}function ho(e){const t=N(e,Mo);return Mo(t)?t:null}function fo(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(!io(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!!Mo(n)&&(go(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=>Mo(e));if(Et(l)&&(l=N(l,Mo)),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),go(t),!0}if(he(e)){const e=\"up\"===n?i.getNodes()[i.getNodes().length-1]:i.getNodes()[0];if(e&&null!==Pn(o,e)){const e=o.getFirstDescendant(),t=o.getLastDescendant();if(!e||!t)return!1;const[n]=_n(e),[r]=_n(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(Et(o)&&(o=N(o,Mo)),!o)return!1;const r=\"down\"===n?o.getNextSibling():o.getPreviousSibling();if(Mo(r)&&l.tableNodeKey===r.getKey()){const e=r.getFirstDescendant(),o=r.getLastDescendant();if(!e||!o)return!1;const[l]=_n(e),[s]=_n(o),c=i.clone();return c.focus.set((\"up\"===n?l:s).getKey(),\"up\"===n?0:s.getChildrenSize(),\"element\"),go(t),M(c),!0}}}}return\"down\"===n&&Fo(e)&&function(e,t){if(!v(e))return!1;const n=pe(e.focus,\"next\"),o=_e(t,\"next\");return null!==Ce(n.origin,o.origin)&&Se(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=pe(n.focus,l?\"previous\":\"next\");if(ye(s))return!1;let c=s;for(const e of be(s).iterNodeCarets(\"shadowRoot\")){if(!we(e)||!O(e.origin))return!1;c=e}const a=c.getParentAtCaret();if(!Et(a))return!1;const u=a,d=function(e){for(const t of be(e).iterNodeCarets(\"root\")){const{origin:n}=t;if(Et(n)){if(Re(t))return _e(n,e.direction)}else if(!Lt(n))break}return null}(xe(u,c.direction)),h=N(u,Mo);if(!h||!h.is(r))return!1;const f=e.getElementByKey(u.getKey()),g=Jn(f);if(!f||!g)return!1;const m=Eo(e,h);if(i.table=m,d)if(\"extend\"===o){const t=Jn(e.getElementByKey(d.origin.getKey()));if(!t)return!1;i.$setAnchorCellForSelection(g),i.$setFocusCellForSelection(t,!0)}else{const e=Ne(d);ve(n.anchor,e),ve(n.focus,e)}else if(\"extend\"===o)i.$setAnchorCellForSelection(g),i.$setFocusCellForSelection(g,!0);else{const e=function(e){const t=Fe(e);return Re(t)?Ne(t):e}(xe(h,s.direction));ve(n.anchor,e),ve(n.focus,e)}return go(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(),Et),u=N(c.getNode(),Et);if(!Et(a)||!a.is(u))return!1;const d=ho(a);if(d!==o&&null!=d){const o=Dn(d,e.getElementByKey(d.getKey()));if(null!=o)return l.table=Qn(d,o),fo(e,t,n,d,l,r)}const h=e.getElementByKey(a.__key),f=e.getElementByKey(s.key);if(null==f||null==h)return!1;let g;if(\"element\"===s.type)g=f.getBoundingClientRect();else{const t=H(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){go(t);const e=o.getCordsFromCellNode(a,l.table);if(!t.shiftKey)return to(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(Fn(i)){const{anchor:r,focus:s,tableKey:c}=i;if(c!==o.getKey())return!1;const a=N(r.getNode(),Et),u=N(s.getNode(),Et),[d]=i.getNodes();Mo(d)||zt(251);const h=Dn(d,e.getElementByKey(d.getKey()));if(!Et(a)||!Et(u)||!Mo(d)||null==h)return!1;l.$updateTableTableSelection(i);const f=Qn(d,h),g=o.getCordsFromCellNode(a,f),m=o.getDOMCellFromCordsOrThrow(g.x,g.y,f);if(l.$setAnchorCellForSelection(m),go(t),t.shiftKey){const[e,t,r]=mn(o,a,u);return function(e,t,n,o,l){const r=Cn(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],d=e[r];for(let e=n;e<=o;e++)i=Math.max(i,u[e].cell.__rowSpan),a=Math.max(a,d[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,d=oo(r,n,o),[h,f]=lo(d);let g=r[h],m=r[f];\"forward\"===l?g+=\"maxColumn\"===h?1:c:\"backward\"===l?g-=\"minColumn\"===h?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=Cn(e,t,n),l=oo(o,t,n);return[ro(e,o,l),ro(e,o,lo(l))]}(t,n,_),y=_o(e,C.cell),b=_o(e,S.cell);return e.$setAnchorCellForSelection(y),e.$setFocusCellForSelection(b,!0),!0}(l,e,t,r,n)}return u.selectEnd(),!0}return!1}function go(e){e.preventDefault(),e.stopImmediatePropagation(),e.stopPropagation()}function mo(e,t,n){const o=d();\"first\"===e?t.insertBefore(o):t.insertAfter(o),o.append(...n||[]),o.selectEnd()}function po(e,t,n){const o=n.getParent();if(!o)return;const l=H(Bn(e));if(!l)return;const r=ge(l,e.getRootElement()).anchorNode,i=e.getElementByKey(o.getKey()),s=Dn(n,e.getElementByKey(n.getKey()));if(!r||!i||!s||!i.contains(r)||s.contains(r))return;const c=N(t.anchor.getNode(),e=>Et(e));if(!c)return;const a=N(c,e=>Mo(e));if(!Mo(a)||!a.is(n))return;const[u,d]=mn(n,c,c),h=u[0][0],f=u[u.length-1][u[0].length-1],{startRow:g,startColumn:m}=d,p=g===h.startRow&&m===h.startColumn,_=g===f.startRow&&m===f.startColumn;return p?\"first\":_?\"last\":void 0}function _o(e,t){const{tableNode:n}=e.$lookup(),o=n.getCordsFromCellNode(t,e.table);return n.getDOMCellFromCordsOrThrow(o.x,o.y,e.table)}function Co(e,t,n){return Pn(e,de(t,n))}function So(e){return i(e)&&\"DIV\"===e.nodeName}const yo=/* @__PURE__ */f()({colWidths:/* @__PURE__ */_(/* @__PURE__ */m(/* @__PURE__ */$e(/* @__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__ */We(),{getter:\"getSerializedRowStriping\",setter:{field:\"__rowStriping\"}})});function bo(e,t,n){let o=e.querySelector(\":scope > colgroup\");if(!n)return void(o&&o.remove());o||(o=l().createElement(\"colgroup\"),Me(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 wo(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 xo=new WeakSet;function vo(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 xo.add(n),n.style.display=\"none\",t.style.scrollbarWidth=\"auto\",()=>{};const l=()=>{n.scrollLeft!==t.scrollLeft&&(n.scrollLeft=t.scrollLeft)},r=()=>{t.scrollLeft!==n.scrollLeft&&(t.scrollLeft=n.scrollLeft)};t.addEventListener(\"scroll\",l,{passive:!0}),n.addEventListener(\"scroll\",r,{passive:!0});let i=null;return\"undefined\"!=typeof ResizeObserver&&(i=new ResizeObserver(()=>{No(t,n)}),i.observe(t),i.observe(o)),No(t,n),()=>{t.removeEventListener(\"scroll\",l),n.removeEventListener(\"scroll\",r),i&&i.disconnect()}}function No(e,t){if(xo.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 To(e){if(!e.hasAttribute(\"data-lexical-sticky-scrollbar\"))return null;const t=e.firstElementChild;if(!So(t))return null;const n=t.querySelector(\":scope > table\");if(!Ln(n))return null;const o=t.nextElementSibling;return So(o)?{scrollable:t,scrollbar:o,tableElement:n}:null}const Ro=new WeakSet;function Fo(e=z()){return Ro.has(e)}function Ao(e=z()){const t=st(e,\"@lexical/table/Table\");return!!t&&t.output.hasStickyScrollbar.peek()&&t.output.hasHorizontalScroll.peek()}function Oo(e,t){t?Ro.add(e):Ro.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:Ko,priority:1})},json:yo})}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=Ln(e)?e:e.querySelector(\"table\");return Ln(t)||zt(229),super.getDOMSlot(e).withElement(t).withAfter(t.querySelector(\":scope > colgroup\"))}createDOM(e,t){const n=l().createElement(\"table\");if(this.__style&&ze(n.style,this.__style),this.getColWidths()){const e=l().createElement(\"colgroup\");n.appendChild(e),Me(e)}if(r(n,e.theme.table),this.updateTableElement(null,n,e),Fo(t)){const o=Ao(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),Me(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:\"\")&&ze(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||bo(t,this.getColumnCount(),this.getColWidths()),wo(t,n,this.getFormatType())}updateDOM(e,t,n){const o=Dn(this,t);if(t===o===Fo())return!0;if(So(t)){if(t.hasAttribute(\"data-lexical-sticky-scrollbar\")!==Ao())return!0;const l=o.parentElement;So(l)&&this.updateTableWrapper(e,l,o,n)}return this.updateTableElement(e,o,n),!1}scaleDOMColWidths(e,t){const n=this.getColWidths();n&&bo(Dn(this,e),this.getColumnCount(),n.map(e=>e*t))}exportDOM(e){const t=super.exportDOM(e),{element:n}=t,o=!Ln(n)&&i(n)?n.querySelector(\"table\"):n;if(i(n)&&Ln(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)),!Ln(n)&&i(n)&&(n=n.querySelector(\"table\")),!Ln(n))return null;wo(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=Co(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=de(o.elem);return Et(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(!Lt(e))return 0;let t=0;return e.getChildren().forEach(e=>{Et(e)&&(t+=e.getColSpan())}),t}}function Eo(e,t){const n=e.getElementByKey(t.getKey());return null===n&&zt(230),Qn(t,n)}function Ko(e){const t=zo();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,Lt),node:t}}function zo(){return h(new ko)}function Mo(e){return e instanceof ko}function Wo(e){Lt(e.getParent())?e.isEmpty()&&e.append(d()):e.remove()}function $o(e){Mo(e.getParent())?ft(e,Et):e.remove()}function Ho(e){ft(e,Lt);const[t]=pn(e,null,null),n=t.reduce((e,t)=>Math.max(e,t.length),0),o=e.getChildren();for(let e=0;e<t.length;++e){const l=o[e];if(!l)continue;Lt(l)||zt(254,l.constructor.name,l.getType());const r=t[e].reduce((e,t)=>t?1+e:e,0);if(r===n)continue;const i=l.getLastChild(),s=Et(i)?i.getHeaderStyles()&Tt.ROW:Tt.NO_STATUS;for(let e=r;e<n;++e){const e=kt(s);e.append(d()),l.append(e)}}const l=e.getColWidths(),r=e.getColumnCount();if(l&&l.length!==r){let t;if(r<l.length)t=l.slice(0,r);else if(l.length>0){const e=l[l.length-1];t=[...l,...Array(r-l.length).fill(e)]}e.setColWidths(t)}}function Lo(e){if(e.detail<3||!oe(e.target))return!1;const t=de(e.target);if(null===t)return!1;const n=N(t,e=>O(e)&&!e.isInline());return null!==n&&(!!Et(n.getParent())&&(n.select(0),!0))}function Do(){const e=x();if(!v(e))return!1;const t=ho(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=On(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]=_n(e),[n]=mn(t,e,e),o=n.length,l=n[0].length;let r=t.getFirstChild();Lt(r)||zt(175);const i=[];for(let e=0;e<o;e++){0!==e&&(r=r.getNextSibling(),Lt(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){Et(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 Po(e,t=!0){const n=new Kn;let o=!1;const l=(o,l,r)=>{const i=Dn(o,r),s=qn(o,i,e,t,n);n.observers.set(l,[s,i])};return He(Yn(e,n),e.registerCommand(W,()=>null!==e.getRootElement()&&(o=!0,function(e,t){const n=x(),o=me(),l=e.getAndClearNextFocus();if(null!==l&&Mo(A(l.tableKey))){const{tableKey:t,focusCell:o}=l,r=e.observers.get(t);r||zt(335,t);const[i]=r;if(Fn(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(Mo(e)){const t=n.anchor.getNode(),o=e.getFirstChild(),l=uo(t);if(null!==l&&Lt(o)){const t=o.getFirstChild();if(Et(t)&&e.is(N(l,n=>n.is(e)||n.is(t))))return t.selectStart(),!0}}}return Fn(n)&&function(e,t){const n=Bn(e),o=me();if(!t.is(o))return;const l=Wn(t.tableKey),r=H(n),i=r&&ge(r,e.getRootElement());if(r&&i&&i.anchorNode&&i.focusNode){const n=de(i.focusNode),o=n&&!l.isParentOf(n),s=de(i.anchorNode),c=s&&l.isParentOf(s);if(o&&c&&r.rangeCount>0){const n=Te(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=me(),{anchor:o,focus:l}=e,r=o.getNode(),i=l.getNode(),s=uo(r),c=uo(i),a=s?ho(s):null,u=c?ho(c):null,d=e.isBackward(),h=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(d?o.getKey():l.getKey(),d?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(d?l.getKey():o.getKey(),d?l.getChildrenSize():0,\"element\"),M(t)}else if(h){if(!s.is(c))return void M(On(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&&uo(e),{pointerStartCell:o}=l,r=o&&de(o.elem);null!==r&&!r.is(c)&&t&&a.is(ho(t))&&!t.is(c)&&(M(On(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())Vn(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 Io(e,t){e.hasNodes([ko])||zt(255);const{hasNestedTables:n=Ge(!1)}=t??{};return He(e.registerCommand(Kt,e=>function({rows:e,columns:t,includeHeaders:n},o){const l=x()||me();if(!l||!v(l))return!1;if(!o&&ho(l.anchor.getNode()))return!1;const r=Dt(Number(e),Number(t),n);dt(r);const i=r.getFirstDescendant();return a(i)&&i.select(),!0}(e,n.peek()),Le),e.registerCommand(De,(t,o)=>e===o&&function(e,t){const{nodes:n,selection:o}=e;if(!n.some(e=>Mo(e)||ht(e).some(e=>Mo(e.node)))){if(Fn(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=Fn(o),r=v(o);return!!(r&&null!==N(o.anchor.getNode(),e=>Et(e))&&null!==N(o.focus.getNode(),e=>Et(e))||l)&&(1===n.length&&Mo(n[0])?xn(n[0],o):!(r&&t.peek()&&!function(e){return!(!Fn(e)||e.focus.getNode().is(e.anchor.getNode()))||!(!v(e)||!Et(e.anchor.getNode())||e.anchor.getNode().is(e.focus.getNode()))}(o)))}(t,n),Le),e.registerCommand(Be,Do,Pe),e.registerCommand(Ie,Lo,Le),e.registerNodeTransform(ko,Ho),e.registerNodeTransform(Wt,$o),e.registerNodeTransform(Ft,Wo))}const Uo={$accepts:Lt,$packageRun:e=>e.every(Et)?[Ht().splice(0,0,e)]:[],name:\"TableSchema\"},Xo={$accepts:Et,name:\"TableRowSchema\"},Yo=[{$import:(e,t)=>{const n=zo();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),Lt))]},match:/* @__PURE__ */et.tag(\"table\"),name:\"@lexical/table/table\"},{$import:(e,t)=>[Ht(pt.test(t.style.height)?parseFloat(t.style.height):void 0).splice(0,0,ct(e.$importChildren(t),Et))],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 h=e.get(tt),f=h|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!==h&&_.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=d().append(l),t.push(n)):(o(),n=null,t.push(l));return o(),0===t.length&&t.push(d()),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\"}],qo={build:(e,t,n)=>Ze(t),config:{hasCellBackgroundColor:!0,hasCellMerge:!0,hasHorizontalScroll:!0,hasNestedTables:!1,hasStickyScrollbar:!1,hasTabHandler:!0},dependencies:[rt,[it,{rules:Yo}]],name:\"@lexical/table/Table\",nodes:()=>[ko,Wt,Ft],register(e,t,n){const o=n.getOutput();let l=!1;return He(Qe(()=>{const t=o.hasHorizontalScroll.value,n=o.hasStickyScrollbar.value&&t,r=Fo(e);r!==t&&Oo(e,t),r===t&&l===n||e.update(Je),l=n}),Io(e,o),Qe(()=>Po(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 He(()=>{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)?To(r):null;n&&s&&n.parts.scrollable===s.scrollable&&n.parts.scrollbar===s.scrollbar&&n.parts.tableElement===s.tableElement?No(s.scrollable,s.scrollbar):(n&&(n.cleanup(),t.delete(o)),s&&t.set(o,{cleanup:vo(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)})))}},Vo={dependencies:[qo],name:\"@lexical/table/Import\"};export{Cn as $computeTableCellRectBoundary,mn as $computeTableMap,pn as $computeTableMapSkipCellCheck,kt as $createTableCellNode,zo as $createTableNode,Dt as $createTableNodeWithDimensions,Ht as $createTableRowNode,An as $createTableSelection,On as $createTableSelectionFrom,on as $deleteTableColumn,sn as $deleteTableColumnAtSelection,cn as $deleteTableColumn__EXPERIMENTAL,ln as $deleteTableRowAtSelection,rn as $deleteTableRow__EXPERIMENTAL,uo as $findCellNode,ho as $findTableNode,Eo as $getElementForTableNode,_n as $getNodeTriplet,En as $getTableAndElementByKey,Bt as $getTableCellNodeFromLexicalNode,wn as $getTableCellNodeRect,Xt as $getTableColumnIndexFromTableCellNode,It as $getTableNodeFromLexicalNodeOrThrow,Ut as $getTableRowIndexFromTableCellNode,Pt 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,Fo as $isScrollableTablesActive,Sn as $isSimpleTable,Ao as $isStickyScrollbarActive,Et as $isTableCellNode,Mo as $isTableNode,Lt as $isTableRowNode,Fn as $isTableSelection,dn as $mergeCells,yn as $moveTableColumn,bn as $moveTableRow,qt as $removeTableRowAtIndex,Nn as $setTableColumnIsHeader,vn as $setTableRowIsHeader,fn as $unmergeCell,gn as $unmergeCellNode,Kt as INSERT_TABLE_COMMAND,Tt as TableCellHeaderStates,Ft as TableCellNode,qo as TableExtension,Vo as TableImportExtension,Yo as TableImportRules,ko as TableNode,zn as TableObserver,Wt as TableRowNode,Xo as TableRowSchema,Uo as TableSchema,qn as applyTableHandlers,Jn as getDOMCellFromTarget,Dn as getTableElement,jn as getTableObserverFromTableElement,Bo as registerTableCellUnmergeTransform,Io as registerTablePlugin,Po as registerTableSelectionObserver,Oo as setScrollableTablesActive};\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","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","/* 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.5.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","// Generated by `scripts/generate-shiki-metadata.js`. DO NOT EDIT.\n\n/**\n * Version of this package, used to resolve the prebuilt Shiki engine chunk from a CDN.\n */\nexport const UI_VERSION = '0.80.2';\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 { $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.\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 {\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 { 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 { CodeNode } from '@lexical/code-core';\n * @import { LexicalEditor, LexicalNode, NodeKey } from 'lexical';\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 * 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 * In-flight loads, keyed by what is being loaded.\n * @type {Map<string, { promise: Promise<void>, targets: Map<NodeKey, LexicalEditor> }>}\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 refresh\n * each waiting code node exactly once when it completes.\n *\n * The transform fires on every keystroke, so without this a burst of typing during a load would\n * start a download per keystroke and then flood the editor with one update each. That storm is\n * enough to starve the final re-highlight, leaving a block tokenized as of an earlier keystroke.\n * @param {string} key Cache key identifying the load.\n * @param {() => Promise<void>} run Work to perform on the first call.\n * @param {LexicalEditor} [editor] Editor instance to refresh once the load completes.\n * @param {NodeKey} [codeNodeKey] Key of the code node to refresh.\n * @returns {Promise<void>} Promise resolving when the load has completed.\n */\nconst loadOnce = (key, run, editor, codeNodeKey) => {\n  let entry = pendingLoads.get(key);\n\n  if (!entry) {\n    /** @type {Map<NodeKey, LexicalEditor>} */\n    const targets = new Map();\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      targets.forEach((target, nodeKey) => refreshCodeNode(target, nodeKey));\n    })();\n\n    entry = { promise, targets };\n    pendingLoads.set(key, entry);\n  }\n\n  if (editor && codeNodeKey) {\n    entry.targets.set(codeNodeKey, editor);\n  }\n\n  return entry.promise;\n};\n\n/**\n * Load the syntax highlighting engine, then refresh the given code node.\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 `refreshCodeNode()`, the same mechanism upstream already uses for grammars.\n * @param {LexicalEditor} [editor] Editor instance to refresh once the engine is ready.\n * @param {NodeKey} [codeNodeKey] Key of the code node to refresh.\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 = (editor, codeNodeKey) => {\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    editor,\n    codeNodeKey,\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 refresh the given code node. The\n * configured 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 {LexicalEditor} [editor] Editor instance to refresh once the payload is loaded.\n * @param {NodeKey} [codeNodeKey] Key of the code node to refresh.\n * @returns {Promise<void>} Promise resolving when the payload is loaded.\n */\nconst loadAsset = (kind, id, editor, codeNodeKey) => {\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    editor,\n    codeNodeKey,\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 refresh the given code node.\n * @param {string} language Language identifier, like `scss` or `diff-js`.\n * @param {LexicalEditor} [editor] Editor instance to refresh once the grammar is ready.\n * @param {NodeKey} [codeNodeKey] Key of the code node to refresh.\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, editor, codeNodeKey) => {\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, editor, codeNodeKey);\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 refresh the given code node.\n * @param {string} theme Theme identifier, like `github-light`.\n * @param {LexicalEditor} [editor] Editor instance to refresh once the theme is ready.\n * @param {NodeKey} [codeNodeKey] Key of the code node to refresh.\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, editor, codeNodeKey) => {\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, editor, codeNodeKey);\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 = engine.stringifyTokenStyle(\n        token.htmlStyle || engine.getTokenStyleObject(token),\n      );\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 diffedLanguage = getDiffedLanguage(language);\n\n  const { tokens } = highlighter.codeToTokens(codeNode.getTextContent(), {\n    lang: diffedLanguage ?? language,\n    theme: codeNode.getTheme(),\n  });\n\n  return mapTokensToLexicalStructure(tokens, !!diffedLanguage);\n};\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","import { CodeHighlightNode, CodeNode, $createCodeNode as createCodeNode } 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  $createTextNode as createTextNode,\n  $getEditor as getEditor,\n  $isParagraphNode as isParagraphNode,\n  isDOMTextNode,\n  isHTMLElement,\n  isInlineDomNode,\n  ParagraphNode,\n  TabNode,\n  TextNode,\n} from 'lexical';\nimport { isPlainLanguage } from './shiki/facade.js';\n\n/**\n * @import {\n * DOMConversion,\n * DOMConversionMap,\n * DOMConversionOutput,\n * DOMExportOutput,\n * DOMExportOutputMap,\n * ElementNode,\n * LexicalEditor,\n * LexicalNode,\n * } from 'lexical';\n * @import { TextEditorComponent } from '../../typedefs.js';\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.\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 * Text formats and their HTML tags, from the innermost to the outermost.\n * @type {[import('lexical').TextFormatType, string][]}\n */\nconst 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/**\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 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 * Remove the attributes not listed in {@link ALLOWED_ATTRIBUTES} from the given element.\n * @param {Element} element Element.\n */\nconst removeExtraAttributes = (element) => {\n  const allowedAttributes = ALLOWED_ATTRIBUTES[element.localName] ?? [];\n\n  [...element.attributes].forEach(({ name }) => {\n    if (!allowedAttributes.includes(name)) {\n      element.removeAttribute(name);\n    }\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.\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  if (parent instanceof TableCellNode && parent.getChildrenSize() === 1) {\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  return exportElementNode(editor, node);\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 * 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, exportElementNode],\n    [ListItemNode, exportElementNode],\n    [LinkNode, exportElementNode],\n    [HorizontalRuleNode, exportElementNode],\n    [CodeNode, exportCodeNode],\n    [TableNode, exportTableNode],\n  ]),\n);\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 * 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 */\nconst 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 */\nconst 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 */\nconst 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/**\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 * 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 */\nconst 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 * 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/**\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) || componentOnlyTagNames.has(tagName))\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/**\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 * Split multiline formatting into separate lines to prevent Markdown parsing issues.\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  value\n    // The surrounding whitespace is checked with lookarounds rather than matched with `\\s+`, which\n    // would take quadratic time on a long run of whitespace not followed by a formatting marker\n    .replace(/(?<=\\s)_([^_\\n]+?)\\n([^_\\n]+?)_(?=\\s)/g, '_$1_\\n_$2_')\n    .replace(/(?<=\\s)\\*\\*([^*\\n]+?)\\n([^*\\n]+?)\\*\\*(?=\\s)/g, '**$1**\\n**$2**')\n    .replace(/(?<=\\s)~~([^~\\n]+?)\\n([^~\\n]+?)~~(?=\\s)/g, '~~$1~~\\n~~$2~~')\n    .replace(/(?<=\\s)`([^`\\n]+?)\\n([^`\\n]+?)`(?=\\s)/g, '`$1`\\n`$2`');\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 */\nconst mapLinesOutsideCodeBlocks = (value, callback) => {\n  /**\n   * Opening fence of the code block being processed, like ```` ``` ````, or an empty string when\n   * outside a code block.\n   */\n  let openingFence = '';\n\n  return value\n    .split('\\n')\n    .map((line) => {\n      // Like Lexical's `CODE_START_REGEX`, allow an indented fence\n      const fence = line.match(/^[ \\t]*(`{3,}|~{3,})/)?.[1];\n\n      if (!openingFence) {\n        if (fence) {\n          openingFence = fence;\n          return line;\n        }\n\n        return callback(line);\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] === openingFence[0] &&\n        fence.length >= openingFence.length &&\n        !line.trim().slice(fence.length)\n      ) {\n        openingFence = '';\n      }\n\n      return line;\n    })\n    .join('\\n');\n};\n\n/**\n * Increase list indentation levels to prevent Markdown parsing issues.\n * Slate uses 2 spaces per indentation level, whereas Lexical uses 4 spaces.\n * This function doubles the indentation to match Lexical's expectations.\n * @param {string} value Markdown string to process.\n * @returns {string} Processed Markdown string.\n * @see https://github.com/sveltia/sveltia-cms/issues/549\n */\nexport const increaseListIndentation = (value) => {\n  if (!value.match(/^\\s{2}(?:-|\\+|\\*|\\d+\\.)\\s/m)) {\n    return value;\n  }\n\n  return mapLinesOutsideCodeBlocks(value, (line) =>\n    line.replace(/^(\\s+)(-|\\+|\\*|\\d+\\.)/, (_match, p1, p2) => `${' '.repeat(p1.length * 2)}${p2}`),\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 * 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  getHighlightNodes,\n  isCodeLanguageLoaded,\n  isCodeThemeLoaded,\n  isEngineLoaded,\n  isEngineUnavailable,\n  isPlainLanguage,\n  loadCodeLanguage,\n  loadCodeTheme,\n  loadEngine,\n} from './facade.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(editor, nodeKey);\n    inFlight = true;\n  } else {\n    // Dynamic load of themes\n    if (!isCodeThemeLoaded(theme)) {\n      loadCodeTheme(theme, 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, 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","import { $isLineBreakNode as isLineBreakNode, $isTextNode as isTextNode } from 'lexical';\n\n/**\n * @import { TextMatchTransformer } from '@lexical/markdown';\n * @import { ElementNode, LexicalNode, TextNode } from 'lexical';\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\n    // ATX heading, bullet list item, blockquote, setext heading underline or thematic break\n    .replace(/^( {0,3})(#{1,6}(?=[ \\t]|$)|[-+](?=[ \\t]|$)|>|=+[ \\t]*$|-{2,}[ \\t]*$)/, '$1\\\\$2')\n    // Ordered list item, whose number can’t be escaped, unlike the delimiter after it\n    .replace(/^( {0,3}\\d{1,9})([.)])(?=[ \\t]|$)/, '$1\\\\$2');\n\n/**\n * Export-only transformer that escapes the Markdown block syntax at the start of a block or of a\n * line after a line break. Without it, a paragraph typed as `## Hours` with the Markdown shortcuts\n * turned off, pasted as text, or imported from the escaped `\\## Hours` would be exported as is and\n * become a heading the next time the Markdown is read.\n * @type {TextMatchTransformer}\n */\nexport const BLOCK_SYNTAX_ESCAPE = {\n  dependencies: [],\n  /**\n   * Export a text node at the start of a line, escaping the block syntax it starts with.\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)) {\n      return null;\n    }\n\n    const parent = node.getParent();\n    const previous = node.getPreviousSibling();\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\n    if (!parent || parent.isInline() || ['code', 'heading'].includes(parent.getType())) {\n      return null;\n    }\n\n    if (previous && !isLineBreakNode(previous)) {\n      return null;\n    }\n\n    // A formatted node starts with its own syntax, such as `**`, which is left as is\n    return escapeBlockSyntax(exportFormat(node, node.getTextContent()));\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\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 * @type {ElementTransformer}\n */\nexport const HR = {\n  dependencies: [HorizontalRuleNode],\n  export: (node) => (isHorizontalRuleNode(node) ? '***' : 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    line.selectNext();\n  },\n  type: 'element',\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  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\n/**\n * @import { ElementTransformer } from '@lexical/markdown';\n */\n\nconst TABLE_ROW_REG_EXP = /^(?:\\|)(.+)(?:\\|)\\s?$/;\nconst TABLE_ROW_DIVIDER_REG_EXP = /^(\\| ?:?-*:? ?)+\\|\\s?$/;\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 * @returns {TableCellNode}\n */\nconst createTableCell = (textContent) => {\n  textContent = textContent.replace(/\\\\n/g, '\\n');\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 * @returns {TableCellNode[] | null}\n */\nexport const mapToTableCells = (textContent) => {\n  const [, match] = textContent.match(TABLE_ROW_REG_EXP) ?? [];\n\n  if (!match) {\n    return null;\n  }\n\n  return match.split('|').map((text) => createTableCell(text));\n};\n\n/**\n * @type {ElementTransformer}\n */\nexport const TABLE = {\n  dependencies: [TableNode, TableRowNode, TableCellNode],\n  export: (node) => {\n    if (!isTableNode(node)) {\n      return null;\n    }\n\n    /** @type {string[]} */\n    const output = [];\n\n    node.getChildren().forEach((row) => {\n      /** @type {string[]} */\n      const rowOutput = [];\n\n      if (!isTableRowNode(row)) {\n        return;\n      }\n\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(convertToMarkdownString(TRANSFORMERS, cell).replace(/\\n/g, '\\\\n').trim());\n\n          if (cell.__headerState === TableCellHeaderStates.ROW) {\n            isHeaderRow = true;\n          }\n        }\n      });\n\n      output.push(`| ${rowOutput.join(' | ')} |`);\n\n      if (isHeaderRow) {\n        output.push(`| ${rowOutput.map(() => '---').join(' | ')} |`);\n      }\n    });\n\n    return output.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      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      // Add header state to row cells\n      lastRow.getChildren().forEach((cell) => {\n        if (!isTableCellNode(cell)) {\n          return;\n        }\n\n        cell.setHeaderStyles(TableCellHeaderStates.ROW, TableCellHeaderStates.ROW);\n      });\n\n      // Remove line\n      parentNode.remove();\n\n      return;\n    }\n\n    const matchCells = mapToTableCells(textContent);\n\n    if (!matchCells) {\n      return;\n    }\n\n    const rows = [matchCells];\n    let sibling = parentNode.getPreviousSibling();\n    let maxCells = matchCells.length;\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());\n\n      if (!cells) {\n        break;\n      }\n\n      maxCells = Math.max(maxCells, cells.length);\n      rows.unshift(cells);\n\n      const previousSibling = sibling.getPreviousSibling();\n\n      sibling.remove();\n      sibling = previousSibling;\n    }\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 < maxCells; i += 1) {\n        tableRow.append(i < cells.length ? cells[i] : createTableCell(''));\n      }\n    });\n\n    const previousSibling = parentNode.getPreviousSibling();\n\n    if (isTableNode(previousSibling) && getTableColumnsSize(previousSibling) === maxCells) {\n      previousSibling.append(...table.getChildren());\n      parentNode.remove();\n    } else {\n      parentNode.replace(table);\n    }\n\n    table.selectEnd();\n  },\n  type: 'element',\n};\n","import {\n  CodeExtension,\n  CodeHighlightNode,\n  CodeNode,\n  $createCodeNode as createCodeNode,\n  $isCodeHighlightNode as isCodeHighlightNode,\n  $isCodeNode as isCodeNode,\n} from '@lexical/code-core';\nimport { registerDragonSupport } from '@lexical/dragon';\nimport { buildEditorFromExtensions, HorizontalRuleNode } from '@lexical/extension';\nimport { createEmptyHistoryState, registerHistory } from '@lexical/history';\nimport { $generateNodesFromDOM as generateNodesFromDOM } from '@lexical/html';\nimport {\n  $isLinkNode as isLinkNode,\n  LinkNode,\n  TOGGLE_LINK_COMMAND,\n  $toggleLink as toggleLink,\n} from '@lexical/link';\nimport {\n  $handleListInsertParagraph as handleListInsertParagraph,\n  INSERT_ORDERED_LIST_COMMAND,\n  INSERT_UNORDERED_LIST_COMMAND,\n  $insertList as insertList,\n  $isListItemNode as isListItemNode,\n  $isListNode as isListNode,\n  ListNode,\n} from '@lexical/list';\nimport {\n  CODE,\n  $convertFromMarkdownString as convertFromMarkdownString,\n  $convertToMarkdownString as convertToMarkdownString,\n  registerMarkdownShortcuts,\n} from '@lexical/markdown';\nimport {\n  $isHeadingNode as isHeadingNode,\n  $isQuoteNode as isQuoteNode,\n  registerRichText,\n} from '@lexical/rich-text';\nimport { TableCellNode, TableNode, TableRowNode } from '@lexical/table';\nimport {\n  $getNearestNodeOfType as getNearestNodeOfType,\n  objectKlassEquals,\n  $unwrapNode as unwrapNode,\n} from '@lexical/utils';\nimport { sleep } from '@sveltia/utils/misc';\nimport { isURL } from '@sveltia/utils/string';\nimport {\n  COMMAND_PRIORITY_LOW,\n  COMMAND_PRIORITY_NORMAL,\n  createEditor,\n  defineExtension,\n  DELETE_CHARACTER_COMMAND,\n  $createParagraphNode as createParagraphNode,\n  $createTextNode as createTextNode,\n  ElementNode,\n  $getNearestNodeFromDOMNode as getNearestNodeFromDOMNode,\n  $getRoot as getRoot,\n  $getSelection as getSelection,\n  HISTORY_MERGE_TAG,\n  INDENT_CONTENT_COMMAND,\n  INSERT_PARAGRAPH_COMMAND,\n  KEY_ENTER_COMMAND,\n  $insertNodes as insertNodes,\n  $isDecoratorNode as isDecoratorNode,\n  $isElementNode as isElementNode,\n  $isRangeSelection as isRangeSelection,\n  $isTextNode as isTextNode,\n  OUTDENT_CONTENT_COMMAND,\n  PASTE_COMMAND,\n  RootNode,\n} from 'lexical';\nimport {\n  BLOCK_BUTTON_TYPES,\n  DISABLED_MARKDOWN_TAGS,\n  EDITOR_THEME,\n  IMPORT_UPDATE_TAG,\n  NODE_MAP,\n  TEXT_FORMAT_BUTTON_TYPES,\n  TRANSFORMER_MAP,\n} from './constants.js';\nimport {\n  editorComponents,\n  exportHtml,\n  findUnsupportedNode,\n  getCodeLanguage,\n  HTML_CODE_IMPORT_MAP,\n  HTML_EXPORT_MAP,\n  HTML_IMPORT_MAP,\n} from './html.js';\nimport {\n  increaseListIndentation,\n  padBlankBlockquoteLines,\n  splitMultilineFormatting,\n  trimBlankBlockquoteLines,\n} from './markdown.js';\nimport {\n  isPlainLanguage,\n  loadCodeLanguage,\n  loadCodeTheme,\n  loadEngine,\n  normalizeCodeLanguage,\n} from './shiki/facade.js';\nimport { registerCodeHighlighting, shikiTokenizer } from './shiki/highlighter.js';\nimport { getCodeTheme, observeCodeTheme } from './shiki/theme.js';\nimport { BLOCK_SYNTAX_ESCAPE } from './transformers/block-escape.js';\nimport { HR } from './transformers/hr.js';\nimport { TABLE } from './transformers/table.js';\n\n/**\n * @import { LexicalEditor, LexicalNode } from 'lexical';\n * @import { ListType } from '@lexical/list';\n * @import { Transformer } from '@lexical/markdown';\n * @import {\n * TextEditorBlockType,\n * TextEditorComponent,\n * TextEditorConfig,\n * TextEditorInlineType,\n * TextEditorNodeType,\n * TextEditorValueFormat,\n * TextEditorSelectionState,\n * } from '../../typedefs.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} dispose Remove all registered Lexical listeners.\n */\n\n/**\n * Maximum number of entries in the undo stack.\n */\nconst HISTORY_MAX_DEPTH = 200;\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 * 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 * 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 */\nconst 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    };\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        return parent.getListType() === 'bullet' ? 'bulleted-list' : 'numbered-list';\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  };\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    // Last, so a 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 unnecessary backslash for underscore and backslash characters\n      // @see https://github.com/sveltia/sveltia-cms/issues/430\n      // @see https://github.com/sveltia/sveltia-cms/issues/512\n      .replace(/\\\\([_\\\\])/g, '$1')\n      // Replace encoded spaces with regular spaces. The HTML entity can appear with a\n      // combination of bold and italic text\n      // @see https://github.com/sveltia/sveltia-cms/issues/511\n      // @see https://github.com/sveltia/sveltia-cms/issues/534\n      .replace(/&#32;/g, ' ')\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 * Listen to changes made on the editor and trigger the Update event.\n * @internal\n * @param {LexicalEditor} editor Editor instance.\n * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.\n * @param {string} [cachedValue] Value from a previous call, to be reused instead of converting the\n * whole document again when only the selection has changed.\n * @param {TextEditorValueFormat} [format] Value format.\n * @returns {string} Markdown or HTML value.\n */\nexport const onEditorUpdate = (editor, enabledTransformers, cachedValue, format = 'markdown') => {\n  const value =\n    cachedValue ?? (format === 'html' ? exportHtml(editor) : exportMarkdown(enabledTransformers));\n\n  editor.getRootElement()?.dispatchEvent(\n    new CustomEvent('Update', {\n      detail: {\n        value,\n        selection: getSelectionTypes(),\n      },\n    }),\n  );\n\n  return value;\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 = onEditorUpdate(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 * 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 */\nconst mergeUnregisters = (...unregisters) => {\n  const handlers = unregisters.filter((unregister) => typeof unregister === 'function');\n\n  return () => {\n    handlers.forEach((unregister) => unregister());\n  };\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 */\nconst 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 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 */\nconst 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        // Ignore an unsafe URL rather than linking to it\n        if (typeof payload === 'string' && !isSafeLinkURL(payload)) {\n          return true;\n        }\n\n        toggleLink(typeof payload === 'string' ? payload : null);\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 * List buttons, along with the command to insert the list and its type.\n * @type {[TextEditorBlockType, typeof INSERT_UNORDERED_LIST_COMMAND, ListType][]}\n */\nconst LIST_COMMANDS = [\n  ['bulleted-list', INSERT_UNORDERED_LIST_COMMAND, 'bullet'],\n  ['numbered-list', INSERT_ORDERED_LIST_COMMAND, 'number'],\n];\n\n/**\n * Register the commands for the enabled list buttons.\n * @param {LexicalEditor} editor Editor instance.\n * @param {TextEditorConfig['enabledButtons']} enabledButtons Enabled buttons.\n * @returns {() => void} Cleanup handler.\n */\nconst registerListCommands = (editor, enabledButtons = []) => {\n  const enabledLists = LIST_COMMANDS.filter(([button]) => enabledButtons.includes(button));\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  );\n};\n\n/**\n * Register an update listener that triggers the Update event with the Markdown or HTML value,\n * debounced so only the latest update in a burst triggers it.\n * @param {LexicalEditor} editor Editor instance.\n * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.\n * @param {TextEditorValueFormat} format Value format.\n * @returns {() => void} Cleanup handler.\n */\nconst registerUpdateEvent = (editor, enabledTransformers, format) => {\n  /** Incremented on every update, so only the latest one in a burst triggers the Update event. */\n  let updateCount = 0;\n  /** Whether the content has changed since the Update event was last triggered. */\n  let contentChanged = true;\n  /** @type {string | undefined} */\n  let lastValue = undefined;\n  let disposed = false;\n\n  return 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\n      const currentCount = updateCount;\n\n      (async () => {\n        await sleep(100);\n\n        // Skip if a newer update has been made in the meantime, or the editor has been disposed\n        if (currentCount !== updateCount || disposed) {\n          return;\n        }\n\n        editor.update(() => {\n          lastValue = onEditorUpdate(\n            editor,\n            enabledTransformers,\n            contentChanged ? undefined : lastValue,\n            format,\n          );\n          contentChanged = false;\n        });\n      })();\n    }),\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 */\nconst 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/**\n * Initialize the Lexical editor.\n * @param {TextEditorConfig} config Editor configuration.\n * @returns {InitEditorResult} Editor instance and cleanup.\n */\nexport const initEditor = ({\n  enabledButtons = [],\n  components = [],\n  useMarkdownShortcuts,\n  isCodeEditor = false,\n  defaultLanguage = 'plain',\n  format = 'markdown',\n}) => {\n  const hasCodeBlock = enabledButtons.includes('code-block') || isCodeEditor;\n\n  const editorExtension = defineExtension({\n    name: '@sveltia/ui/editor',\n    namespace: 'editor',\n    // `CodeNode` expects the editor to be built with `CodeExtension`, which also registers the\n    // `CodeNode` and `CodeHighlightNode` nodes\n    dependencies: hasCodeBlock ? [CodeExtension] : [],\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      ...new Set(\n        Object.entries(NODE_MAP)\n          .filter(([button]) => enabledButtons.includes(/** @type {TextEditorNodeType} */ (button)))\n          .flatMap(([, nodes]) => nodes),\n      ),\n      ...(isCodeEditor\n        ? [CodeNode, CodeHighlightNode]\n        : // We haven’t implemented buttons for horizontal rules and tables yet, but we still want\n          // to support them in Markdown, so always include them in the node list\n          [HorizontalRuleNode, TableNode, TableCellNode, TableRowNode]),\n    ],\n    theme: EDITOR_THEME,\n    // Export clean HTML without the attributes and elements only meant for the editor, and import\n    // code blocks with their language. The export map also applies to copying\n    html:\n      format === 'html'\n        ? {\n            export: HTML_EXPORT_MAP,\n            import: { ...HTML_IMPORT_MAP, ...(hasCodeBlock ? HTML_CODE_IMPORT_MAP : {}) },\n          }\n        : 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  /** @type {Transformer[]} */\n  const enabledTransformers = [\n    ...components.map(({ transformer }) => transformer),\n    ...new Set(\n      Object.entries(TRANSFORMER_MAP)\n        .filter(([button]) => enabledButtons.includes(/** @type {TextEditorNodeType} */ (button)))\n        .flatMap(([, transformers]) => transformers),\n    ),\n    ...(isCodeEditor\n      ? [CODE]\n      : // See the comment above for why we always include horizontal rules and tables\n        [HR, TABLE]),\n  ];\n\n  const editor = buildEditorFromExtensions(editorExtension);\n\n  // Let the HTML import tell the elements the components import\n  editorComponents.set(editor, components);\n\n  // The order matters, as listeners with the same priority are called in the registration order\n  const unregister = 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    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    enabledButtons.includes('link') ? registerLinkCommands(editor) : undefined,\n    registerListCommands(editor, enabledButtons),\n    registerUpdateEvent(editor, enabledTransformers, format),\n    registerTabIndentation(editor),\n  );\n\n  return {\n    editor,\n    enabledTransformers,\n    /**\n     * Remove all registered Lexical listeners.\n     */\n    dispose: () => {\n      unregister();\n      editor.dispose();\n    },\n  };\n};\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\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  importValue(editor, {\n    languages: [...value.matchAll(/^```(?<lang>.+?)\\n/gm)].map(\n      ({ groups: { lang = 'plain' } = {} }) => lang,\n    ),\n    /**\n     * Import the Markdown.\n     */\n    $import: () => {\n      convertFromMarkdownString(\n        // Split multiline formatting into separate lines to prevent Markdown parsing issues, then\n        // increase list indentation levels to prevent Markdown parsing issues, and pad blank\n        // blockquote lines so they are not imported as literal `>` text\n        padBlankBlockquoteLines(increaseListIndentation(splitMultilineFormatting(value))),\n        enabledTransformers,\n      );\n    },\n    /**\n     * Export the content as Markdown.\n     * @returns {string} Markdown.\n     */\n    $export: () => exportMarkdown(enabledTransformers),\n    formatName: 'Markdown',\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/**\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","<script>\n  import { $getRoot as getRoot, HISTORY_MERGE_TAG } from 'lexical';\n  import { getContext, onMount } from 'svelte';\n  import { IMPORT_UPDATE_TAG } from './constants.js';\n  import { handleEditorMouseDown, initEditor } from './core.js';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { TextEditorStore } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [class] The `class` attribute on the wrapper element.\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   * @property {boolean} [hidden] Whether to hide the widget.\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   * @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 {Snippet} [children] Primary slot content.\n   */\n\n  /**\n   * @type {Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    class: className,\n    dir = undefined,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    invalid = false,\n    children,\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 {@link value} and other state variables whenever the editor content is updated.\n   * @param {Event} event `Update` custom event.\n   */\n  const onUpdate = (event) => {\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    const { value: exportedValue, selection } = /** @type {CustomEvent} */ (event).detail;\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      // Temporarily disable rich text to prevent unnecessary Markdown conversion that resets\n      // Lexical nodes and selection, then restore the state\n      editorStore.useRichText = false;\n      editorStore.inputValue = newValue;\n      editorStore.useRichText = true;\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  onMount(() => {\n    const { editor, enabledTransformers, dispose } = initEditor(editorStore.config);\n\n    editorStore.editor = editor;\n    editorStore.enabledTransformers = enabledTransformers;\n\n    lexicalRoot?.addEventListener('Update', onUpdate);\n    lexicalRoot?.addEventListener('click', onClick);\n    lexicalRoot?.addEventListener('mousedown', onMouseDown);\n\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    const unregisterUpdateListener = editor.registerUpdateListener(\n      ({ 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    );\n\n    return () => {\n      unregisterUpdateListener();\n      lexicalRoot?.removeEventListener('Update', onUpdate);\n      lexicalRoot?.removeEventListener('click', onClick);\n      lexicalRoot?.removeEventListener('mousedown', onMouseDown);\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=\"true\"\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: hidden;\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}\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-visible {\n  outline: 0;\n}\n.lexical-root[aria-invalid=true] {\n  border-color: var(--sui-error-border-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(.strikethrough) {\n  text-decoration: line-through;\n}\n.lexical-root :global(li.nested) {\n  list-style-type: 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(hr) {\n  margin: var(--sui-paragraph-margin) 0;\n  border: none;\n  padding: 0;\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 { convertHtmlToLexical, convertMarkdownToLexical } from './core.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 * 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\n  /** @type {TextEditorConfig} */\n  let config = $state({\n    modes: [],\n    enabledButtons: [],\n    components: [],\n    useMarkdownShortcuts: true,\n    isCodeEditor: false,\n    useEmojiAutocomplete: false,\n  });\n\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 {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  return {\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 = newValue;\n      useRichText = newValue.modes[0] === 'rich-text' || newValue.isCodeEditor;\n    },\n    get inputValue() {\n      return inputValue;\n    },\n    set inputValue(newValue) {\n      const hasChange = inputValue !== newValue;\n\n      if (hasChange) {\n        inputValue = newValue;\n      }\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 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    /* eslint-enable jsdoc/require-jsdoc */\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, loadCodeHighlighter } from '../core.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 { Snippet } from 'svelte';\n   */\n\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.\n   * @property {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\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   * @property {Snippet} [children] Primary slot content.\n   */\n\n  /**\n   * @type {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 Toolbar from '../../toolbar/toolbar.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\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</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <Toolbar {...restProps} {disabled}>\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: 0;\n  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(.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","<script>\n  import { _ } from '@sveltia/i18n';\n  import CodeLanguageSwitcher from './code-language-switcher.svelte';\n  import ToolbarWrapper from './toolbar-wrapper.svelte';\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [hidden] Whether to hide the widget.\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</script>\n\n<ToolbarWrapper disabled={disabled || readonly} ariaLabel={_('_sui.text_editor.code_editor')}>\n  <CodeLanguageSwitcher disabled={disabled || readonly} />\n</ToolbarWrapper>\n","<!--\n  @component\n  A code 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 Toast from '../toast/toast.svelte';\n  import { parseCodeBlock, toCodeBlock } from './code-editor.js';\n  import LexicalRoot from './lexical-root.svelte';\n  import { createEditorStore } from './store.svelte.js';\n  import CodeEditorToolbar from './toolbar/code-editor-toolbar.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\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   * @property {boolean} [flex] Make the text input container flexible.\n   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [hidden] Whether to hide the widget.\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   * @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] The `aria-label` attribute on the editable text box. Either\n   * this or `ariaLabelledby` is required for the editor to have an accessible name.\n   * @property {string} [ariaLabelledby] The `aria-labelledby` attribute on the editable text box.\n   * @property {string} [ariaDescribedby] The `aria-describedby` attribute on the editable text\n   * box.\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    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    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  $effect(() => {\n    pending = 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    pending = 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    void code;\n    void lang;\n\n    untrack(() => {\n      editorStore.inputValue = toCodeBlock(lang, code);\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    void editorStore.inputValue;\n\n    untrack(() => {\n      const { lang: _lang, code: _code } = parseCodeBlock(editorStore.inputValue);\n\n      if (lang !== _lang) {\n        lang = _lang;\n      }\n\n      if (code !== _code) {\n        code = _code;\n      }\n    });\n  });\n</script>\n\n<div {...restProps} role=\"none\" class=\"sui code-editor\" class:flex {hidden}>\n  {#if showLanguageSwitcher}\n    <CodeEditorToolbar {disabled} {readonly} />\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  border-radius: var(--sui-textbox-border-radius);\n  width: calc(100% - var(--sui-focus-ring-width) * 2);\n  transition: all 200ms;\n}\n.code-editor:focus-within {\n  outline: var(--sui-focus-ring-width) solid var(--sui-focus-ring-color);\n}\n.code-editor.flex:not([hidden]) {\n  display: block;\n}</style>\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 EmojiAutocomplete from './emoji-autocomplete.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { CommonEventHandlers, HighlightedToken, InputEventHandlers } 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   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [hidden] Whether to hide the widget.\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   * @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 {Snippet} [children] Primary slot content.\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    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    children,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\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.by(() => {\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('') === cloneValue ? tokens : undefined;\n  });\n  /** A reference to the clone element. */\n  let cloneElement = $state();\n\n  $effect(() => {\n    // Keep the highlighted text scrolled along with the `<textarea>`. It never scrolls when it’s\n    // auto-resized\n    if (!element || !cloneElement || autoResize) {\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  {hidden}\n>\n  <textarea\n    bind:this={element}\n    {...restProps}\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\n:is(textarea, .clone) {\n  grid-area: 1/1/2/2;\n  display: block;\n  margin: 0;\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  width: 100%;\n  min-height: 8em;\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  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  letter-spacing: var(--sui-textbox-letter-spacing, normal);\n  word-spacing: var(--sui-word-spacing-normal, normal);\n  transition: all 200ms;\n}\n:is(textarea, .clone).resizing {\n  transition-duration: 0ms;\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):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}\ntextarea[aria-invalid=true] {\n  border-color: var(--sui-error-border-color);\n}\n\n.clone {\n  overflow: hidden;\n  visibility: hidden;\n}\n.clone:not(.auto-resize) {\n  position: absolute;\n  inset: 0;\n  min-height: 0;\n  scroll-behavior: auto;\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\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 {Array<() => void>} Cleanup handlers.\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 [];\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 [\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 unregisters = registerCommands();\n\n    return () => {\n      unregisters.forEach((unregister) => 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  @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 { createDOMRange } from '@lexical/selection';\n  import { $findMatchingParent as findMatchingParent } from '@lexical/utils';\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 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 { focusEditor, isSafeLinkURL } from './core.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 } | 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  /**\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   * Find the link that contains the whole selection. This must be called within an editor state\n   * read.\n   * @returns {import('@lexical/link').LinkNode | null} Link, if any.\n   */\n  const findLink = () => {\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 {import('@lexical/link').LinkNode} */ (link)\n      : null;\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    /** @type {DOMRect | undefined} */\n    let rect;\n\n    if (editTarget && 'selection' in editTarget) {\n      const { selection } = editTarget;\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    } else {\n      const key = editTarget && 'linkKey' in editTarget ? editTarget.linkKey : currentLink?.key;\n\n      rect = key ? editor.getElementByKey(key)?.getBoundingClientRect() : undefined;\n    }\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  /**\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   */\n  const startEditing = async (target, initialURL) => {\n    editTarget = target;\n    url = initialURL;\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  };\n\n  /**\n   * Move the focus back to the editor, where the selection is restored, after the popup is done.\n   */\n  const refocusEditor = async () => {\n    // The editor is there for as long as the popup can be shown\n    /* v8 ignore else */\n    if (editorStore.editor) {\n      await focusEditor(editorStore.editor);\n    }\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\n    editorStore.editor?.getEditorState().read(() => {\n      const link = findLink();\n\n      if (link) {\n        target = { linkKey: link.getKey() };\n        initialURL = link.getURL();\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);\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    // 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      });\n    } else {\n      editor.update(() => {\n        setSelection(target.selection.clone());\n      });\n      editor.dispatchCommand(TOGGLE_LINK_COMMAND, newURL);\n    }\n\n    await refocusEditor();\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();\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();\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 = findLink();\n\n        currentLink = link ? { key: link.getKey(), url: link.getURL() } : 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 () => {\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    window.addEventListener('scroll', reposition, { capture: true, passive: true });\n    window.addEventListener('resize', reposition, { passive: true });\n    document.addEventListener('focusin', onFocusIn);\n    document.addEventListener('focusout', onFocusOut);\n\n    return () => {\n      window.removeEventListener('scroll', reposition, { capture: true });\n      window.removeEventListener('resize', reposition);\n      document.removeEventListener('focusin', onFocusIn);\n      document.removeEventListener('focusout', onFocusOut);\n    };\n  });\n</script>\n\n{#if open && position}\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 is pressed, which would otherwise\n      // move it to the page, hiding the popup or blurring the URL field\n      if (event.target === event.currentTarget) {\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      <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=\"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({ linkKey: currentLink.key }, currentLink.url);\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  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: 4px;\n  width: min(400px, 100vw - 16px);\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  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.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 * 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} and {@link insertComponent}, everything here is pure: a function\n * takes the current value and selection, and returns the edit to apply.\n */\n\nimport { isMac, matchesShortcuts } from '@sveltia/utils/events';\nimport { getComponentMarkdown } from './core.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.\n * @type {Record<TextEditorFormatType, 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.\n */\nconst BLOCK_PREFIX_REGEX = /^(?:#{1,6}[ \\t]+|>[ \\t]?|[-*+][ \\t]+|\\d+[.)][ \\t]+)/;\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 * @returns {TextEditorBlockType} Block type.\n */\nexport const getBlockType = (state) => {\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 (/^[-*+][ \\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 {TextEditorFormatType} 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 === '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","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","<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 } from '../constants.js';\n  import { focusEditor } from '../core.js';\n  import { editRawText, registerRawTextShortcut, toggleInlineFormat } from '../raw-markdown.js';\n\n  /**\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   */\n  const format = async () => {\n    const { editor, textArea, useRichText } = editorStore;\n\n    if (!useRichText) {\n      // The button is only enabled while the `<textarea>` is there\n      editRawText(textArea, (state) => toggleInlineFormat(state, type));\n\n      return;\n    }\n\n    // The button is only enabled while the editor is there\n    /* v8 ignore else */\n    if (editor) {\n      await focusEditor(editor);\n      editor.dispatchCommand(FORMAT_TEXT_COMMAND, type);\n    }\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","import { $createParagraphNode as createParagraphNode, $insertNodes as insertNodes } from 'lexical';\nimport { insertComponent } from '../raw-markdown.js';\n\n/**\n * @import { TextEditorComponent, TextEditorStore } from '../../../typedefs.js';\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.\n * @param {TextEditorStore} editorStore Editor store.\n * @param {TextEditorComponent} component Editor component.\n */\nexport const insertEditorComponent = (editorStore, component) => {\n  const { textArea, useRichText } = editorStore;\n\n  // Insert the component’s Markdown in the plain text mode\n  if (!useRichText) {\n    // The toolbar is only enabled while the `<textarea>` is there\n    /* v8 ignore else */\n    if (textArea) {\n      insertComponent(textArea, component);\n    }\n\n    return;\n  }\n\n  const { createNode } = component;\n\n  editorStore.editor?.update(() => {\n    // Add an additional paragraph for easier editing\n    insertNodes([createNode(), createParagraphNode()]);\n  });\n};\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 './insert-component.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 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, isSafeLinkURL } from '../core.js';\n  import {\n    editRawText,\n    getRawTextState,\n    insertLink,\n    registerRawTextShortcut,\n  } from '../raw-markdown.js';\n\n  /**\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  /**\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    const { textArea, useRichText } = editorStore;\n\n    if (!useRichText) {\n      // The dialog can only be opened from the button, which needs the `<textarea>`\n      /* v8 ignore else */\n      if (textArea) {\n        if (event.detail.returnValue !== 'cancel') {\n          editRawText(textArea, (state) =>\n            insertLink(state, { url: anchorURL.trim(), text: hasAnchor ? undefined : anchorText }),\n          );\n        } else {\n          textArea.focus();\n        }\n      }\n\n      anchorURL = '';\n      anchorText = '';\n\n      return;\n    }\n\n    if (event.detail.returnValue !== 'cancel') {\n      // The dialog can only be opened from the button, which needs the editor\n      /* v8 ignore next */\n      if (!editorStore.editor) {\n        return;\n      }\n\n      await new Promise((resolve) => {\n        editorStore.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      await focusEditor(editorStore.editor);\n      editorStore.editor.dispatchCommand(TOGGLE_LINK_COMMAND, anchorURL);\n    } else /* v8 ignore else */ if (editorStore.editor) {\n      // The dialog leaves the focus alone (see `restoreFocus` below), so bring it back here\n      await focusEditor(editorStore.editor);\n    }\n\n    anchorURL = '';\n    anchorText = '';\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</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 './insert-component.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","<script>\n  import { $createCodeNode as createCodeNode } from '@lexical/code-core';\n  import { INSERT_ORDERED_LIST_COMMAND, INSERT_UNORDERED_LIST_COMMAND } from '@lexical/list';\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 } from '../constants.js';\n  import { focusEditor } from '../core.js';\n  import { editRawText, setBlockType } from '../raw-markdown.js';\n\n  /**\n   * @import { TextEditorBlockType, TextEditorStore } from '../../../typedefs.js';\n   * @import { HeadingTagType } from '@lexical/rich-text';\n   * @import { ElementNode, LexicalCommand } 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   * Commands for the list block types, which are toggled by the list plugin instead.\n   * @type {Record<string, LexicalCommand<void>>}\n   */\n  const LIST_COMMANDS = {\n    'bulleted-list': INSERT_UNORDERED_LIST_COMMAND,\n    'numbered-list': INSERT_ORDERED_LIST_COMMAND,\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   */\n  const changeBlockType = async () => {\n    if (!editorStore.useRichText) {\n      // The item is only clickable while the `<textarea>` is there\n      editRawText(editorStore.textArea, (state) => setBlockType(state, type));\n\n      return;\n    }\n\n    // The item is only clickable while the editor is there\n    /* v8 ignore next */\n    if (!editorStore.editor) {\n      return;\n    }\n\n    await focusEditor(editorStore.editor);\n\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      editorStore.editor.update(() => {\n        setBlocksType(getSelection(), createNode);\n      });\n    }\n\n    if (type in LIST_COMMANDS) {\n      editorStore.editor.dispatchCommand(LIST_COMMANDS[type], undefined);\n    }\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 { AVAILABLE_BUTTONS, BLOCK_BUTTON_TYPES, INLINE_BUTTON_TYPES } from '../constants.js';\n  import CodeLanguageSwitcher from './code-language-switcher.svelte';\n  import FormatTextButton from './format-text-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 ToggleBlockMenuItem from './toggle-block-menu-item.svelte';\n  import ToolbarWrapper from './toolbar-wrapper.svelte';\n\n  /**\n   * @import { TextEditorBlockType, TextEditorInlineType, TextEditorStore } from '../../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {boolean} [hidden] Whether to hide the widget.\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  const buttons = $derived(\n    editorStore.config.components.filter(({ trigger = 'menuitem' }) => trigger === 'button'),\n  );\n  const menuitems = $derived(\n    editorStore.config.components.filter(({ trigger = 'menuitem' }) => trigger === 'menuitem'),\n  );\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   * Enabled inline level buttons.\n   * @type {TextEditorInlineType[]}\n   */\n  const inlineLevelButtons = $derived(\n    unique(\n      editorStore.config.enabledButtons.filter((type) =>\n        INLINE_BUTTON_TYPES.includes(/** @type {any} */ (type)),\n      ),\n    ),\n  );\n</script>\n\n<ToolbarWrapper disabled={disabled || readonly} ariaLabel={_('_sui.text_editor.text_editor')}>\n  {#if canFormat && 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 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 editorStore.config.components.length}\n      <Divider orientation=\"vertical\" />\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        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 { BLOCK_BUTTON_TYPES, INLINE_BUTTON_TYPES } from './constants.js';\n  import { loadCodeHighlighter } from './core.js';\n  import EmojiAutocomplete from './emoji-autocomplete.svelte';\n  import FloatingLinkEditor from './floating-link-editor.svelte';\n  import LexicalRoot from './lexical-root.svelte';\n  import { getBlockType, getRawTextState } from './raw-markdown.js';\n  import { highlightCodeToTokens } from './shiki/facade.js';\n  import { getCodeTheme, onCodeThemeChange } from './shiki/theme.js';\n  import { createEditorStore } from './store.svelte.js';\n  import TextEditorToolbar from './toolbar/text-editor-toolbar.svelte';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import {\n   * TextEditorComponent,\n   * TextEditorMode,\n   * TextEditorNodeType,\n   * TextEditorValueFormat,\n   * } from '../../typedefs.js';\n   * @import { HighlightedToken } from '../../typedefs.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 {boolean} [flex] Make the text input container flexible.\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.\n   * @property {TextEditorComponent[]} [components] Editor components.\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   * @property {string} [class] The `class` attribute on the wrapper element.\n   * @property {boolean} [hidden] Whether to hide the widget.\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   * @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] The `aria-label` attribute on the editable text box. Either\n   * this or `ariaLabelledby` is required for the editor to have an accessible name.\n   * @property {string} [ariaLabelledby] The `aria-labelledby` attribute on the editable text box.\n   * @property {string} [ariaDescribedby] The `aria-describedby` attribute on the editable text\n   * box.\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    value = $bindable(''),\n    pending = $bindable(false),\n    format = 'markdown',\n    flex = false,\n    dir = undefined,\n    modes = ['rich-text', 'plain-text'],\n    buttons = [...INLINE_BUTTON_TYPES, ...BLOCK_BUTTON_TYPES],\n    components = [],\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    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  // svelte-ignore state_referenced_locally\n  editorStore.config = {\n    ...editorStore.config,\n    modes,\n    enabledButtons: buttons,\n    components,\n    useMarkdownShortcuts,\n    useEmojiAutocomplete,\n    format,\n  };\n\n  setContext('editorStore', editorStore);\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  /**\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\n   * sluggish.\n   */\n  const MAX_HIGHLIGHT_LENGTH = 20_000;\n\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 highlighterLoadCount = $state(0);\n\n  const usePlainText = $derived(!editorStore.useRichText && !hidden);\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 (\n      !usePlainText ||\n      sourceLanguage !== 'markdown' ||\n      editorStore.inputValue.length > MAX_HIGHLIGHT_LENGTH\n    ) {\n      return '';\n    }\n\n    return [\n      ...new Set(\n        [...editorStore.inputValue.matchAll(/^[ \\t]*(?:```|~~~)[ \\t]*(?<lang>[\\w+#-]+)/gm)].map(\n          ({ groups }) => groups?.lang,\n        ),\n      ),\n    ].join(',');\n  });\n\n  /**\n   * Highlight the Markdown or HTML source in the plain text mode.\n   * @param {string} source Markdown or HTML source.\n   * @returns {HighlightedToken[][] | undefined} Tokens, or `undefined` while the highlighter is\n   * still loading.\n   */\n  const highlightSource = (source) => {\n    void highlighterLoadCount;\n\n    // Don’t waste time on tokenizing the source while the rich text mode is shown\n    if (!usePlainText || source.length > MAX_HIGHLIGHT_LENGTH) {\n      return undefined;\n    }\n\n    return highlightCodeToTokens(source, sourceLanguage, { theme: codeTheme });\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 (usePlainText) {\n        await loadCodeHighlighter(sourceLanguage);\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 (!usePlainText) {\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(sourceLanguage).then(async () => {\n        highlighterLoadCount += 1;\n        await Promise.all(languages.map((lang) => loadCodeHighlighter(lang)));\n        highlighterLoadCount += 1;\n      });\n    });\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    /**\n     * Update the selection state. Until the `<textarea>` gets the focus, its caret is at the end of\n     * the value rather than where the user would expect, so the block type is not detected yet.\n     */\n    const update = () => {\n      editorStore.selection = {\n        blockNodeKey: null,\n        blockType:\n          document.activeElement === textArea\n            ? getBlockType(getRawTextState(textArea))\n            : 'paragraph',\n        inlineTypes: [],\n      };\n    };\n\n    const events = ['selectionchange', 'select', 'input', 'keyup', 'mouseup', 'focus'];\n\n    untrack(update);\n    events.forEach((type) => textArea.addEventListener(type, update));\n\n    return () => {\n      events.forEach((type) => textArea.removeEventListener(type, update));\n    };\n  });\n\n  $effect(() => {\n    pending = 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    pending = 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 = value;\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    untrack(() => {\n      if (value !== newValue) {\n        value = newValue;\n      }\n    });\n  });\n</script>\n\n<div {...restProps} role=\"none\" class=\"sui text-editor\" class:flex {hidden}>\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    bind:value={editorStore.inputValue}\n    {useEmojiAutocomplete}\n    highlight={highlightSource}\n    {flex}\n    {dir}\n    hidden={editorStore.useRichText || hidden}\n    {disabled}\n    {readonly}\n    {required}\n    {invalid}\n  />\n  {#if editorStore.config.useEmojiAutocomplete && !disabled && !readonly}\n    <EmojiAutocomplete />\n  {/if}\n  {#if editorStore.config.enabledButtons.includes('link') && !disabled && !readonly}\n    <FloatingLinkEditor />\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  margin: var(--sui-focus-ring-width);\n  border-radius: var(--sui-textbox-border-radius);\n  width: calc(100% - var(--sui-focus-ring-width) * 2);\n  transition: all 200ms;\n}\n.text-editor:focus-within {\n  outline: var(--sui-focus-ring-width) solid var(--sui-focus-ring-color);\n}\n.text-editor.flex:not([hidden]) {\n  display: block;\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}</style>\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 * Get the number of fraction digits a value should be formatted with, so stepping by `0.1` yields\n * `0.3` rather than `0.30000000000000004`.\n * @param {number} step Step value.\n * @returns {number} Number of fraction digits, `0` for an integer step.\n */\nexport const getMaximumFractionDigits = (step) => {\n  // A small step like `0.0000001` is stringified in exponent notation as `1e-7`\n  const [mantissa, exponent = '0'] = String(step).toLowerCase().split('e');\n  const digits = (mantissa.split('.')[1]?.length ?? 0) - Number(exponent);\n\n  return Math.max(digits, 0);\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  const maximumFractionDigits = getMaximumFractionDigits(step);\n  const newValue = Number((toNumber(inputValue) + step * direction).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 { _ } from '@sveltia/i18n';\n  import { untrack } from 'svelte';\n  import Button from '../button/button.svelte';\n  import Icon from '../icon/icon.svelte';\n  import {\n    getMaximumFractionDigits,\n    isAtMax,\n    isAtMin,\n    isInvalidNumber,\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 { CommonEventHandlers, InputEventHandlers, TextInputProps } 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.\n   * @property {Snippet} [increaseIcon] Increase icon slot content.\n   * @property {Snippet} [decreaseIcon] Decrease icon slot content.\n   */\n\n  /**\n   * @type {TextInputProps & CommonEventHandlers & InputEventHandlers & Props & Record<string, any>}\n   */\n  let {\n    /* eslint-disable prefer-const */\n    value = $bindable(),\n    invalid = $bindable(false),\n    flex = false,\n    min = undefined,\n    max = undefined,\n    step = 1,\n    class: className,\n    hidden = false,\n    disabled = false,\n    readonly = false,\n    required = false,\n    children,\n    increaseIcon,\n    decreaseIcon,\n    onChange,\n    onkeydown,\n    oninput,\n    ...restProps\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const id = $props.id();\n\n  let edited = $state(false);\n  let inputValue = $state('');\n\n  const maximumFractionDigits = $derived(getMaximumFractionDigits(step));\n  const isMin = $derived(isAtMin(inputValue, min));\n  const isMax = $derived(isAtMax(inputValue, 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(inputValue) !== newValue) {\n        inputValue = String(newValue ?? '');\n      }\n    });\n  });\n\n  $effect(() => {\n    value = parseNumber(inputValue);\n  });\n\n  $effect(() => {\n    if (edited) {\n      invalid = isInvalidNumber(inputValue, { 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(inputValue, { step, direction, min, max });\n\n    if (newInputValue !== undefined) {\n      inputValue = newInputValue;\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  {hidden}\n>\n  <div role=\"none\" class=\"buttons\">\n    <Button\n      iconic\n      disabled={disabled || readonly || Number.isNaN(Number(inputValue)) || 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(inputValue)) || 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  <TextInput\n    dir=\"ltr\"\n    {...restProps}\n    role=\"spinbutton\"\n    {id}\n    bind:value={inputValue}\n    spellcheck=\"false\"\n    {flex}\n    {hidden}\n    {disabled}\n    {readonly}\n    {required}\n    {invalid}\n    aria-valuenow={Number.isFinite(value) ? value : undefined}\n    aria-valuemin={min}\n    aria-valuemax={max}\n    inputmode={maximumFractionDigits > 0 ? 'decimal' : 'numeric'}\n    onkeydown={(event) => {\n      const { key, ctrlKey, metaKey, altKey, shiftKey } = event;\n      const hasModifier = shiftKey || altKey || ctrlKey || metaKey;\n      // A read-only field can’t be stepped, just like the spin buttons\n      const canStep = !disabled && !readonly && !hasModifier;\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    {onChange}\n  />\n</div>\n\n<style>.number-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.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: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(:not(:first-child)) :global(input) {\n  border-start-start-radius: 0;\n  border-end-start-radius: 0;\n}\n.number-input :global(:not(:last-child)) :global(input) {\n  border-start-end-radius: 0;\n  border-end-end-radius: 0;\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: row;\n  width: 48px;\n  height: var(--sui-textbox-height);\n}\n.buttons :global(button) {\n  flex: none;\n  margin: 0 !important;\n  border-width: 1px;\n  border-color: var(--sui-textbox-border-color);\n  width: 50%;\n  height: 100%;\n  border-inline-end-width: 0;\n}\n.buttons :global(button:first-of-type) {\n  border-start-end-radius: 0;\n  border-end-end-radius: 0;\n}\n.buttons :global(button:last-of-type) {\n  border-radius: 0;\n}\n.buttons :global(button) :global(.icon) {\n  font-size: 20px;\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 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 {'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 {TextInputProps & CommonEventHandlers & InputEventHandlers & Props & 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    // 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  /**\n   * Reference to the `<input>` element.\n   * @type {HTMLInputElement | undefined}\n   */\n  let inputElement = $state();\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\n  $effect(() => {\n    if (mask === 'type') {\n      inputElement?.setAttribute('type', show ? 'text' : 'password');\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  {hidden}\n>\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    bind:element={inputElement}\n    {...mask === 'css' ? { autocomplete: 'off', autocapitalize: 'off', autocorrect: 'off' } : {}}\n    {...restProps}\n    {id}\n    bind:value\n    {...mask === 'type' ? { type: '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 :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}</style>\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 { CommonEventHandlers, InputEventHandlers, TextInputProps } 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 {TextInputProps & CommonEventHandlers & InputEventHandlers & Props & 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 } from '../../typedefs.js';\n   */\n\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 {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\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.\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 & 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    // svelte-ignore state_referenced_locally\n    value = label,\n    // svelte-ignore state_referenced_locally\n    valueType = getValueType(value),\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  /** 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=\"{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    {@render endIcon?.()}\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>[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 { getArrowKeys } from './navigation.js';\nimport { scrollIntoViewIfNeeded } from './scroll.js';\nimport { normalize } from './text.js';\nimport { getSelectedItemDetail } from './select.svelte.js';\nimport { findTypeAheadMatch, TypeAhead } from './type-ahead.js';\nimport { activateBefore, activateLater } from './widget.js';\n\n/**\n * @import { Attachment } from 'svelte/attachments';\n */\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 {\n  /**\n   * Keystroke buffer for type-ahead.\n   * @type {TypeAhead}\n   */\n  #typeAhead = new TypeAhead();\n\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, { clickToSelect = true, selectionFollowsFocus, expandOnSelect = true } = {}) {\n    parent.dispatchEvent(new CustomEvent('Initializing'));\n\n    this.parent = parent;\n    this.id = generateElementId('tree');\n    this.clickToSelect = clickToSelect;\n    this.expandOnSelect = expandOnSelect;\n\n    /**\n     * Whether the selection follows the focus. `undefined` means auto detect.\n     * @type {boolean | undefined}\n     */\n    this.selectionFollowsFocusOption = selectionFollowsFocus;\n\n    /**\n     * Item used as the starting point of a range selection.\n     * @type {HTMLElement | undefined}\n     */\n    this.anchor = undefined;\n\n    /**\n     * Whether {@link activate} has run.\n     * @type {boolean}\n     */\n    this.activated = false;\n\n    /**\n     * Whether {@link destroy} has run, so a pending {@link activate} must not set anything up.\n     * @type {boolean}\n     */\n    this.destroyed = false;\n\n    /** @type {(event: MouseEvent) => void} */\n    this._onClick = activateBefore(this, (event) => this.onClick(event));\n    /** @type {(event: KeyboardEvent) => void} */\n    this._onKeyDown = activateBefore(this, (event) => this.onKeyDown(event));\n    /** @type {(event: FocusEvent) => void} */\n    this._onFocusIn = activateBefore(this, (event) => this.onFocusIn(event));\n\n    // The items can be added or removed at any time, e.g. when a subtree is lazily rendered\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    parent.addEventListener('click', this._onClick);\n    parent.addEventListener('keydown', this._onKeyDown);\n    parent.addEventListener('focusin', this._onFocusIn);\n\n    // Wait a bit before the child components are mounted. If the widget is unmounted in the\n    // meantime, the observer set up by `activate()` would never be disconnected.\n    activateLater(this, () => this.destroyed);\n  }\n\n  /**\n   * Activate the items, unless they already are.\n   */\n  activate() {\n    if (this.activated) {\n      return;\n    }\n\n    const { parent } = this;\n\n    this.activated = true;\n    this.update();\n    this.observer.observe(parent, { childList: true, subtree: true });\n    parent.dispatchEvent(new CustomEvent('Initialized'));\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   * 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   * 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        if (!item.matches('[hidden], [aria-hidden=\"true\"]')) {\n          items.push(item);\n        }\n\n        // A collapsed parent hides everything below it, so there is nothing to descend into\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 item.dataset.label ?? item.querySelector('.label')?.textContent ?? '';\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   * Scroll the given element into view if needed.\n   * @param {HTMLElement} element Element to be scrolled into view.\n   */\n  scrollIntoView(element) {\n    scrollIntoViewIfNeeded(element);\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    this.scrollIntoView(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.parent.dispatchEvent(new CustomEvent('Change', { detail: getSelectedItemDetail(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.parent.dispatchEvent(new CustomEvent('Change', { detail: getSelectedItemDetail(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 = findTypeAheadMatch(\n      items.map((item) => normalize(this.getLabel(item))),\n      this.#typeAhead.push(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    if (!item) {\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    const currentItem = target ?? this.currentItem ?? activeItems[0];\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 (key.length === 1 && key.trim()) {\n      this.typeAhead(key, currentItem);\n    }\n  }\n\n  /**\n   * Clean up event listeners.\n   */\n  destroy() {\n    this.destroyed = true;\n    this.#typeAhead.reset();\n    this.observer.disconnect();\n    this.parent.removeEventListener('click', this._onClick);\n    this.parent.removeEventListener('keydown', this._onKeyDown);\n    this.parent.removeEventListener('focusin', this._onFocusIn);\n  }\n}\n\n/**\n * Activate a new tree.\n * @param {object} [params] Params to be passed to the `Tree` constructor.\n * @returns {Attachment} Attachment.\n */\nexport const activateTree = (params) => (parent) => {\n  const tree = new Tree(/** @type {HTMLElement} */ (parent), params);\n\n  return () => {\n    tree.destroy();\n  };\n};\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 { Snippet } from 'svelte';\n   * @import { CommonEventHandlers } from '../../typedefs.js';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {HTMLElement} [element] A reference to the wrapper element.\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 {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   * @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 {Snippet} [children] Primary slot content.\n   * @property {(event: CustomEvent) => void} [onChange] Custom `Change` event handler.\n   */\n\n  /**\n   * @type {CommonEventHandlers & 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-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-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 { Snippet } from 'svelte';\n   */\n\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.\n   * @property {boolean} [disabled] Whether to disable the widget. An alias of the `aria-disabled`\n   * attribute.\n   * @property {string} [ariaLabel] The `aria-label` attribute on the wrapper element.\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    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 {Snippet} children Slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    children,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {HTMLElement | null} */\n  let placeholder = $state(null);\n  /** @type {boolean} */\n  let visible = $state(false);\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\"},\"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\"},\"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\",\"blockquote\":\"Block Quote\",\"code_block\":\"Code Block\",\"bold\":\"Bold\",\"italic\":\"Italic\",\"strikethrough\":\"Strikethrough\",\"code\":\"Code\",\"link\":\"Link\",\"insert_link\":\"Insert Link\",\"edit_link\":\"Edit Link\",\"remove_link\":\"Remove Link\",\"text\":\"Text\",\"url\":\"URL\",\"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 pkg from '../../../../package.json';\n\nexport const { dependencies, version } = pkg;\n\n/**\n * Base URL for the CMS on the UNPKG CDN.\n */\nexport const UNPKG_BASE_URL = 'https://unpkg.com/@sveltia/cms';\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/yaml', // default\n  'application/toml',\n  'application/json',\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 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 * 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 */\nexport const watchAsync = (fn, onResult) => {\n  $effect(() => {\n    const promise = fn();\n\n    if (!promise) {\n      return undefined;\n    }\n\n    let stale = false;\n\n    promise.then((result) => {\n      if (!stale) {\n        onResult(result);\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 * @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   * 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\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, updateValue);\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};\n","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.\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  const [, dirname, basename, filename, extension] = path.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 * 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`, and a subtype may carry a suffix like `svg+xml`\n  const extension = file.type.split('/')[1]?.split(/[+;]/)[0];\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\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\") case-insesitively 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]|lpt[0-9])(\\..*)?$/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  return end < str.length ? str.slice(0, end) + replacement : str;\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  return truncate(sanitized, 255);\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 * 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 * 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.\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    const value = /** @type {V} */ (cache.get(key));\n\n    // A `Map` iterates in insertion order, so re-inserting the key moves it to the end, marking it\n    // as the most recently used entry\n    cache.delete(key);\n    cache.set(key, value);\n\n    return value;\n  }\n\n  const value = create();\n\n  cache.set(key, value);\n\n  if (cache.size > maxSize) {\n    // The first key is the least recently used one\n    cache.delete(/** @type {K} */ (cache.keys().next().value));\n  }\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","import { getHash } from '@sveltia/utils/crypto';\nimport { getPathInfo } from '@sveltia/utils/file';\nimport { escapeRegExp } from '@sveltia/utils/string';\nimport sanitize from 'sanitize-filename';\n\nimport { getOrCreateAsync } from '$lib/services/utils/cache';\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. Since {@link encodeURIComponent} encodes\n * slashes, we need to split and join. Also, encode some more characters, including `!`, `(` and\n * `)`, which affect the Markdown syntax like images and links. The `@` prefix is an exception; it\n * shouldn’t be encoded.\n * @param {string} path Original path.\n * @returns {string} Encoded path.\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent#encoding_for_rfc3986\n */\nexport const encodeFilePath = (path) => {\n  const hasAtPrefix = path.startsWith('@');\n\n  if (hasAtPrefix) {\n    path = path.slice(1);\n  }\n\n  path = path\n    .split('/')\n    .map((str) =>\n      encodeURIComponent(str).replace(\n        /[!'()*]/g,\n        (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,\n      ),\n    )\n    .join('/');\n\n  if (hasAtPrefix) {\n    return `@${path}`;\n  }\n\n  return path;\n};\n\n/**\n * Check if the given file name or slug has duplicate(s) or its variant in the other names. If\n * found, rename it by prepending a number like `summer-beach-2.jpg`.\n * @param {string} name Original name.\n * @param {string[]} otherNames Other names (of files in the same folder).\n * @returns {string} Determined name.\n */\nexport const renameIfNeeded = (name, otherNames) => {\n  if (!otherNames.length) {\n    return name;\n  }\n\n  const { filename: slug, extension } = getPathInfo(name);\n\n  // Case-insensitive, since `Photo.jpg` and `photo.jpg` clash on a case-insensitive file system\n  // like macOS’s or Windows’s\n  const regex = new RegExp(\n    `^${escapeRegExp(slug)}(?:-(?<num>\\\\d+?))?${extension ? `\\\\.${extension}` : ''}$`,\n    'i',\n  );\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\n  let highest = -1;\n\n  otherNames.forEach((otherName) => {\n    const match = otherName.match(regex);\n\n    if (match) {\n      highest = Math.max(highest, Number(match.groups?.num ?? 0));\n    }\n  });\n\n  if (highest === -1) {\n    return name;\n  }\n\n  return `${slug}-${highest + 1}${extension ? `.${extension}` : ''}`;\n};\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.\n * @param {string} name Name.\n * @returns {string} Sanitized name.\n */\nexport const sanitizeFileName = (name) =>\n  sanitize(name.normalize().replace(/[\\s\\u00A0\\u202F]+/g, ' '));\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 * 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.\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 | null)[]} */\n  const segments = path.split('/');\n  let nameFound = false;\n\n  segments.forEach((segment, index) => {\n    if (segment === '.' || segment === '..') {\n      if (nameFound) {\n        segments[index] = null;\n\n        if (segment === '..') {\n          const lastIndex = segments.findLastIndex((s, i) => !!s && i < index);\n\n          if (lastIndex > -1) {\n            segments[lastIndex] = null;\n          }\n        }\n      }\n    } else {\n      nameFound = true;\n    }\n  });\n\n  return createPath(segments);\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","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 * Get a file or directory handle at the given path.\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, name] of pathParts.entries()) {\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 * 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","const types = {\n    'application/prs.cww': ['cww'],\n    'application/prs.xsf+xml': ['xsf'],\n    'application/vnd.1000minds.decision-model+xml': ['1km'],\n    'application/vnd.3gpp.pic-bw-large': ['plb'],\n    'application/vnd.3gpp.pic-bw-small': ['psb'],\n    'application/vnd.3gpp.pic-bw-var': ['pvb'],\n    'application/vnd.3gpp2.tcap': ['tcap'],\n    'application/vnd.3m.post-it-notes': ['pwn'],\n    'application/vnd.accpac.simply.aso': ['aso'],\n    'application/vnd.accpac.simply.imp': ['imp'],\n    'application/vnd.acucobol': ['acu'],\n    'application/vnd.acucorp': ['atc', 'acutc'],\n    'application/vnd.adobe.air-application-installer-package+zip': ['air'],\n    'application/vnd.adobe.formscentral.fcdt': ['fcdt'],\n    'application/vnd.adobe.fxp': ['fxp', 'fxpl'],\n    'application/vnd.adobe.xdp+xml': ['xdp'],\n    'application/vnd.adobe.xfdf': ['*xfdf'],\n    'application/vnd.age': ['age'],\n    'application/vnd.ahead.space': ['ahead'],\n    'application/vnd.airzip.filesecure.azf': ['azf'],\n    'application/vnd.airzip.filesecure.azs': ['azs'],\n    'application/vnd.amazon.ebook': ['azw'],\n    'application/vnd.americandynamics.acc': ['acc'],\n    'application/vnd.amiga.ami': ['ami'],\n    'application/vnd.android.package-archive': ['apk'],\n    'application/vnd.anser-web-certificate-issue-initiation': ['cii'],\n    'application/vnd.anser-web-funds-transfer-initiation': ['fti'],\n    'application/vnd.antix.game-component': ['atx'],\n    'application/vnd.apple.installer+xml': ['mpkg'],\n    'application/vnd.apple.keynote': ['key'],\n    'application/vnd.apple.mpegurl': ['m3u8'],\n    'application/vnd.apple.numbers': ['numbers'],\n    'application/vnd.apple.pages': ['pages'],\n    'application/vnd.apple.pkpass': ['pkpass'],\n    'application/vnd.aristanetworks.swi': ['swi'],\n    'application/vnd.astraea-software.iota': ['iota'],\n    'application/vnd.audiograph': ['aep'],\n    'application/vnd.autodesk.fbx': ['fbx'],\n    'application/vnd.balsamiq.bmml+xml': ['bmml'],\n    'application/vnd.blueice.multipass': ['mpm'],\n    'application/vnd.bmi': ['bmi'],\n    'application/vnd.businessobjects': ['rep'],\n    'application/vnd.chemdraw+xml': ['cdxml'],\n    'application/vnd.chipnuts.karaoke-mmd': ['mmd'],\n    'application/vnd.cinderella': ['cdy'],\n    'application/vnd.citationstyles.style+xml': ['csl'],\n    'application/vnd.claymore': ['cla'],\n    'application/vnd.cloanto.rp9': ['rp9'],\n    'application/vnd.clonk.c4group': ['c4g', 'c4d', 'c4f', 'c4p', 'c4u'],\n    'application/vnd.cluetrust.cartomobile-config': ['c11amc'],\n    'application/vnd.cluetrust.cartomobile-config-pkg': ['c11amz'],\n    'application/vnd.commonspace': ['csp'],\n    'application/vnd.contact.cmsg': ['cdbcmsg'],\n    'application/vnd.cosmocaller': ['cmc'],\n    'application/vnd.crick.clicker': ['clkx'],\n    'application/vnd.crick.clicker.keyboard': ['clkk'],\n    'application/vnd.crick.clicker.palette': ['clkp'],\n    'application/vnd.crick.clicker.template': ['clkt'],\n    'application/vnd.crick.clicker.wordbank': ['clkw'],\n    'application/vnd.criticaltools.wbs+xml': ['wbs'],\n    'application/vnd.ctc-posml': ['pml'],\n    'application/vnd.cups-ppd': ['ppd'],\n    'application/vnd.curl.car': ['car'],\n    'application/vnd.curl.pcurl': ['pcurl'],\n    'application/vnd.dart': ['dart'],\n    'application/vnd.data-vision.rdz': ['rdz'],\n    'application/vnd.dbf': ['dbf'],\n    'application/vnd.dcmp+xml': ['dcmp'],\n    'application/vnd.dece.data': ['uvf', 'uvvf', 'uvd', 'uvvd'],\n    'application/vnd.dece.ttml+xml': ['uvt', 'uvvt'],\n    'application/vnd.dece.unspecified': ['uvx', 'uvvx'],\n    'application/vnd.dece.zip': ['uvz', 'uvvz'],\n    'application/vnd.denovo.fcselayout-link': ['fe_launch'],\n    'application/vnd.dna': ['dna'],\n    'application/vnd.dolby.mlp': ['mlp'],\n    'application/vnd.dpgraph': ['dpg'],\n    'application/vnd.dreamfactory': ['dfac'],\n    'application/vnd.ds-keypoint': ['kpxx'],\n    'application/vnd.dvb.ait': ['ait'],\n    'application/vnd.dvb.service': ['svc'],\n    'application/vnd.dynageo': ['geo'],\n    'application/vnd.ecowin.chart': ['mag'],\n    'application/vnd.enliven': ['nml'],\n    'application/vnd.epson.esf': ['esf'],\n    'application/vnd.epson.msf': ['msf'],\n    'application/vnd.epson.quickanime': ['qam'],\n    'application/vnd.epson.salt': ['slt'],\n    'application/vnd.epson.ssf': ['ssf'],\n    'application/vnd.eszigno3+xml': ['es3', 'et3'],\n    'application/vnd.ezpix-album': ['ez2'],\n    'application/vnd.ezpix-package': ['ez3'],\n    'application/vnd.fdf': ['*fdf'],\n    'application/vnd.fdsn.mseed': ['mseed'],\n    'application/vnd.fdsn.seed': ['seed', 'dataless'],\n    'application/vnd.flographit': ['gph'],\n    'application/vnd.fluxtime.clip': ['ftc'],\n    'application/vnd.framemaker': ['fm', 'frame', 'maker', 'book'],\n    'application/vnd.frogans.fnc': ['fnc'],\n    'application/vnd.frogans.ltf': ['ltf'],\n    'application/vnd.fsc.weblaunch': ['fsc'],\n    'application/vnd.fujitsu.oasys': ['oas'],\n    'application/vnd.fujitsu.oasys2': ['oa2'],\n    'application/vnd.fujitsu.oasys3': ['oa3'],\n    'application/vnd.fujitsu.oasysgp': ['fg5'],\n    'application/vnd.fujitsu.oasysprs': ['bh2'],\n    'application/vnd.fujixerox.ddd': ['ddd'],\n    'application/vnd.fujixerox.docuworks': ['xdw'],\n    'application/vnd.fujixerox.docuworks.binder': ['xbd'],\n    'application/vnd.fuzzysheet': ['fzs'],\n    'application/vnd.genomatix.tuxedo': ['txd'],\n    'application/vnd.geogebra.file': ['ggb'],\n    'application/vnd.geogebra.slides': ['ggs'],\n    'application/vnd.geogebra.tool': ['ggt'],\n    'application/vnd.geometry-explorer': ['gex', 'gre'],\n    'application/vnd.geonext': ['gxt'],\n    'application/vnd.geoplan': ['g2w'],\n    'application/vnd.geospace': ['g3w'],\n    'application/vnd.gmx': ['gmx'],\n    'application/vnd.google-apps.document': ['gdoc'],\n    'application/vnd.google-apps.drawing': ['gdraw'],\n    'application/vnd.google-apps.form': ['gform'],\n    'application/vnd.google-apps.jam': ['gjam'],\n    'application/vnd.google-apps.map': ['gmap'],\n    'application/vnd.google-apps.presentation': ['gslides'],\n    'application/vnd.google-apps.script': ['gscript'],\n    'application/vnd.google-apps.site': ['gsite'],\n    'application/vnd.google-apps.spreadsheet': ['gsheet'],\n    'application/vnd.google-earth.kml+xml': ['kml'],\n    'application/vnd.google-earth.kmz': ['kmz'],\n    'application/vnd.gov.sk.xmldatacontainer+xml': ['xdcf'],\n    'application/vnd.grafeq': ['gqf', 'gqs'],\n    'application/vnd.groove-account': ['gac'],\n    'application/vnd.groove-help': ['ghf'],\n    'application/vnd.groove-identity-message': ['gim'],\n    'application/vnd.groove-injector': ['grv'],\n    'application/vnd.groove-tool-message': ['gtm'],\n    'application/vnd.groove-tool-template': ['tpl'],\n    'application/vnd.groove-vcard': ['vcg'],\n    'application/vnd.hal+xml': ['hal'],\n    'application/vnd.handheld-entertainment+xml': ['zmm'],\n    'application/vnd.hbci': ['hbci'],\n    'application/vnd.hhe.lesson-player': ['les'],\n    'application/vnd.hp-hpgl': ['hpgl'],\n    'application/vnd.hp-hpid': ['hpid'],\n    'application/vnd.hp-hps': ['hps'],\n    'application/vnd.hp-jlyt': ['jlt'],\n    'application/vnd.hp-pcl': ['pcl'],\n    'application/vnd.hp-pclxl': ['pclxl'],\n    'application/vnd.hydrostatix.sof-data': ['sfd-hdstx'],\n    'application/vnd.ibm.minipay': ['mpy'],\n    'application/vnd.ibm.modcap': ['afp', 'listafp', 'list3820'],\n    'application/vnd.ibm.rights-management': ['irm'],\n    'application/vnd.ibm.secure-container': ['sc'],\n    'application/vnd.iccprofile': ['icc', 'icm'],\n    'application/vnd.igloader': ['igl'],\n    'application/vnd.immervision-ivp': ['ivp'],\n    'application/vnd.immervision-ivu': ['ivu'],\n    'application/vnd.insors.igm': ['igm'],\n    'application/vnd.intercon.formnet': ['xpw', 'xpx'],\n    'application/vnd.intergeo': ['i2g'],\n    'application/vnd.intu.qbo': ['qbo'],\n    'application/vnd.intu.qfx': ['qfx'],\n    'application/vnd.ipunplugged.rcprofile': ['rcprofile'],\n    'application/vnd.irepository.package+xml': ['irp'],\n    'application/vnd.is-xpr': ['xpr'],\n    'application/vnd.isac.fcs': ['fcs'],\n    'application/vnd.jam': ['jam'],\n    'application/vnd.jcp.javame.midlet-rms': ['rms'],\n    'application/vnd.jisp': ['jisp'],\n    'application/vnd.joost.joda-archive': ['joda'],\n    'application/vnd.kahootz': ['ktz', 'ktr'],\n    'application/vnd.kde.karbon': ['karbon'],\n    'application/vnd.kde.kchart': ['chrt'],\n    'application/vnd.kde.kformula': ['kfo'],\n    'application/vnd.kde.kivio': ['flw'],\n    'application/vnd.kde.kontour': ['kon'],\n    'application/vnd.kde.kpresenter': ['kpr', 'kpt'],\n    'application/vnd.kde.kspread': ['ksp'],\n    'application/vnd.kde.kword': ['kwd', 'kwt'],\n    'application/vnd.kenameaapp': ['htke'],\n    'application/vnd.kidspiration': ['kia'],\n    'application/vnd.kinar': ['kne', 'knp'],\n    'application/vnd.koan': ['skp', 'skd', 'skt', 'skm'],\n    'application/vnd.kodak-descriptor': ['sse'],\n    'application/vnd.las.las+xml': ['lasxml'],\n    'application/vnd.llamagraphics.life-balance.desktop': ['lbd'],\n    'application/vnd.llamagraphics.life-balance.exchange+xml': ['lbe'],\n    'application/vnd.lotus-1-2-3': ['123'],\n    'application/vnd.lotus-approach': ['apr'],\n    'application/vnd.lotus-freelance': ['pre'],\n    'application/vnd.lotus-notes': ['nsf'],\n    'application/vnd.lotus-organizer': ['org'],\n    'application/vnd.lotus-screencam': ['scm'],\n    'application/vnd.lotus-wordpro': ['lwp'],\n    'application/vnd.macports.portpkg': ['portpkg'],\n    'application/vnd.mapbox-vector-tile': ['mvt'],\n    'application/vnd.mcd': ['mcd'],\n    'application/vnd.medcalcdata': ['mc1'],\n    'application/vnd.mediastation.cdkey': ['cdkey'],\n    'application/vnd.mfer': ['mwf'],\n    'application/vnd.mfmp': ['mfm'],\n    'application/vnd.micrografx.flo': ['flo'],\n    'application/vnd.micrografx.igx': ['igx'],\n    'application/vnd.mif': ['mif'],\n    'application/vnd.mobius.daf': ['daf'],\n    'application/vnd.mobius.dis': ['dis'],\n    'application/vnd.mobius.mbk': ['mbk'],\n    'application/vnd.mobius.mqy': ['mqy'],\n    'application/vnd.mobius.msl': ['msl'],\n    'application/vnd.mobius.plc': ['plc'],\n    'application/vnd.mobius.txf': ['txf'],\n    'application/vnd.mophun.application': ['mpn'],\n    'application/vnd.mophun.certificate': ['mpc'],\n    'application/vnd.mozilla.xul+xml': ['xul'],\n    'application/vnd.ms-artgalry': ['cil'],\n    'application/vnd.ms-cab-compressed': ['cab'],\n    'application/vnd.ms-excel': ['xls', 'xlm', 'xla', 'xlc', 'xlt', 'xlw'],\n    'application/vnd.ms-excel.addin.macroenabled.12': ['xlam'],\n    'application/vnd.ms-excel.sheet.binary.macroenabled.12': ['xlsb'],\n    'application/vnd.ms-excel.sheet.macroenabled.12': ['xlsm'],\n    'application/vnd.ms-excel.template.macroenabled.12': ['xltm'],\n    'application/vnd.ms-fontobject': ['eot'],\n    'application/vnd.ms-htmlhelp': ['chm'],\n    'application/vnd.ms-ims': ['ims'],\n    'application/vnd.ms-lrm': ['lrm'],\n    'application/vnd.ms-officetheme': ['thmx'],\n    'application/vnd.ms-outlook': ['msg'],\n    'application/vnd.ms-pki.seccat': ['cat'],\n    'application/vnd.ms-pki.stl': ['*stl'],\n    'application/vnd.ms-powerpoint': ['ppt', 'pps', 'pot'],\n    'application/vnd.ms-powerpoint.addin.macroenabled.12': ['ppam'],\n    'application/vnd.ms-powerpoint.presentation.macroenabled.12': ['pptm'],\n    'application/vnd.ms-powerpoint.slide.macroenabled.12': ['sldm'],\n    'application/vnd.ms-powerpoint.slideshow.macroenabled.12': ['ppsm'],\n    'application/vnd.ms-powerpoint.template.macroenabled.12': ['potm'],\n    'application/vnd.ms-project': ['*mpp', 'mpt'],\n    'application/vnd.ms-visio.viewer': ['vdx'],\n    'application/vnd.ms-word.document.macroenabled.12': ['docm'],\n    'application/vnd.ms-word.template.macroenabled.12': ['dotm'],\n    'application/vnd.ms-works': ['wps', 'wks', 'wcm', 'wdb'],\n    'application/vnd.ms-wpl': ['wpl'],\n    'application/vnd.ms-xpsdocument': ['xps'],\n    'application/vnd.mseq': ['mseq'],\n    'application/vnd.musician': ['mus'],\n    'application/vnd.muvee.style': ['msty'],\n    'application/vnd.mynfc': ['taglet'],\n    'application/vnd.nato.bindingdataobject+xml': ['bdo'],\n    'application/vnd.neurolanguage.nlu': ['nlu'],\n    'application/vnd.nitf': ['ntf', 'nitf'],\n    'application/vnd.noblenet-directory': ['nnd'],\n    'application/vnd.noblenet-sealer': ['nns'],\n    'application/vnd.noblenet-web': ['nnw'],\n    'application/vnd.nokia.n-gage.ac+xml': ['*ac'],\n    'application/vnd.nokia.n-gage.data': ['ngdat'],\n    'application/vnd.nokia.n-gage.symbian.install': ['n-gage'],\n    'application/vnd.nokia.radio-preset': ['rpst'],\n    'application/vnd.nokia.radio-presets': ['rpss'],\n    'application/vnd.novadigm.edm': ['edm'],\n    'application/vnd.novadigm.edx': ['edx'],\n    'application/vnd.novadigm.ext': ['ext'],\n    'application/vnd.oasis.opendocument.chart': ['odc'],\n    'application/vnd.oasis.opendocument.chart-template': ['otc'],\n    'application/vnd.oasis.opendocument.database': ['odb'],\n    'application/vnd.oasis.opendocument.formula': ['odf'],\n    'application/vnd.oasis.opendocument.formula-template': ['odft'],\n    'application/vnd.oasis.opendocument.graphics': ['odg'],\n    'application/vnd.oasis.opendocument.graphics-template': ['otg'],\n    'application/vnd.oasis.opendocument.image': ['odi'],\n    'application/vnd.oasis.opendocument.image-template': ['oti'],\n    'application/vnd.oasis.opendocument.presentation': ['odp'],\n    'application/vnd.oasis.opendocument.presentation-template': ['otp'],\n    'application/vnd.oasis.opendocument.spreadsheet': ['ods'],\n    'application/vnd.oasis.opendocument.spreadsheet-template': ['ots'],\n    'application/vnd.oasis.opendocument.text': ['odt'],\n    'application/vnd.oasis.opendocument.text-master': ['odm'],\n    'application/vnd.oasis.opendocument.text-template': ['ott'],\n    'application/vnd.oasis.opendocument.text-web': ['oth'],\n    'application/vnd.olpc-sugar': ['xo'],\n    'application/vnd.oma.dd2+xml': ['dd2'],\n    'application/vnd.openblox.game+xml': ['obgx'],\n    'application/vnd.openofficeorg.extension': ['oxt'],\n    'application/vnd.openstreetmap.data+xml': ['osm'],\n    'application/vnd.openxmlformats-officedocument.presentationml.presentation': [\n        'pptx',\n    ],\n    'application/vnd.openxmlformats-officedocument.presentationml.slide': [\n        'sldx',\n    ],\n    'application/vnd.openxmlformats-officedocument.presentationml.slideshow': [\n        'ppsx',\n    ],\n    'application/vnd.openxmlformats-officedocument.presentationml.template': [\n        'potx',\n    ],\n    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ['xlsx'],\n    'application/vnd.openxmlformats-officedocument.spreadsheetml.template': [\n        'xltx',\n    ],\n    'application/vnd.openxmlformats-officedocument.wordprocessingml.document': [\n        'docx',\n    ],\n    'application/vnd.openxmlformats-officedocument.wordprocessingml.template': [\n        'dotx',\n    ],\n    'application/vnd.osgeo.mapguide.package': ['mgp'],\n    'application/vnd.osgi.dp': ['dp'],\n    'application/vnd.osgi.subsystem': ['esa'],\n    'application/vnd.palm': ['pdb', 'pqa', 'oprc'],\n    'application/vnd.pawaafile': ['paw'],\n    'application/vnd.pg.format': ['str'],\n    'application/vnd.pg.osasli': ['ei6'],\n    'application/vnd.picsel': ['efif'],\n    'application/vnd.pmi.widget': ['wg'],\n    'application/vnd.pocketlearn': ['plf'],\n    'application/vnd.powerbuilder6': ['pbd'],\n    'application/vnd.previewsystems.box': ['box'],\n    'application/vnd.procrate.brushset': ['brushset'],\n    'application/vnd.procreate.brush': ['brush'],\n    'application/vnd.procreate.dream': ['drm'],\n    'application/vnd.proteus.magazine': ['mgz'],\n    'application/vnd.publishare-delta-tree': ['qps'],\n    'application/vnd.pvi.ptid1': ['ptid'],\n    'application/vnd.pwg-xhtml-print+xml': ['xhtm'],\n    'application/vnd.quark.quarkxpress': [\n        'qxd',\n        'qxt',\n        'qwd',\n        'qwt',\n        'qxl',\n        'qxb',\n    ],\n    'application/vnd.rar': ['rar'],\n    'application/vnd.realvnc.bed': ['bed'],\n    'application/vnd.recordare.musicxml': ['mxl'],\n    'application/vnd.recordare.musicxml+xml': ['musicxml'],\n    'application/vnd.rig.cryptonote': ['cryptonote'],\n    'application/vnd.rim.cod': ['cod'],\n    'application/vnd.rn-realmedia': ['rm'],\n    'application/vnd.rn-realmedia-vbr': ['rmvb'],\n    'application/vnd.route66.link66+xml': ['link66'],\n    'application/vnd.sailingtracker.track': ['st'],\n    'application/vnd.seemail': ['see'],\n    'application/vnd.sema': ['sema'],\n    'application/vnd.semd': ['semd'],\n    'application/vnd.semf': ['semf'],\n    'application/vnd.shana.informed.formdata': ['ifm'],\n    'application/vnd.shana.informed.formtemplate': ['itp'],\n    'application/vnd.shana.informed.interchange': ['iif'],\n    'application/vnd.shana.informed.package': ['ipk'],\n    'application/vnd.simtech-mindmapper': ['twd', 'twds'],\n    'application/vnd.smaf': ['mmf'],\n    'application/vnd.smart.teacher': ['teacher'],\n    'application/vnd.software602.filler.form+xml': ['fo'],\n    'application/vnd.solent.sdkm+xml': ['sdkm', 'sdkd'],\n    'application/vnd.spotfire.dxp': ['dxp'],\n    'application/vnd.spotfire.sfs': ['sfs'],\n    'application/vnd.stardivision.calc': ['sdc'],\n    'application/vnd.stardivision.draw': ['sda'],\n    'application/vnd.stardivision.impress': ['sdd'],\n    'application/vnd.stardivision.math': ['smf'],\n    'application/vnd.stardivision.writer': ['sdw', 'vor'],\n    'application/vnd.stardivision.writer-global': ['sgl'],\n    'application/vnd.stepmania.package': ['smzip'],\n    'application/vnd.stepmania.stepchart': ['sm'],\n    'application/vnd.sun.wadl+xml': ['wadl'],\n    'application/vnd.sun.xml.calc': ['sxc'],\n    'application/vnd.sun.xml.calc.template': ['stc'],\n    'application/vnd.sun.xml.draw': ['sxd'],\n    'application/vnd.sun.xml.draw.template': ['std'],\n    'application/vnd.sun.xml.impress': ['sxi'],\n    'application/vnd.sun.xml.impress.template': ['sti'],\n    'application/vnd.sun.xml.math': ['sxm'],\n    'application/vnd.sun.xml.writer': ['sxw'],\n    'application/vnd.sun.xml.writer.global': ['sxg'],\n    'application/vnd.sun.xml.writer.template': ['stw'],\n    'application/vnd.sus-calendar': ['sus', 'susp'],\n    'application/vnd.svd': ['svd'],\n    'application/vnd.symbian.install': ['sis', 'sisx'],\n    'application/vnd.syncml+xml': ['xsm'],\n    'application/vnd.syncml.dm+wbxml': ['bdm'],\n    'application/vnd.syncml.dm+xml': ['xdm'],\n    'application/vnd.syncml.dmddf+xml': ['ddf'],\n    'application/vnd.tao.intent-module-archive': ['tao'],\n    'application/vnd.tcpdump.pcap': ['pcap', 'cap', 'dmp'],\n    'application/vnd.tmobile-livetv': ['tmo'],\n    'application/vnd.trid.tpt': ['tpt'],\n    'application/vnd.triscape.mxs': ['mxs'],\n    'application/vnd.trueapp': ['tra'],\n    'application/vnd.ufdl': ['ufd', 'ufdl'],\n    'application/vnd.uiq.theme': ['utz'],\n    'application/vnd.umajin': ['umj'],\n    'application/vnd.unity': ['unityweb'],\n    'application/vnd.uoml+xml': ['uoml', 'uo'],\n    'application/vnd.vcx': ['vcx'],\n    'application/vnd.visio': ['vsd', 'vst', 'vss', 'vsw', 'vsdx', 'vtx'],\n    'application/vnd.visionary': ['vis'],\n    'application/vnd.vsf': ['vsf'],\n    'application/vnd.wap.wbxml': ['wbxml'],\n    'application/vnd.wap.wmlc': ['wmlc'],\n    'application/vnd.wap.wmlscriptc': ['wmlsc'],\n    'application/vnd.webturbo': ['wtb'],\n    'application/vnd.wolfram.player': ['nbp'],\n    'application/vnd.wordperfect': ['wpd'],\n    'application/vnd.wqd': ['wqd'],\n    'application/vnd.wt.stf': ['stf'],\n    'application/vnd.xara': ['xar'],\n    'application/vnd.xfdl': ['xfdl'],\n    'application/vnd.yamaha.hv-dic': ['hvd'],\n    'application/vnd.yamaha.hv-script': ['hvs'],\n    'application/vnd.yamaha.hv-voice': ['hvp'],\n    'application/vnd.yamaha.openscoreformat': ['osf'],\n    'application/vnd.yamaha.openscoreformat.osfpvg+xml': ['osfpvg'],\n    'application/vnd.yamaha.smaf-audio': ['saf'],\n    'application/vnd.yamaha.smaf-phrase': ['spf'],\n    'application/vnd.yellowriver-custom-menu': ['cmp'],\n    'application/vnd.zul': ['zir', 'zirz'],\n    'application/vnd.zzazz.deck+xml': ['zaz'],\n    'application/x-7z-compressed': ['7z'],\n    'application/x-abiword': ['abw'],\n    'application/x-ace-compressed': ['ace'],\n    'application/x-apple-diskimage': ['*dmg'],\n    'application/x-arj': ['arj'],\n    'application/x-authorware-bin': ['aab', 'x32', 'u32', 'vox'],\n    'application/x-authorware-map': ['aam'],\n    'application/x-authorware-seg': ['aas'],\n    'application/x-bcpio': ['bcpio'],\n    'application/x-bdoc': ['*bdoc'],\n    'application/x-bittorrent': ['torrent'],\n    'application/x-blender': ['blend'],\n    'application/x-blorb': ['blb', 'blorb'],\n    'application/x-bzip': ['bz'],\n    'application/x-bzip2': ['bz2', 'boz'],\n    'application/x-cbr': ['cbr', 'cba', 'cbt', 'cbz', 'cb7'],\n    'application/x-cdlink': ['vcd'],\n    'application/x-cfs-compressed': ['cfs'],\n    'application/x-chat': ['chat'],\n    'application/x-chess-pgn': ['pgn'],\n    'application/x-chrome-extension': ['crx'],\n    'application/x-cocoa': ['cco'],\n    'application/x-compressed': ['*rar'],\n    'application/x-conference': ['nsc'],\n    'application/x-cpio': ['cpio'],\n    'application/x-csh': ['csh'],\n    'application/x-debian-package': ['*deb', 'udeb'],\n    'application/x-dgc-compressed': ['dgc'],\n    'application/x-director': [\n        'dir',\n        'dcr',\n        'dxr',\n        'cst',\n        'cct',\n        'cxt',\n        'w3d',\n        'fgd',\n        'swa',\n    ],\n    'application/x-doom': ['wad'],\n    'application/x-dtbncx+xml': ['ncx'],\n    'application/x-dtbook+xml': ['dtb'],\n    'application/x-dtbresource+xml': ['res'],\n    'application/x-dvi': ['dvi'],\n    'application/x-envoy': ['evy'],\n    'application/x-eva': ['eva'],\n    'application/x-font-bdf': ['bdf'],\n    'application/x-font-ghostscript': ['gsf'],\n    'application/x-font-linux-psf': ['psf'],\n    'application/x-font-pcf': ['pcf'],\n    'application/x-font-snf': ['snf'],\n    'application/x-font-type1': ['pfa', 'pfb', 'pfm', 'afm'],\n    'application/x-freearc': ['arc'],\n    'application/x-futuresplash': ['spl'],\n    'application/x-gca-compressed': ['gca'],\n    'application/x-glulx': ['ulx'],\n    'application/x-gnumeric': ['gnumeric'],\n    'application/x-gramps-xml': ['gramps'],\n    'application/x-gtar': ['gtar'],\n    'application/x-hdf': ['hdf'],\n    'application/x-httpd-php': ['php'],\n    'application/x-install-instructions': ['install'],\n    'application/x-ipynb+json': ['ipynb'],\n    'application/x-iso9660-image': ['*iso'],\n    'application/x-iwork-keynote-sffkey': ['*key'],\n    'application/x-iwork-numbers-sffnumbers': ['*numbers'],\n    'application/x-iwork-pages-sffpages': ['*pages'],\n    'application/x-java-archive-diff': ['jardiff'],\n    'application/x-java-jnlp-file': ['jnlp'],\n    'application/x-keepass2': ['kdbx'],\n    'application/x-latex': ['latex'],\n    'application/x-lua-bytecode': ['luac'],\n    'application/x-lzh-compressed': ['lzh', 'lha'],\n    'application/x-makeself': ['run'],\n    'application/x-mie': ['mie'],\n    'application/x-mobipocket-ebook': ['*prc', 'mobi'],\n    'application/x-ms-application': ['application'],\n    'application/x-ms-shortcut': ['lnk'],\n    'application/x-ms-wmd': ['wmd'],\n    'application/x-ms-wmz': ['wmz'],\n    'application/x-ms-xbap': ['xbap'],\n    'application/x-msaccess': ['mdb'],\n    'application/x-msbinder': ['obd'],\n    'application/x-mscardfile': ['crd'],\n    'application/x-msclip': ['clp'],\n    'application/x-msdos-program': ['*exe'],\n    'application/x-msdownload': ['*exe', '*dll', 'com', 'bat', '*msi'],\n    'application/x-msmediaview': ['mvb', 'm13', 'm14'],\n    'application/x-msmetafile': ['*wmf', '*wmz', '*emf', 'emz'],\n    'application/x-msmoney': ['mny'],\n    'application/x-mspublisher': ['pub'],\n    'application/x-msschedule': ['scd'],\n    'application/x-msterminal': ['trm'],\n    'application/x-mswrite': ['wri'],\n    'application/x-netcdf': ['nc', 'cdf'],\n    'application/x-ns-proxy-autoconfig': ['pac'],\n    'application/x-nzb': ['nzb'],\n    'application/x-perl': ['pl', 'pm'],\n    'application/x-pilot': ['*prc', '*pdb'],\n    'application/x-pkcs12': ['p12', 'pfx'],\n    'application/x-pkcs7-certificates': ['p7b', 'spc'],\n    'application/x-pkcs7-certreqresp': ['p7r'],\n    'application/x-rar-compressed': ['*rar'],\n    'application/x-redhat-package-manager': ['rpm'],\n    'application/x-research-info-systems': ['ris'],\n    'application/x-sea': ['sea'],\n    'application/x-sh': ['sh'],\n    'application/x-shar': ['shar'],\n    'application/x-shockwave-flash': ['swf'],\n    'application/x-silverlight-app': ['xap'],\n    'application/x-sql': ['*sql'],\n    'application/x-stuffit': ['sit'],\n    'application/x-stuffitx': ['sitx'],\n    'application/x-subrip': ['srt'],\n    'application/x-sv4cpio': ['sv4cpio'],\n    'application/x-sv4crc': ['sv4crc'],\n    'application/x-t3vm-image': ['t3'],\n    'application/x-tads': ['gam'],\n    'application/x-tar': ['tar'],\n    'application/x-tcl': ['tcl', 'tk'],\n    'application/x-tex': ['tex'],\n    'application/x-tex-tfm': ['tfm'],\n    'application/x-texinfo': ['texinfo', 'texi'],\n    'application/x-tgif': ['*obj'],\n    'application/x-ustar': ['ustar'],\n    'application/x-virtualbox-hdd': ['hdd'],\n    'application/x-virtualbox-ova': ['ova'],\n    'application/x-virtualbox-ovf': ['ovf'],\n    'application/x-virtualbox-vbox': ['vbox'],\n    'application/x-virtualbox-vbox-extpack': ['vbox-extpack'],\n    'application/x-virtualbox-vdi': ['vdi'],\n    'application/x-virtualbox-vhd': ['vhd'],\n    'application/x-virtualbox-vmdk': ['vmdk'],\n    'application/x-wais-source': ['src'],\n    'application/x-web-app-manifest+json': ['webapp'],\n    'application/x-x509-ca-cert': ['der', 'crt', 'pem'],\n    'application/x-xfig': ['fig'],\n    'application/x-xliff+xml': ['*xlf'],\n    'application/x-xpinstall': ['xpi'],\n    'application/x-xz': ['xz'],\n    'application/x-zip-compressed': ['*zip'],\n    'application/x-zmachine': ['z1', 'z2', 'z3', 'z4', 'z5', 'z6', 'z7', 'z8'],\n    'audio/vnd.dece.audio': ['uva', 'uvva'],\n    'audio/vnd.digital-winds': ['eol'],\n    'audio/vnd.dra': ['dra'],\n    'audio/vnd.dts': ['dts'],\n    'audio/vnd.dts.hd': ['dtshd'],\n    'audio/vnd.lucent.voice': ['lvp'],\n    'audio/vnd.ms-playready.media.pya': ['pya'],\n    'audio/vnd.nuera.ecelp4800': ['ecelp4800'],\n    'audio/vnd.nuera.ecelp7470': ['ecelp7470'],\n    'audio/vnd.nuera.ecelp9600': ['ecelp9600'],\n    'audio/vnd.rip': ['rip'],\n    'audio/x-aac': ['*aac'],\n    'audio/x-aiff': ['aif', 'aiff', 'aifc'],\n    'audio/x-caf': ['caf'],\n    'audio/x-flac': ['flac'],\n    'audio/x-m4a': ['*m4a'],\n    'audio/x-matroska': ['mka'],\n    'audio/x-mpegurl': ['m3u'],\n    'audio/x-ms-wax': ['wax'],\n    'audio/x-ms-wma': ['wma'],\n    'audio/x-pn-realaudio': ['ram', 'ra'],\n    'audio/x-pn-realaudio-plugin': ['rmp'],\n    'audio/x-realaudio': ['*ra'],\n    'audio/x-wav': ['*wav'],\n    'chemical/x-cdx': ['cdx'],\n    'chemical/x-cif': ['cif'],\n    'chemical/x-cmdf': ['cmdf'],\n    'chemical/x-cml': ['cml'],\n    'chemical/x-csml': ['csml'],\n    'chemical/x-xyz': ['xyz'],\n    'image/prs.btif': ['btif', 'btf'],\n    'image/prs.pti': ['pti'],\n    'image/vnd.adobe.photoshop': ['psd'],\n    'image/vnd.airzip.accelerator.azv': ['azv'],\n    'image/vnd.blockfact.facti': ['facti'],\n    'image/vnd.dece.graphic': ['uvi', 'uvvi', 'uvg', 'uvvg'],\n    'image/vnd.djvu': ['djvu', 'djv'],\n    'image/vnd.dvb.subtitle': ['*sub'],\n    'image/vnd.dwg': ['dwg'],\n    'image/vnd.dxf': ['dxf'],\n    'image/vnd.fastbidsheet': ['fbs'],\n    'image/vnd.fpx': ['fpx'],\n    'image/vnd.fst': ['fst'],\n    'image/vnd.fujixerox.edmics-mmr': ['mmr'],\n    'image/vnd.fujixerox.edmics-rlc': ['rlc'],\n    'image/vnd.microsoft.icon': ['ico'],\n    'image/vnd.ms-dds': ['dds'],\n    'image/vnd.ms-modi': ['mdi'],\n    'image/vnd.ms-photo': ['wdp'],\n    'image/vnd.net-fpx': ['npx'],\n    'image/vnd.pco.b16': ['b16'],\n    'image/vnd.tencent.tap': ['tap'],\n    'image/vnd.valve.source.texture': ['vtf'],\n    'image/vnd.wap.wbmp': ['wbmp'],\n    'image/vnd.xiff': ['xif'],\n    'image/vnd.zbrush.pcx': ['pcx'],\n    'image/x-3ds': ['3ds'],\n    'image/x-adobe-dng': ['dng'],\n    'image/x-cmu-raster': ['ras'],\n    'image/x-cmx': ['cmx'],\n    'image/x-freehand': ['fh', 'fhc', 'fh4', 'fh5', 'fh7'],\n    'image/x-icon': ['*ico'],\n    'image/x-jng': ['jng'],\n    'image/x-mrsid-image': ['sid'],\n    'image/x-ms-bmp': ['*bmp'],\n    'image/x-pcx': ['*pcx'],\n    'image/x-pict': ['pic', 'pct'],\n    'image/x-portable-anymap': ['pnm'],\n    'image/x-portable-bitmap': ['pbm'],\n    'image/x-portable-graymap': ['pgm'],\n    'image/x-portable-pixmap': ['ppm'],\n    'image/x-rgb': ['rgb'],\n    'image/x-tga': ['tga'],\n    'image/x-xbitmap': ['xbm'],\n    'image/x-xpixmap': ['xpm'],\n    'image/x-xwindowdump': ['xwd'],\n    'message/vnd.wfa.wsc': ['wsc'],\n    'model/vnd.bary': ['bary'],\n    'model/vnd.cld': ['cld'],\n    'model/vnd.collada+xml': ['dae'],\n    'model/vnd.dwf': ['dwf'],\n    'model/vnd.gdl': ['gdl'],\n    'model/vnd.gtw': ['gtw'],\n    'model/vnd.mts': ['*mts'],\n    'model/vnd.opengex': ['ogex'],\n    'model/vnd.parasolid.transmit.binary': ['x_b'],\n    'model/vnd.parasolid.transmit.text': ['x_t'],\n    'model/vnd.pytha.pyox': ['pyo', 'pyox'],\n    'model/vnd.sap.vds': ['vds'],\n    'model/vnd.usda': ['usda'],\n    'model/vnd.usdz+zip': ['usdz'],\n    'model/vnd.valve.source.compiled-map': ['bsp'],\n    'model/vnd.vtu': ['vtu'],\n    'text/prs.lines.tag': ['dsc'],\n    'text/vnd.curl': ['curl'],\n    'text/vnd.curl.dcurl': ['dcurl'],\n    'text/vnd.curl.mcurl': ['mcurl'],\n    'text/vnd.curl.scurl': ['scurl'],\n    'text/vnd.dvb.subtitle': ['sub'],\n    'text/vnd.familysearch.gedcom': ['ged'],\n    'text/vnd.fly': ['fly'],\n    'text/vnd.fmi.flexstor': ['flx'],\n    'text/vnd.graphviz': ['gv'],\n    'text/vnd.in3d.3dml': ['3dml'],\n    'text/vnd.in3d.spot': ['spot'],\n    'text/vnd.sun.j2me.app-descriptor': ['jad'],\n    'text/vnd.wap.wml': ['wml'],\n    'text/vnd.wap.wmlscript': ['wmls'],\n    'text/x-asm': ['s', 'asm'],\n    'text/x-c': ['c', 'cc', 'cxx', 'cpp', 'h', 'hh', 'dic'],\n    'text/x-component': ['htc'],\n    'text/x-fortran': ['f', 'for', 'f77', 'f90'],\n    'text/x-handlebars-template': ['hbs'],\n    'text/x-java-source': ['java'],\n    'text/x-lua': ['lua'],\n    'text/x-markdown': ['mkd'],\n    'text/x-nfo': ['nfo'],\n    'text/x-opml': ['opml'],\n    'text/x-org': ['*org'],\n    'text/x-pascal': ['p', 'pas'],\n    'text/x-processing': ['pde'],\n    'text/x-sass': ['sass'],\n    'text/x-scss': ['scss'],\n    'text/x-setext': ['etx'],\n    'text/x-sfv': ['sfv'],\n    'text/x-suse-ymp': ['ymp'],\n    'text/x-uuencode': ['uu'],\n    'text/x-vcalendar': ['vcs'],\n    'text/x-vcard': ['vcf'],\n    'video/vnd.dece.hd': ['uvh', 'uvvh'],\n    'video/vnd.dece.mobile': ['uvm', 'uvvm'],\n    'video/vnd.dece.pd': ['uvp', 'uvvp'],\n    'video/vnd.dece.sd': ['uvs', 'uvvs'],\n    'video/vnd.dece.video': ['uvv', 'uvvv'],\n    'video/vnd.dvb.file': ['dvb'],\n    'video/vnd.fvt': ['fvt'],\n    'video/vnd.mpegurl': ['mxu', 'm4u'],\n    'video/vnd.ms-playready.media.pyv': ['pyv'],\n    'video/vnd.uvvu.mp4': ['uvu', 'uvvu'],\n    'video/vnd.vivo': ['viv'],\n    'video/x-f4v': ['f4v'],\n    'video/x-fli': ['fli'],\n    'video/x-flv': ['flv'],\n    'video/x-m4v': ['m4v'],\n    'video/x-matroska': ['mkv', 'mk3d', 'mks'],\n    'video/x-mng': ['mng'],\n    'video/x-ms-asf': ['asf', 'asx'],\n    'video/x-ms-vob': ['vob'],\n    'video/x-ms-wm': ['wm'],\n    'video/x-ms-wmv': ['wmv'],\n    'video/x-ms-wmx': ['wmx'],\n    'video/x-ms-wvx': ['wvx'],\n    'video/x-msvideo': ['avi'],\n    'video/x-sgi-movie': ['movie'],\n    'video/x-smv': ['smv'],\n    'x-conference/x-cooltalk': ['ice'],\n};\nObject.freeze(types);\nexport default types;\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            if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").has(type)) {\n                __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").set(type, new Set());\n            }\n            const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").get(type);\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        return __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").get(type.toLowerCase()) ?? 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        for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, \"f\").values()) {\n            Object.freeze(extensions);\n        }\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 otherTypes from '../types/other.js';\nimport standardTypes from '../types/standard.js';\nimport Mime from './Mime.js';\nexport { default as Mime } from './Mime.js';\nexport default new Mime(standardTypes, otherTypes)._freeze();\n","import { isTextFileType } from '@sveltia/utils/file';\nimport { isURL } from '@sveltia/utils/string';\nimport mime from '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 a thumbnail can be generated for a PDF document with the given name, by rendering its\n * first page with PDF.js. Not in the npm build, which doesn’t load PDF.js from a CDN and doesn’t\n * bundle it either, as the library comes with hundreds of files for character maps, fonts and\n * image decoders; `pdf.npm.js` replaces `pdf.js` there. A PDF is shown with a generic icon instead.\n * @param {string} fileName File name or path, e.g. `files/brochure.pdf`.\n * @returns {boolean} Result.\n */\nexport const hasPDFThumbnail = (fileName) =>\n  !import.meta.env.NPM_BUILD && fileName.endsWith('.pdf');\n\n/**\n * Whether a thumbnail can be generated for the given asset: an image, a video, or a PDF document\n * outside the npm build, see {@link hasPDFThumbnail}.\n * @param {Asset} asset Asset.\n * @returns {boolean} Result.\n */\nexport const canCreateThumbnail = (asset) =>\n  THUMBNAIL_KINDS.includes(asset.kind) || hasPDFThumbnail(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 { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Asset, 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 * 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/**\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(name.normalize().toLowerCase());\n\n/**\n * Check whether the given folder is, or is below, a folder the CMS itself is usually served from.\n * @param {string} dirPath Folder path. An empty string for the root.\n * @returns {boolean} Result.\n */\nexport const isCmsFolderPath = (dirPath) => dirPath.split('/').some(isCmsFolderName);\n\n/**\n * Check whether the given file is below a folder the CMS itself is usually served from.\n * @param {string} path File path.\n * @returns {boolean} Result.\n */\nexport const isInCmsFolder = (path) =>\n  isCmsFolderPath(path.slice(0, Math.max(path.lastIndexOf('/'), 0)));\n\n/**\n * Make sure none of the given files is below a folder the CMS itself is usually served from. The\n * Asset Library doesn’t offer 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 * 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.\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 * Regex to match escaped `{{variable}}` placeholders.\n */\nexport const ESCAPED_PLACEHOLDER_REGEX = /\\\\\\{\\\\\\{.+?\\\\\\}\\\\\\}/g;\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 * Regex to match inner tags within transformation values.\n */\nexport const INNER_TAG_REGEX = /^{{(?<innerTag>.+?)}}$/;\n\n/**\n * UUID generator functions mapped by tag name.\n * Note: Functions are called dynamically to generate UUIDs on demand.\n */\nexport const UUID_TYPES = {\n  uuid: 'uuid',\n  uuid_short: 'uuid_short',\n  uuid_shorter: 'uuid_shorter',\n};\n","import { TEMPLATE_TAG_REGEX } from '$lib/services/common/template/constants';\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.\n * @param {string} str The string containing template tags.\n * @param {(match: string, placeholder: string) => string} replacer Replacement callback.\n * @returns {string} Result of the replacements.\n */\nexport const replaceTemplateTags = (str, replacer) => {\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      if (char === \"'\" && !quoteState) {\n        quoteState = true;\n      } else if (char === \"'\" && quoteState) {\n        quoteState = false;\n      }\n\n      if (!quoteState && char === '}' && nextChar === '}') {\n        const closeIndex = cursor;\n        const hasLeadingQuote = str[openIndex - 1] === \"'\";\n        const hasTrailingQuote = str[closeIndex + 2] === \"'\";\n        const openingDelimiter = str[openIndex - 2];\n        const closingDelimiter = str[closeIndex + 3];\n        const placeholder = str.slice(openIndex + 2, closeIndex);\n\n        /* v8 ignore next */\n        const isNestedTransformationArgument =\n          hasLeadingQuote &&\n          hasTrailingQuote &&\n          ['(', ',', '[', '|'].includes(openingDelimiter ?? '') &&\n          [')', ',', ']'].includes(closingDelimiter ?? '');\n\n        if (!placeholder) {\n          result += str.slice(openIndex, closeIndex + 2);\n        } else if (isNestedTransformationArgument) {\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 * 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","/**\n * @import { CustomFileFormat } from '$lib/types/private';\n * @import {\n * AppEventListener,\n * CustomFieldControl,\n * CustomFieldPreview,\n * CustomFieldSchema,\n * CustomPreviewTemplate,\n * EditorComponentDefinition,\n * } from '$lib/types/public';\n */\n\n/**\n * Custom components registered using the `CMS.registerEditorComponent` API.\n * @type {Map<string, EditorComponentDefinition>}\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 field types registered using the `CMS.registerField` API.\n * @type {Map<string, { control: CustomFieldControl | string, preview?: CustomFieldPreview, schema?:\n * 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 stylesheet URLs registered with the `CMS.registerPreviewStyle` API.\n * @type {Set<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 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","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 { flatten, unflatten } from 'flat';\n\n/**\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 * 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  unflatten(\n    Object.fromEntries(\n      Object.entries(flatten(props)).filter(([key]) => !key.split('.').pop()?.startsWith('__sc_')),\n    ),\n  );\n\n/**\n * Replace double quotes with single quotes to avoid breaking Markdown syntax.\n * @param {string} str String to escape.\n * @returns {string} Escaped string.\n */\nexport const replaceQuotes = (str) => str.replace(/\"/g, \"'\");\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)`, and\n * supports escaped characters like `![alt](image\\(1\\).jpg)` and titles with escaped quotes.\n * @type {RegExp}\n */\nexport const IMAGE_REGEX =\n  /!\\[(?<alt>(?:[^\\]\\\\]|\\\\.)*)\\]\\((?<src>(?:[^\"()\\\\]|\\\\.|\\([^)]*\\)|\"[^\"]*\")*?)(?:\\s+\"(?<title>(?:[^\"\\\\]|\\\\.)*)\")?\\)/;\n\n/**\n * Global version of `IMAGE_REGEX` (with the `g` flag).\n * @type {RegExp}\n */\nexport const GLOBAL_IMAGE_REGEX = new RegExp(IMAGE_REGEX, 'g');\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)`.\n * @type {RegExp}\n */\nexport const LINKED_IMAGE_REGEX =\n  /\\[!\\[(?<alt2>(?:[^\\]\\\\]|\\\\.)*)\\]\\((?<src2>(?:[^\"()\\\\]|\\\\.|\\([^)]*\\)|\"[^\"]*\")*?)(?:\\s+\"(?<title2>(?:[^\"\\\\]|\\\\.)*)\")?\\)\\](?:\\((?<link>[^)]*\\([^)]*\\)[^)]*|[^)]*)\\))/;\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","import { 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 * 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","import { _ } from '@sveltia/i18n';\n\nimport { customComponentRegistry } from '$lib/services/api/registries';\nimport { replaceQuotes } from '$lib/services/contents/fields/rich-text/components/utils';\nimport {\n  IMAGE_OR_LINKED_IMAGE_REGEX,\n  IMAGE_REGEX,\n} from '$lib/services/contents/fields/rich-text/constants';\nimport { escapeAttr } from '$lib/services/utils/string';\n\n/**\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 * 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 = {\n  /* eslint-disable jsdoc/require-jsdoc */\n  id: 'image',\n  label: 'Image',\n  fields: [\n    { name: 'src', label: 'Source', widget: 'image' },\n    { name: 'alt', label: 'Alt Text', required: false },\n    { name: 'title', label: 'Title', required: false },\n  ],\n  pattern: IMAGE_REGEX,\n  toBlock: (props) => {\n    const { src = '', alt = '', title = '' } = props;\n\n    return src ? `![${alt}](${src}${title ? ` \"${replaceQuotes(title)}\"` : ''})` : '';\n  },\n  toPreview: (props) => {\n    const { src = '', alt = '', title = '' } = props;\n\n    return `<img src=\"${escapeAttr(src)}\" alt=\"${escapeAttr(alt)}\" title=\"${escapeAttr(title)}\">`;\n  },\n  htmlSelector: 'img',\n  fromBlockHTML: getImageProps,\n  toBlockHTML: createImageElement,\n  /* eslint-enable jsdoc/require-jsdoc */\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 = {\n  /* eslint-disable jsdoc/require-jsdoc */\n  id: 'linked-image',\n  label: 'Image',\n  fields: [...IMAGE_COMPONENT.fields, { name: 'link', label: 'Link', required: false }],\n  pattern: IMAGE_OR_LINKED_IMAGE_REGEX,\n  fromBlock: (match) => {\n    const { src, alt, title, src2, alt2, title2, link } = match.groups ?? {};\n\n    return {\n      src: (src || src2 || '').trim(),\n      alt: (alt || alt2 || '').trim(),\n      title: (title || title2 || '').trim(),\n      link: (link || '').trim(),\n    };\n  },\n  toBlock: (props) => {\n    const { src = '', alt = '', title = '', link = '' } = props;\n    const img = src ? `![${alt}](${src}${title ? ` \"${replaceQuotes(title)}\"` : ''})` : '';\n\n    return img && link ? `[${img}](${link})` : img;\n  },\n  toPreview: (props) => {\n    const { src = '', alt = '', title = '', link = '' } = props;\n    // eslint-disable-next-line @stylistic/max-len\n    const img = `<img src=\"${escapeAttr(src)}\" alt=\"${escapeAttr(alt)}\" title=\"${escapeAttr(title)}\">`;\n\n    return link ? `<a href=\"${escapeAttr(link)}\">${img}</a>` : img;\n  },\n  // An image within a link that has nothing else, or a bare image\n  htmlSelector: 'a:has(> img:only-child), img',\n  fromBlockHTML: (element) => {\n    if (element.localName === 'img') {\n      return { ...getImageProps(element), link: '' };\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 = '' } = props;\n    const img = createImageElement(props);\n\n    if (!img || !link) {\n      return img;\n    }\n\n    const anchor = document.createElement('a');\n\n    anchor.setAttribute('href', link);\n    anchor.append(img);\n\n    return anchor;\n  },\n  /* eslint-enable jsdoc/require-jsdoc */\n};\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  // Common props with localized labels\n  const commonImageProps = {\n    icon: 'image',\n    label: _('editor_components.image'),\n    fields: [\n      { name: 'src', label: _('editor_components.src'), widget: 'image' },\n      { name: 'alt', label: _('editor_components.alt'), required: false },\n      { name: 'title', label: _('editor_components.title'), required: false },\n    ],\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  return [\n    {\n      ...IMAGE_COMPONENT,\n      // Override with localized labels\n      ...commonImageProps,\n    },\n    {\n      ...LINKED_IMAGE_COMPONENT,\n      // Override with localized labels\n      ...commonImageProps,\n      fields: [\n        ...commonImageProps.fields,\n        { name: 'link', label: _('editor_components.link'), required: false },\n      ],\n    },\n  ];\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 {EditorComponentDefinition | undefined} Definition.\n */\nexport const getComponentDef = (name) => {\n  const customComponentName = getCustomComponentName(name);\n\n  if (customComponentName) {\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    const customComponentDef = /** @type {EditorComponentDefinition} */ (\n      customComponentRegistry.get(customComponentName)\n    );\n\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","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","/**\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 { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\nimport { OPEN_AUTHORING_STAGES, WORKFLOW_STAGES } from '$lib/services/workflow/constants';\n\n/**\n * @import {\n * ForkPermissionRequest,\n * RepositoryInfo,\n * RepositoryPath,\n * WorkflowStatus,\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 * The review stages an unpublished entry can move through, which are the board columns and the\n * options in the editor’s status menu. An Open Authoring contributor can’t merge a pull request, so\n * the stage that says an entry is ready to be published is left out.\n * @type {{ readonly current: WorkflowStatus[] }}\n */\nexport const workflowStages = createDerivedState(() =>\n  openAuthoring.current ? OPEN_AUTHORING_STAGES : WORKFLOW_STAGES,\n);\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 be\n  // defensive: leaving an earlier request unresolved would hang that flow forever\n  forkPermissionRequest.current?.respond(false);\n\n  return new Promise((resolve) => {\n    /** @type {ForkPermissionRequest} */\n    const request = {\n      repo,\n      /**\n       * Answer the request.\n       * @param {boolean} granted Whether the user granted permission.\n       */\n      respond: (granted) => {\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 (forkPermissionRequest.current === request) {\n          forkPermissionRequest.current = undefined;\n        }\n\n        resolve(granted);\n      },\n    };\n\n    forkPermissionRequest.current = request;\n  });\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 { ESCAPED_PLACEHOLDER_REGEX } from '$lib/services/common/template/constants';\nimport { hasTemplateTags } from '$lib/services/common/template/tags';\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 nested collection keeps its own `images` folder there, which is left out, since\n  // any folder named like that would match. Media stored next to the entries (no subfolder), out of\n  // the repository (`../`) or in a folder named after each entry (a leading tag like `{{slug}}`)\n  // can’t be told apart from the other files in the repository, so the folder 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 = escapeRegExp(subPath).replace(ESCAPED_PLACEHOLDER_REGEX, '[^/]+');\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 * @type {() => {\n * items: Array<{ folder: AssetFolderInfo, regexSub: RegExp, regexExact: RegExp }>,\n * entryRelative: Array<{ folder: AssetFolderInfo, regex: RegExp }>,\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 = escapeRegExp(internalPath).replace(ESCAPED_PLACEHOLDER_REGEX, '.+?');\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 };\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 } = getAssetFolderPathCache();\n  const dir = dirname ?? '';\n\n  const results = [\n    ...entryRelative.filter(({ regex }) => regex.test(path)).map(({ folder }) => folder),\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    ...items\n      .filter(({ regexSub, regexExact }) => (matchSubFolders ? regexSub : regexExact).test(dir))\n      .map(({ folder }) => folder),\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 * 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.\n */\nexport const assetsLocked = createDerivedState(\n  () => openAuthoring.current || !!lockedBranch.current,\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. A file in a folder the CMS itself\n * is served from, such as `admin`, is read-only as well, wherever the media folder is.\n * @param {Asset[]} assets Assets.\n * @returns {boolean} Result.\n */\nexport const hasReadonlyAsset = (assets) =>\n  assets.some(({ folder, path }) => !!folder?.readonly || isInCmsFolder(path));\n","/**\n * Name prefix of the temporary file a new or updated file is written to before it’s renamed to its\n * final name. See {@link saveFile}.\n */\nexport const TEMP_FILE_PREFIX = '.sveltia-tmp-';\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 { 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","/* eslint-disable no-continue */\n/* eslint-disable no-restricted-syntax */\n\nimport { unique } from '@sveltia/utils/array';\nimport { escapeRegExp, stripSlashes } from '@sveltia/utils/string';\n\nimport { allAssetFolders } from '$lib/services/assets/folders';\nimport { TEMP_FILE_PREFIX } from '$lib/services/backends/fs/shared/constants';\nimport { GIT_CONFIG_FILE_REGEX } from '$lib/services/backends/git/shared/config';\nimport { ESCAPED_PLACEHOLDER_REGEX } from '$lib/services/common/template/constants';\nimport { allEntryFolders } from '$lib/services/contents';\nimport { createPathRegEx } from '$lib/services/utils/file';\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/**\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) =>\n    escapeRegExp(segment).replace(ESCAPED_PLACEHOLDER_REGEX, '.+?'),\n  );\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.\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.\n * @param {Map<string, RegExp>} context.pathRegexCache Cache for path regexes.\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  for await (const [name, handle] of dirHandle.entries()) {\n    // Skip hidden files and directories, except for Git configuration files\n    if (name.startsWith('.') && !GIT_CONFIG_FILE_REGEX.test(name)) {\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    const hasMatchingPath = scanningPathsRegEx.some((regex) => regex.test(path));\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      fileHandles.push({\n        handle: /** @type {FileSystemFileHandle} */ (handle),\n        path,\n      });\n    }\n\n    if (handle.kind === 'directory') {\n      // Cache regex creation to avoid recreating for the same path\n      let regex = pathRegexCache.get(path);\n\n      if (!regex) {\n        regex = getPathRegex(path);\n        pathRegexCache.set(path, regex);\n      }\n\n      if (hasMatchingPath || scanningPaths.some((p) => regex.test(p))) {\n        await scanDir(/** @type {FileSystemDirectoryHandle} */ (handle), context, path);\n      }\n    }\n  }\n};\n\n/**\n * Collect all scanning paths from entry and asset folders.\n * @returns {string[]} Unique list of normalized scanning paths.\n */\nexport const collectScanningPaths = () => {\n  const entryPaths = allEntryFolders.current.flatMap(({ filePathMap, folderPathMap }) =>\n    filePathMap ? Object.values(filePathMap) : Object.values(folderPathMap ?? {}),\n  );\n\n  const assetPaths = allAssetFolders.current\n    .filter(({ internalPath }) => internalPath !== undefined)\n    .map(({ internalPath }) => internalPath);\n\n  return unique(\n    /* v8 ignore next */\n    [...entryPaths, ...assetPaths].map((path) => stripSlashes(path ?? '')),\n  );\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 * 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","/**\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","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    indexFile = {\n      name,\n      label: file.label || _('index_file'),\n      icon: file.icon ?? 'home',\n      // The following properties are inherited from the collection file, collection or global\n      // config\n      extension: file.extension,\n      format: file.format,\n      fields: file.fields,\n      editor: file.editor,\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 { 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 */\nconst 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","/**\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  uuid_read_only: 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};\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  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    'https://sveltiacms.app/en/docs/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`. https://sveltiacms.app/en/docs/data-output#controlling-data-output',\n  uuid_read_only:\n    'The `read_only` option for the UUID field type is deprecated and will be removed in Sveltia ' +\n    'CMS 1.0. Use the `readonly` option instead.',\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    'https://sveltiacms.app/en/docs/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    'https://sveltiacms.app/en/docs/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    'https://sveltiacms.app/en/docs/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    'https://sveltiacms.app/en/docs/i18n/structures',\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. https://sveltiacms.app/en/docs/customization#custom-logo',\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","/**\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 * Template engine extensions that support any front matter format.\n * @type {string[]}\n */\nexport const TEMPLATE_ENGINE_EXTENSIONS = ['njk'];\n\n/**\n * Allowed extensions for the `frontmatter` auto-detect format.\n * @type {string[]}\n */\nexport const ALLOWED_FRONTMATTER_EXTENSIONS = [\n  ...MARKDOWN_EXTENSIONS,\n  ...TEMPLATE_ENGINE_EXTENSIONS,\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","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 nested collection.\n * @typedef {object} NestedCollectionConfig\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 `widget` and `label` options are\n * accepted for compatibility with Netlify/Decap CMS but ignored: the editor is always a folder\n * picker with a built-in label.\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 nested collection.\n * @param {Collection | InternalCollection} collection Collection.\n * @returns {NestedCollectionConfig | 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 is a nested collection.\n * @param {Collection | InternalCollection} collection Collection.\n * @returns {boolean} Result.\n */\nexport const isNestedCollection = (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 (!isNestedCollection(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 nested collection stores its entries as, e.g. `_index`. Unlike\n * the `index_file` collection option, which marks one special entry within a collection, this file\n * name is meaningful throughout a nested collection: it names every entry in the `subfolders` mode,\n * 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  isNestedCollection(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 nested collection from the given slug, which is\n * the entry’s path within the collection folder. That name is how the content folder stores an\n * entry, not part of how the entry is referred to — in a preview URL, or in another entry’s\n * 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 * 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 a nested collection’s tree, which is what the folder\n * route browses. A folder is there as long as it holds an entry, directly or further down; the\n * collection’s root folder is always there, even while the collection is still 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 (!isNestedCollection(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 * nested collection. Only the immediate children of the folder are listed, because the deeper\n * 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 nested collection.\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","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 * Cache of {@link Intl.ListFormat} instances, keyed by `\"${locale}|${serializedOptions}\"`.\n * @type {Map<string, Intl.ListFormat>}\n */\nconst listFormatterCache = new Map();\n\n/**\n * Get a simple list formatter.\n * @param {InternalLocaleCode} locale Locale code.\n * @param {Partial<Intl.ListFormatOptions>} options Format options.\n * @returns {Intl.ListFormat} 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(\n    listFormatterCache,\n    cacheKey,\n    () => new Intl.ListFormat(getCanonicalLocale(locale), effectiveOptions),\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 { ESCAPED_PLACEHOLDER_REGEX } from '$lib/services/common/template/constants';\nimport { warnDeprecation } from '$lib/services/config/deprecations';\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 nested collection. `undefined` for a regular collection, where an entry is always a direct\n * 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 = escapeRegExp(subPath).replace(ESCAPED_PLACEHOLDER_REGEX, '[^/]+?');\n    const fileMatcher = `${escapedSubPath}${indexAlternative}`;\n\n    if (nestedDepth === undefined) {\n      entryMatcher = fileMatcher;\n    } else {\n      // In a nested collection, the `path` option says where an entry sits within the folder\n      // holding it, not within the collection folder, so any number of folders can come first —\n      // 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 nested collection.\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  const localeMatcher = `(?<locale>${allLocales.join('|')})`;\n  const joinedNonDefaultLocales = allLocales.filter((locale) => locale !== defaultLocale).join('|');\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      : `\\\\.(?:${allLocales.join('|')})`;\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  // @todo Remove the option prior to the 1.0 release.\n  if (yamlQuote !== undefined) {\n    warnDeprecation('yaml_quote');\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 { warnDeprecation } from '$lib/services/config/deprecations';\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 * 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 (\n    structureMap.i18nMultiFile || structureMap.i18nMultiFolder || structureMap.i18nMultiRootFolder\n  );\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  // @todo Remove the option prior to the 1.0 release.\n  if (config?.save_all_locales !== undefined) {\n    warnDeprecation('save_all_locales');\n  }\n\n  if (omitDefaultLocaleLegacy !== undefined) {\n    warnDeprecation('omit_default_locale_from_filename');\n  }\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  if (structure === 'multiple_folders_i18n_root') {\n    warnDeprecation('multiple_folders_i18n_root');\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 { _ } 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 { 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(({ multiple, name }) =>\n      // If `multiple` is true, append `.*` to the name to indicate that it’s an array\n      multiple ? `${name}.*` : 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","import { cmsConfig } from '$lib/services/config';\nimport { allEntries, allEntryFolders } from '$lib/services/contents';\nimport { getCollection, getValidCollections } from '$lib/services/contents/collection';\nimport { getValidCollectionFiles } from '$lib/services/contents/collection/predicates';\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  if (!_collection || !('_fileMap' in _collection)) {\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.\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(\n    ({ _file, _i18n }) => _file.fullPath === entry.locales[_i18n.defaultLocale]?.path,\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  const validPaths = new Set(Object.values(folderInfo.filePathMap));\n\n  return allEntries.current.find((entry) =>\n    Object.values(entry.locales).some(({ path }) => validPaths.has(path)),\n  );\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","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 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","import { isObject } from '@sveltia/utils/object';\nimport { compare } from '@sveltia/utils/string';\nimport { unflatten } from 'flat';\n\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 * 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 (isObject(value) && [Object.prototype, null].includes(Object.getPrototypeOf(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 * 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.\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.\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  if (!Object.keys(map).some((key) => key.split('.').some(isNumericStringKey))) {\n    return unflatten(map);\n  }\n\n  return restoreStringKeys(unflatten(map, { transformKey: prefixStringKey }));\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  (isObject(value) &&\n    [Object.prototype, null].includes(Object.getPrototypeOf(value)) &&\n    !Object.keys(value).length);\n","import { isObject } from '@sveltia/utils/object';\nimport { flatten } from 'flat';\n\nimport { getKeysByPrefix, isKeyPathWithin } from '$lib/services/contents/entry/key-paths';\nimport { 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  ...Object.fromEntries(\n    Object.entries(flatten(value)).map(([key, val]) => [`${keyPath}.${key}`, val]),\n  ),\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 * 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 { cmsConfig } from '$lib/services/config';\n\n/**\n * @import { MediaField, MediaLibraries, MediaLibrary } from '$lib/types/public';\n */\n\n/**\n * Helper to check `multiple` option in media libraries config.\n * @param {MediaLibraries | undefined} mediaLibraries Media libraries 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 {MediaLibrary | undefined} mediaLibrary Media 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","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 * 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`\n  const factor = 10 ** decimals;\n\n  return Math.round(number * factor) / factor;\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 * 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 * Regular expression to match the list key path, e.g. `field.0`, `field.1`, etc.\n * @type {RegExp}\n */\nexport const LIST_KEY_PATH_REGEX = /\\.\\d+$/;\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 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","/*!\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// >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 /* - */)) { /* no-op */ }\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","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","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 * Front matter format detected in each file of a collection in the `frontmatter` format, keyed by\n * file path. Such a collection reads YAML, TOML and JSON front matter alike, and an existing file\n * is saved back in the format it was read in; only a new file gets YAML front matter.\n * @type {Map<string, FrontMatterFormat>}\n */\nexport const detectedFrontMatterFormats = new Map();\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.\n * @param {object} args Arguments.\n * @param {FileConfig} args._file Configuration of the collection’s files.\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, which takes over the detected format,\n * so the file keeps it once it has been renamed.\n * @returns {FileConfig} Configuration.\n */\nexport const getSavedFileConfig = ({ _file, previousPath, path }) => {\n  if (_file.format !== 'frontmatter') {\n    return _file;\n  }\n\n  const format = previousPath ? detectedFrontMatterFormats.get(previousPath) : undefined;\n\n  if (!format) {\n    return _file;\n  }\n\n  detectedFrontMatterFormats.set(path, format);\n\n  return {\n    ..._file,\n    format,\n    fmDelimiters: _file.fmDelimiters ?? FRONTMATTER_DELIMITER_MAP[format],\n  };\n};\n","import { toRaw } from '@sveltia/utils/object';\nimport { escapeRegExp } from '@sveltia/utils/string';\nimport { parse as libParseTOML } from 'smol-toml';\nimport { parse as libParseYAML } 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 { FRONTMATTER_FORMATS } from '$lib/services/contents/file/constants';\nimport { detectedFrontMatterFormats } from '$lib/services/contents/file/detected-formats';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import {\n * BaseEntryListItem,\n * InternalCollection,\n * InternalCollectionFile,\n * } from '$lib/types/private';\n * @import { FrontMatterFormat } from '$lib/types/public';\n */\n\n/**\n * Parse a JSON document using the built-in method.\n * @param {string} str JSON document.\n * @returns {any} Parsed object.\n */\nexport const parseJSON = (str) => JSON.parse(str);\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.\n * @param {string} str TOML document.\n * @returns {any} Parsed object.\n */\nexport const parseTOML = (str) => toRaw(libParseTOML(str));\n\n/**\n * Parse a YAML document using a library.\n * @param {string} str YAML document.\n * @param {object} [options] Parsing options.\n * @returns {any} Parsed object.\n */\nexport const parseYAML = (str, options) => libParseYAML(str, options);\n\n/**\n * Detect the Markdown front matter serialization format by checking a delimiter in the content.\n * @param {string} text File content.\n * @returns {FrontMatterFormat} Determined format.\n */\nexport const detectFrontMatterFormat = (text) => {\n  if (text.startsWith('+++')) {\n    return 'toml-frontmatter';\n  }\n\n  if (text.startsWith('{')) {\n    return 'json-frontmatter';\n  }\n\n  return 'yaml-frontmatter';\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 * @returns {any} Parsed object.\n */\nconst parseJSONFrontMatterHead = (head) => {\n  const trimmedHead = head.trim();\n\n  return parseJSON(trimmedHead.startsWith('{') ? trimmedHead : `{${trimmedHead}}`);\n};\n\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.\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 * @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 = ({ collection, collectionFile, isIndexFile, format, text }) => {\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] = (_format === 'frontmatter'\n    ? getFrontMatterDelimiters({ format, delimiter: fmDelimiters })\n    : fmDelimiters) ?? ['---', '---'];\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.\n  const regex = getOrCreate(\n    frontMatterRegexCache,\n    cacheKey,\n    () => new RegExp(`^${sd}\\n(?:(?<head>[\\\\s\\\\S]*?)\\n)?${ed}(?:\\n(?<body>[\\\\s\\\\S]*))?$`, 's'),\n  );\n\n  const groups =\n    (format === 'json-frontmatter' && startDelimiter === '{' && endDelimiter === '}'\n      ? text.match(DOUBLE_BRACE_JSON_FRONT_MATTER_REGEX)?.groups\n      : undefined) ?? text.match(regex)?.groups;\n\n  if (!groups) {\n    // Support Markdown without a front matter block, particularly for VitePress\n    // The text can be an empty string, but it’s okay to return an empty body\n    return { [bodyKey]: text };\n  }\n\n  const { head = '', body } = groups;\n  let parsedHead = {};\n\n  if (format === 'yaml-frontmatter') {\n    parsedHead = parseYAML(head);\n  }\n\n  if (format === 'toml-frontmatter') {\n    parsedHead = parseTOML(head);\n  }\n\n  if (format === 'json-frontmatter') {\n    parsedHead = parseJSONFrontMatterHead(head);\n  }\n\n  if (!parsedHead || typeof parsedHead !== 'object' || Array.isArray(parsedHead)) {\n    parsedHead = {};\n  }\n\n  return {\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.\n    ...(!bodyInline && !(bodyKey in parsedHead) ? { [bodyKey]: body?.replace(/^\\n/, '') } : {}),\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: { 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  // Normalize line breaks\n  text = text.trim().replace(/\\r\\n?/g, '\\n');\n\n  // The collection’s special index file can have a format of its own\n  const isIndexFile = !collectionFile && isCollectionIndexFilePath(collection, path);\n  let { format } = resolveFileConfig({ collection, collectionFile, isIndexFile });\n  const customParser = customFileFormatRegistry.get(format)?.parser;\n\n  if (customParser) {\n    return customParser(text);\n  }\n\n  // Raw format: return the content as-is\n  if (format === 'raw') {\n    return { body: text };\n  }\n\n  try {\n    if (format === 'yaml' || format === 'yml') {\n      return parseYAML(text);\n    }\n\n    if (format === 'toml') {\n      return parseTOML(text);\n    }\n\n    if (format === 'json') {\n      return parseJSON(text);\n    }\n\n    if (format === 'frontmatter') {\n      const detectedFormat = detectFrontMatterFormat(text);\n\n      // Remembered, so the file is saved back in the same format\n      detectedFrontMatterFormats.set(path, detectedFormat);\n      format = detectedFormat;\n    }\n\n    if (FRONTMATTER_FORMATS.includes(/** @type {any} */ (format))) {\n      return parseFrontMatter({\n        collection,\n        collectionFile,\n        isIndexFile,\n        format: /** @type {FrontMatterFormat} */ (format),\n        text,\n      });\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 * 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, a chunk at a time, yielding to the browser between chunks. Use\n * this for a large batch of synchronous work that would otherwise block the main thread for the\n * whole batch. Within a chunk, the tasks run concurrently, so they 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.chunkSize] Number of items to process before yielding.\n */\nexport const runInChunks = async (items, task, { chunkSize = 200 } = {}) => {\n  for (let index = 0; index < items.length; index += chunkSize) {\n    if (index) {\n      // eslint-disable-next-line no-await-in-loop\n      await yieldToMain();\n    }\n\n    // eslint-disable-next-line no-await-in-loop\n    await Promise.all(items.slice(index, index + chunkSize).map((item) => task(item)));\n  }\n};\n","import { generateUUID } from '@sveltia/utils/crypto';\nimport { isObject } from '@sveltia/utils/object';\nimport { escapeRegExp } from '@sveltia/utils/string';\nimport { flatten } from 'flat';\n\nimport { getIndexFile } 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 { parseEntryFile } from '$lib/services/contents/file/parse';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { runInChunks } from '$lib/services/utils/scheduling';\n\n/**\n * @import {\n * BaseEntryListItem,\n * Entry,\n * InternalCollection,\n * InternalEntryCollection,\n * InternalLocaleCode,\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 * Parse the raw content from the file and handle any errors.\n * @param {BaseEntryListItem} file Entry file list item.\n * @param {Error[]} errors List of parse errors.\n * @returns {Promise<RawEntryContent | undefined>} Parsed content or undefined if parsing failed.\n */\nexport const parseFileContent = async (file, errors) => {\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(`${file.path} could not be read.`);\n    }\n\n    return await parseEntryFile(file);\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 * Transform raw content to handle special cases like root List and root KeyValue fields.\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 args = { rawContent, fields, i18nSingleFile };\n\n  // Handle a special case: top-level List field\n  if (hasRootField(fields, 'list')) {\n    return transformRoot({ ...args, validate: Array.isArray });\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 * 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 is a nested collection where 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: flatten(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: flatten(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: flatten(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 */\nexport const prepareEntry = async ({ file, entries, entryMap, errors }) => {\n  const rawContent = await parseFileContent(file, errors);\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 = [],\n    _file: { fullPathRegEx, subPath: subPathTemplate, extension },\n    _i18n: {\n      i18nEnabled,\n      allLocales,\n      defaultLocale,\n      structureMap: {\n        i18nSingleFile,\n        i18nSingleFileDefaultRoot,\n        i18nMultiFile,\n        i18nMultiFolder,\n        i18nMultiRootFolder,\n      },\n      canonicalSlug: { key: canonicalSlugKey },\n    },\n  } = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\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 = i18nSingleFileDefaultRoot\n    ? normalizeDefaultRootContent(rawContent, allLocales, defaultLocale)\n    : rawContent;\n\n  if (!effectiveRawContent) {\n    return;\n  }\n\n  const isI18nSingleFile = i18nSingleFile || i18nSingleFileDefaultRoot;\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 = i18nMultiFile || i18nMultiFolder || i18nMultiRootFolder;\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 * @returns {Promise<{ entries: Entry[], errors: Error[] }>} Entry list and error list.\n */\nexport const prepareEntries = async (entryFiles) => {\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, (file) => prepareEntry({ file, entries, entryMap, errors }));\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","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.\n */\nexport const getEntryFoldersByPath = (path) => {\n  const { fileMap, regexFolders } = getEntryFolderCache();\n\n  return [\n    // A file/singleton collection declares the exact path, so it’s always more specific than an\n    // entry collection, whose folder may happen to contain the same file. This notably applies to\n    // Hugo’s special index file: `content/blog/_index.md` can be declared as a file collection item\n    // while `content/blog` is also an entry collection’s folder\n    ...(fileMap.get(path) ?? []),\n    // Deeper folder paths are more specific, so sort them in descending order\n    ...regexFolders\n      .filter(([, regex]) => regex?.test(path))\n      .map(([folder]) => folder)\n      .sort((a, b) => (b.folderPath ?? '').localeCompare(a.folderPath ?? '')),\n  ];\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 { createFileList, describeFileList } from '$lib/services/backends/process';\nimport { allEntries, dataLoaded, entryParseErrors } from '$lib/services/contents';\nimport { prepareEntries } from '$lib/services/contents/file/process';\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 * Read the asset hashes cached by a previous load.\n * @param {IndexedDB | null | undefined} hashCacheDB Cache store.\n * @returns {Promise<Map<string, AssetHashCacheRecord>>} Cached hashes keyed by file path. Empty if\n * there is no store or it can’t be read; every file is then hashed as usual.\n */\nconst readCachedHashes = async (hashCacheDB) => {\n  try {\n    return new Map((await hashCacheDB?.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 * Update the asset hash cache once the assets have been hashed: save the hashes computed in this\n * load, and drop the records of files that are gone. The records of unchanged files stay as they\n * are, so a load that reused every hash writes nothing.\n * @param {IndexedDB | null | undefined} hashCacheDB Cache store.\n * @param {object} hashes Hashes.\n * @param {Map<string, AssetHashCacheRecord>} hashes.cachedHashes Hashes read from the store.\n * @param {Map<string, AssetHashCacheRecord>} hashes.newHashes Hashes computed in this load.\n * @param {Set<string>} hashes.currentPaths Paths of the asset files found in this load.\n */\nconst updateCachedHashes = async (hashCacheDB, { cachedHashes, newHashes, currentPaths }) => {\n  if (!hashCacheDB) {\n    return;\n  }\n\n  const stalePaths = [...cachedHashes.keys()].filter((path) => !currentPaths.has(path));\n\n  try {\n    if (newHashes.size) {\n      await hashCacheDB.saveEntries([...newHashes]);\n    }\n\n    if (stalePaths.length) {\n      await hashCacheDB.deleteEntries(stalePaths);\n    }\n  } catch (ex) {\n    // The cache is a nicety; the next load hashes the files again\n    // eslint-disable-next-line no-console\n    console.error(ex);\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  const cachedHashesPromise = readCachedHashes(hashCacheDB);\n  const fileList = createFileList(await getAllFiles(rootDirHandle));\n  const { entryFiles, assetFiles, configFiles } = fileList;\n\n  log(`Scanned the directory: ${describeFileList(fileList)}`);\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  const cachedHashes = await cachedHashesPromise;\n  /** @type {Map<string, AssetHashCacheRecord>} */\n  const newHashes = new Map();\n\n  /** @type {Asset[]} */\n  const assets = await mapConcurrently(\n    assetFiles,\n    (fileInfo) => parseAssetFileInfo(fileInfo, { cachedHashes, newHashes }),\n    { concurrency: FILE_PROCESS_CONCURRENCY },\n  );\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\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  await updateCachedHashes(hashCacheDB, {\n    cachedHashes,\n    newHashes,\n    currentPaths: new Set(assetFiles.map(({ path }) => 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`, which\n * browsers treat as a secure context over HTTP.\n * @see https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts\n */\nexport const LOCALHOST_REGEX = /^(.+\\.)?localhost$/;\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 (\n      protocol === 'https:' ||\n      ['127.0.0.1', '[::1]'].includes(hostname) ||\n      LOCALHOST_REGEX.test(hostname)\n    );\n  } catch {\n    return false;\n  }\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 (5xx).\n * Defaults to `1`. Used internally for recursive retries.\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  { responseType = 'json', refreshAccessToken = undefined, retries = 1 } = {},\n) => {\n  /** @type {Response} */\n  let response;\n\n  init.cache = 'no-cache';\n  init.headers = new Headers(init.headers);\n\n  if (init.headers.has('Authorization') && !isSecureURL(url)) {\n    throw new Error('Refusing to send credentials over an insecure connection');\n  }\n\n  if (responseType === 'json') {\n    init.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    init.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  if (responseType === 'raw') {\n    return response;\n  }\n\n  const { ok, status } = response;\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  // Retry the request if the server responded with 502 Bad Gateway, which is a transient error that\n  // may succeed on retry. This is especially relevant for the GitHub GraphQL API, which is known to\n  // occasionally return 502 errors.\n  // @see https://github.com/sveltia/sveltia-cms/issues/695\n  if (status === 502 && retries > 0) {\n    await sleep(1000);\n\n    return sendRequest(url, init, { responseType, refreshAccessToken, retries: retries - 1 });\n  }\n\n  if (status === 401 && refreshAccessToken) {\n    const [scheme] = init.headers.get('Authorization')?.split(' ') ?? ['token'];\n    const { token } = await refreshAccessToken();\n\n    init.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 });\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","import { LOCALHOST_REGEX } 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 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, either `http://localhost` or `http://*.localhost`\n  env.isLocalHost = hostname === '127.0.0.1' || LOCALHOST_REGEX.test(hostname);\n  env.isLocalBackendSupported = 'showDirectoryPicker' in globalThis;\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  getDirectoryHandle,\n  getFileHandle,\n  getHandleByPath,\n} from '$lib/services/backends/fs/shared/handles';\nimport { env } from '$lib/services/user/env.svelte';\nimport { 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 */\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  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  } finally {\n    try {\n      await writer?.close();\n    } catch {\n      //\n    }\n  }\n};\n\n/**\n * Move a file from a previous path to a new path within the file system.\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, basename: oldBasename } = 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    // @ts-ignore\n    await fileHandle.move(await getDirectoryHandle(rootDirHandle, newDirname), newBasename);\n\n    return fileHandle;\n  }\n\n  const newFileHandle = await getFileHandle(rootDirHandle, path);\n  const oldDirHandle = await getDirectoryHandle(rootDirHandle, oldDirname);\n\n  await writeFile(newFileHandle, await fileHandle.getFile());\n  await oldDirHandle.removeEntry(oldBasename);\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.\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 {{ dirname: string | undefined, 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 tempPath = `${dirname ? `${dirname}/` : ''}${TEMP_FILE_PREFIX}${crypto.randomUUID()}`;\n\n      fileHandle = await getFileHandle(rootDirHandle, tempPath);\n      pendingRename = { dirname, 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 { dirname, basename } = pendingRename;\n  const dirHandle = await getDirectoryHandle(rootDirHandle, dirname);\n\n  try {\n    await writeFile(fileHandle, data);\n    await renameFile(fileHandle, 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 * 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 */\nconst isNotFoundError = (ex) => /** @type {DOMException} */ (ex)?.name === 'NotFoundError';\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 dirHandle = await parentHandle.getDirectoryHandle(dirName);\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(dirName);\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.\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(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","export const BACKEND_NAME = 'gitea';\nexport const BACKEND_LABEL = 'Gitea / Forgejo';\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","/**\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 { _ } from '@sveltia/i18n';\n\nimport { user } from '$lib/services/user/account.svelte';\nimport { isSecureURL, sendRequest } from '$lib/services/utils/networking';\n\n/**\n * @import { ApiEndpointConfig, AuthTokens, FetchApiOptions } 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  let token = '';\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  ({ access_token: token, refresh_token: refreshToken } = await response.json());\n\n  // Update the user store with the new token and refresh token\n  user.account = user.account ? { ...user.account, token, refreshToken } : user.account;\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 * 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  } = {},\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  return sendRequest(\n    `${baseURL}${path}`,\n    {\n      method,\n      headers,\n      body,\n      ...(includeCredentials && { credentials: 'include' }),\n    },\n    {\n      responseType,\n      refreshAccessToken: refreshToken\n        ? async () => {\n            const { account } = user;\n\n            // Another request has refreshed the token since this one was sent, which used up the\n            // refresh token if it’s single-use, so take the new token instead of refreshing again\n            if (\n              account?.token &&\n              account.token !== token &&\n              account.refreshToken !== refreshToken\n            ) {\n              return { token: account.token, refreshToken: account.refreshToken };\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 * @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 = {}) => {\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 })\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  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) {\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/gitea/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 Gitea/Forgejo REST API.\n * @param {AuthTokens} tokens Authentication tokens.\n * @returns {Promise<User>} User information.\n * @see https://docs.gitea.com/api/next/#tag/user/operation/userGetCurrent\n */\nexport const getUserProfile = (tokens) =>\n  fetchUserProfile(tokens, BACKEND_NAME, {\n    name: 'full_name',\n    login: 'login',\n    profileURL: 'html_url',\n  });\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 {\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 * 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 * @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 }) => {\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\n    /**\n     * Timer to check if the popup is closed. This doesn’t work with GitLab; `window.closed` will\n     * always be `true`.\n     */\n    const timer =\n      backendName === 'github'\n        ? setInterval(() => {\n            if (authPopup.closed) {\n              controller.abort();\n              clearInterval(timer);\n              reject(createAbortError());\n            }\n          }, 1000)\n        : 0;\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      const provider = backendName;\n\n      // First message\n      if (data === `authorizing:${provider}`) {\n        authPopup.postMessage(data, origin);\n\n        return;\n      }\n\n      // Second message\n      const { result: resultStr } =\n        data.match(`^authorization:${provider}:(success|error):(?<result>.+)`)?.groups ?? {};\n\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      controller.abort();\n      clearInterval(timer);\n      authPopup.close();\n    };\n\n    window.addEventListener('message', handler, { signal: controller.signal });\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} args.authURL Authorization site URL.\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, 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  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('sveltia-cms.auth', {\n    csrfToken,\n    codeVerifier,\n    realAuthURL: `${authURL}?${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  return authorize({\n    backendName,\n    authURL: redirectURL,\n    popup,\n  });\n};\n\n/**\n * Communicate with the window opener as part of {@link finishClientSideAuth}.\n * @param {object} args Options.\n * @param {string} [args.provider] Backend name, e,g. `github`.\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 = ({ provider = 'unknown', token, refreshToken, error, errorCode }) => {\n  const _state = error ? 'error' : 'success';\n  const content = error ? { provider, error, errorCode } : { provider, token, refreshToken };\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 === `authorizing:${provider}`\n    ) {\n      window.opener?.postMessage(\n        `authorization:${provider}:${_state}:${JSON.stringify(content)}`,\n        origin,\n      );\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(`authorizing:${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('sveltia-cms.auth')) ?? {};\n  const provider = backendName;\n  const redirectURL = `${origin}${pathname}`;\n\n  // Remove the temporary secret\n  await LocalStorage.delete('sveltia-cms.auth');\n\n  if (!csrfToken || !codeVerifier || state !== csrfToken) {\n    return sendMessage({\n      provider,\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      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      error: _('sign_in_error.MALFORMED_RESPONSE'),\n      errorCode: 'MALFORMED_RESPONSE',\n    });\n  }\n\n  return sendMessage({ provider, 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  const { code, state } = Object.fromEntries(new URLSearchParams(search));\n\n  if (code && state) {\n    await finishClientSideAuth({ backendName, apiConfig, code, state });\n  } else {\n    const { realAuthURL } = (await LocalStorage.get('sveltia-cms.auth')) ?? {};\n\n    if (realAuthURL) {\n      window.location.href = realAuthURL;\n    }\n  }\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 (backendName === 'gitea' || authType === 'pkce') {\n    const inPopup = window.opener?.origin === window.location.origin && window.name === 'auth';\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 { getUserProfile } from '$lib/services/backends/git/gitea/user';\nimport { signInToBackend } from '$lib/services/backends/git/shared/auth';\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 Gitea/Forgejo.\n * @param {string} repoURL Repository URL, e.g. `https://gitea.com/owner/repo`.\n * @returns {string} URL to create a new PAT.\n */\nexport const getTokenPageURL = (repoURL) => {\n  const { origin } = new URL(repoURL);\n\n  return `${origin}/user/settings/applications`;\n};\n\n/**\n * Sign in with the Gitea/Forgejo REST API.\n * @param {SignInOptions} options Options.\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 signIn = (options) => signInToBackend({ options, getUserProfile });\n\nexport { signOut } from '$lib/services/backends/git/shared/auth';\n","import { _ } from '@sveltia/i18n';\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 * Encode a slash-separated value, such as a file path or a branch name, for use in a URL path,\n * segment by segment. `encodeURI` would leave `#` and `?` as they are, which end the path, so a\n * value containing them would be cut short and the request would address something else — a Git\n * branch name can contain `#`, for example, and `cms/posts/c#` would become `cms/posts/c`.\n * @param {string} path File path or branch name.\n * @returns {string} Encoded value, with the slashes kept.\n */\nexport const encodePath = (path) => path.split('/').map(encodeURIComponent).join('/');\n","import { locale as appLocale, locales as appLocales, dictionary, waitLocale } from '@sveltia/i18n';\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/**\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 _prefs = (await LocalStorage.get(PREFS_STORAGE_KEY)) ?? {};\n\n      _prefs.apiKeys ??= {};\n      _prefs.useDraftBackup ??= true;\n      _prefs.closeOnSave ??= true;\n      _prefs.closeWithEscape ??= true;\n      _prefs.underlineLinks ??= true;\n      _prefs.beta ??= false;\n      _prefs.devModeEnabled ??= 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      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, beta = false, 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      beta,\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\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      if (locale in dictionary) {\n        appLocale.set(locale);\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\n        prefs.locale = previousLocale;\n      }\n    });\n  });\n});\n","import { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport { getRootDir } from '$lib/services/backends/root-dir';\nimport { prefs } from '$lib/services/user/prefs.svelte';\n\n/**\n * @import { RepositoryBaseURLs, RepositoryInfo } 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 for the repository from the REST API root URL.\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 * @param {string} repoPath Repository path, e.g., `owner/repo`.\n * @returns {string} Base URL for the repository.\n */\nexport const getRepoURL = (restApiRoot, repoPath) => {\n  const baseURL =\n    restApiRoot === 'https://api.github.com'\n      ? 'https://github.com'\n      : restApiRoot.replace(API_PATH_REGEX, '$<origin>$<path>');\n\n  return `${baseURL}/${repoPath}`;\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}/${encodePath(rootDir)}`,\n    blobBaseURL: `${urls.blobBaseURL}/${encodePath(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 {(repoURL: string) => string} args.getTokenPageURL Function to get the URL of the page\n * for creating a new Personal Access Token.\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  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(repoURL),\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 } 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  applyDefaultBranch,\n  REPOSITORY_INFO_PLACEHOLDER,\n} from '$lib/services/backends/git/shared/repository';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport { user } from '$lib/services/user/account.svelte';\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 * Cache for repository information to avoid multiple API calls. The information includes the\n * signed-in user’s permissions, so it’s kept along with the ID of the user it was fetched for. The\n * request is cached rather than its result, so callers asking at the same time, like the access\n * check and the default branch lookup, share one request.\n * @type {{ userId: number | undefined, promise: Promise<Record<string, any>> } | null}\n */\nlet repositoryInfoCache = null;\n/**\n * Last response of the branch endpoint, along with the branch and user it was fetched for. The\n * last commit and the user’s branch permissions come from the same endpoint, and the permissions\n * are checked right after the last commit is fetched on the initial load, so they’re read from\n * here rather than requested again.\n * @type {{ branch: string, userId: number | undefined, result: Record<string, any> } | undefined}\n */\nlet lastBranchResponse;\n\n/**\n * Reset the repository info cache. Used for testing.\n */\nexport const resetRepositoryInfoCache = () => {\n  repositoryInfoCache = null;\n  lastBranchResponse = undefined;\n};\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 = (repoURL, branch) => ({\n  treeBaseURL: branch ? `${repoURL}/src/branch/${branch}` : repoURL,\n  blobBaseURL: branch ? `${repoURL}/src/branch/${branch}` : '',\n  commitBaseURL: `${repoURL}/commit`,\n});\n\n/**\n * Get the repository information.\n * @returns {Promise<Record<string, any>>} Repository information.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGet\n */\nexport const getRepositoryInfo = () => {\n  const { owner, repo } = repository;\n  const userId = user.account?.id;\n\n  // Another user may have signed in on the same page, e.g. after a read-only account was refused,\n  // and their permissions are not the previous user’s\n  if (repositoryInfoCache && repositoryInfoCache.userId === userId) {\n    return repositoryInfoCache.promise;\n  }\n\n  const promise = /** @type {Promise<Record<string, any>>} */ (\n    fetchAPI(`/repos/${owner}/${repo}`)\n  ).catch((ex) => {\n    // A failure isn’t remembered, so a later call can try again\n    if (repositoryInfoCache?.promise === promise) {\n      repositoryInfoCache = null;\n    }\n\n    throw ex;\n  });\n\n  repositoryInfoCache = { userId, promise };\n\n  return promise;\n};\n\n/**\n * Fetch the configured branch, which includes its last commit and the signed-in user’s permissions\n * on it. The response is kept for {@link checkBranchAccess}.\n * @returns {Promise<Record<string, any>>} Branch information.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetBranch\n */\nexport const fetchBranch = async () => {\n  const { owner, repo } = repository;\n  const branch = String(repository.branch);\n  const userId = user.account?.id;\n\n  const result = /** @type {Record<string, any>} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/branches/${encodePath(branch)}`)\n  );\n\n  lastBranchResponse = { branch, userId, result };\n\n  return result;\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.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGet\n */\nexport const checkRepositoryAccess = async () => {\n  const { repo } = repository;\n\n  try {\n    const { permissions } = await getRepositoryInfo();\n\n    if (!permissions?.push) {\n      throw createLocalizedError(NOT_COLLABORATOR_ERROR_MESSAGE, 'repository_no_access', { repo });\n    }\n  } catch (error) {\n    if (error instanceof Error && error.message === NOT_COLLABORATOR_ERROR_MESSAGE) {\n      throw error;\n    }\n\n    throw createLocalizedError('Failed to check repository access', 'repository_not_found', {\n      repo,\n    });\n  }\n};\n\n/**\n * Check if the user can push to and merge into the configured branch, and record it in\n * {@link lockedBranch} and {@link mergeLockedBranch}. Write access is enough to sign in, but a\n * protected branch may only allow some users to push or merge, in which case everything that would\n * fail is made read-only or hidden up front. A failed request leaves the branch writable, as\n * Gitea/Forgejo still refuses a push or merge the user isn’t allowed to make.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetBranch\n */\nexport const checkBranchAccess = async () => {\n  const { owner, repo, branch } = repository;\n  // Read the response the last commit was just fetched with, if it’s for this branch and user. It’s\n  // only used once, so a later check doesn’t go by permissions fetched long ago\n  const cached = lastBranchResponse;\n\n  lastBranchResponse = undefined;\n\n  await recordBranchAccess(branch, async (_branch) => {\n    const result = /** @type {{ user_can_push?: boolean, user_can_merge?: boolean }} */ (\n      cached?.branch === _branch && cached.userId === user.account?.id\n        ? cached.result\n        : await fetchAPI(`/repos/${owner}/${repo}/branches/${encodePath(_branch)}`)\n    );\n\n    return { canPush: result.user_can_push, canMerge: result.user_can_merge };\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 * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGet\n */\nexport const fetchDefaultBranchName = async () => {\n  // A request that fails means the repository could not be read at all, which `applyDefaultBranch`\n  // reports as a missing repository; a repository that was read but has no default branch is empty\n  const info = await getRepositoryInfo().catch(() => undefined);\n\n  return applyDefaultBranch(repository, {\n    found: !!info,\n    branch: info?.default_branch,\n    getBaseURLs,\n  });\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { MIN_FORGEJO_VERSION, MIN_GITEA_VERSION } from '$lib/services/backends/git/gitea/constants';\nimport { repository } from '$lib/services/backends/git/gitea/repository';\nimport { apiConfig, fetchAPI } from '$lib/services/backends/git/shared/api';\nimport { sendRequest } from '$lib/services/utils/networking';\n\n/**\n * Flag to indicate if the backend is Forgejo. This is used to determine which API endpoints to use,\n * as Gitea and Forgejo have different endpoints for fetching file contents.\n * @type {{ isForgejo: boolean }}\n */\nexport const instance = { isForgejo: false };\n\n/**\n * Gitea’s first major version after 1.x. Gitea jumped from 1.27 to 28.0, while Forgejo, which has\n * used its own major versions since 7.0, won’t reach 28 for years.\n * @see https://blog.gitea.com/tags/release\n * @see https://forgejo.org/releases/\n */\nconst FIRST_NEW_GITEA_MAJOR_VERSION = 28;\n\n/**\n * Check if the instance is Forgejo by requesting the Forgejo-specific version API endpoint, which\n * Gitea doesn’t have. The endpoint lives next to the regular API root, e.g. `/api/forgejo/v1` next\n * to `/api/v1`, and doesn’t require authentication.\n * @param {number} version Major and minor version number reported by the regular API.\n * @returns {Promise<boolean>} Whether the instance is Forgejo.\n * @see https://codeberg.org/api/swagger#/miscellaneous/getVersion\n */\nconst probeForgejo = async (version) => {\n  const { restBaseURL, includeCredentials } = apiConfig;\n\n  try {\n    const url = new URL('../forgejo/v1/version', `${restBaseURL}/`).href;\n    const init = includeCredentials ? { credentials: /** @type {const} */ ('include') } : {};\n\n    const { ok, status, redirected } = /** @type {Response} */ (\n      await sendRequest(url, init, { responseType: 'raw' })\n    );\n\n    // Only a 404 shows that the endpoint is missing; any other error, e.g. 401 on an instance that\n    // requires sign-in, is inconclusive, and so is a redirect, e.g. to a sign-in page\n    if (!redirected && (ok || status === 404)) {\n      return ok;\n    }\n  } catch {\n    // The request failed, e.g. because of a CORS restriction\n  }\n\n  // Fall back to the version number\n  return version < FIRST_NEW_GITEA_MAJOR_VERSION;\n};\n\n/**\n * Check if the version of the user’s Gitea/Forgejo instance is supported. The API endpoint requires\n * authentication, meaning the user must be signed in before calling this function.\n * @throws {Error} When the detected version is unsupported.\n * @see https://docs.gitea.com/api/next/#tag/miscellaneous/operation/getVersion\n */\nexport const checkInstanceVersion = async () => {\n  const { version: versionStr } = /** @type {{ version: string }} */ (await fetchAPI('/version'));\n  const version = Number.parseFloat(versionStr);\n\n  // Forgejo version strings typically look like `13.0.3+gitea-1.22.0`, while Gitea’s look like\n  // `1.24.0`, `1.27.0+dev-954-g1f3981a301` or `28.0.0`. However, depending on the installation, the\n  // fork indicator may not be included (I’ve got `13.0.3` with Homebrew), and both Forgejo and\n  // Gitea 28+ use major versions above 1, so ask the instance when the version string is ambiguous\n  const isForgejo =\n    /\\+gitea-/.test(versionStr ?? '') || (version >= 2 && (await probeForgejo(version)));\n\n  const name = isForgejo ? 'Forgejo' : 'Gitea';\n  const minVersion = isForgejo ? MIN_FORGEJO_VERSION : MIN_GITEA_VERSION;\n\n  Object.assign(instance, { isForgejo });\n  Object.assign(repository, { label: name });\n\n  if (version < minVersion) {\n    throw new Error(`Unsupported ${name} version`, {\n      cause: new Error(\n        _('backend_unsupported_version', {\n          values: { name, version: minVersion },\n        }),\n      ),\n    });\n  }\n};\n","import { sleep } from '@sveltia/utils/misc';\n\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { cmsConfig } from '$lib/services/config';\nimport {\n  ENTRY_ALREADY_PUBLISHED,\n  forkedRepository,\n  openAuthoring,\n  openAuthoringInitialized,\n  requestForkPermission,\n} from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * CommitOptions,\n * CommitResults,\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']} name Backend name, e.g. `github`.\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\n  return backend?.name === name && 'open_authoring' in backend && backend.open_authoring === true;\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 * 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 * 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 attempts remaining, used for the recursive retry.\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 checkFork();\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  if (attemptsLeft <= 1) {\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  await sleep(FORK_POLL.interval);\n  await pollForFork({ repoPath, checkFork, attemptsLeft: attemptsLeft - 1 });\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 * 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 * 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 }) =>\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 });\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 { instance } from '$lib/services/backends/git/gitea/instance';\nimport {\n  fetchDefaultBranchName,\n  getRepositoryInfo,\n  repository,\n} from '$lib/services/backends/git/gitea/repository';\nimport { fetchAPI } 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  ensureForkPermission,\n  isOpenAuthoringConfiguredFor,\n  resolveWorkflowRepository,\n  runOpenAuthoringSetUp,\n} from '$lib/services/backends/git/shared/fork';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport { user } from '$lib/services/user/account.svelte';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { RepositoryPath, User } from '$lib/types/private';\n */\n\n/**\n * Maximum number of the user’s forks to look through for one of the configured repository, when it\n * isn’t at the name it was given by default. A contributor rarely has more than a handful.\n */\nconst MAX_FORKS = 50;\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('gitea');\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 * Parse a repository returned by the REST API into the owner and name pair the CMS works with.\n * @param {Record<string, any>} result Repository.\n * @returns {RepositoryPath} Repository owner and name.\n */\nconst toRepositoryPath = ({ full_name: fullName }) => {\n  const [owner, repo] = fullName.split('/');\n\n  return { owner, repo };\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. The repository reports the authenticated user’s own permissions. A private\n * repository answers a request from someone without access with a 404 rather than a 403, so its\n * existence isn’t leaked; either way, being unable to read it is a dead end rather than a reason to\n * fall back to a fork.\n * @returns {Promise<{ canWrite: 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 * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGet\n */\nexport const fetchRepositoryAccess = async () => {\n  const { owner, repo } = repository;\n  const repoPath = `${owner}/${repo}`;\n  /** @type {Record<string, any>} */\n  let result;\n\n  try {\n    result = await getRepositoryInfo();\n  } catch (/** @type {any} */ ex) {\n    // The shared message is what the sign-in flow looks for to drop the cached credentials, the\n    // same as the regular access check does, so the user gets the sign-in form rather than the\n    // same error on every reload\n    if ([403, 404].includes(ex.cause?.status)) {\n      throw createLocalizedError(NOT_COLLABORATOR_ERROR_MESSAGE, 'repository_no_access', {\n        repo: repoPath,\n      });\n    }\n\n    // A rate limit or an outage leaves the question unanswered. Reading that as “no write access”\n    // would send a maintainer down the fork path over something passing, and offer to create a\n    // copy of a repository they can already write to, so make the failure visible instead\n    throw createLocalizedError(\n      'Failed to check the repository permission.',\n      'open_authoring.permission_check_failed',\n      { repo: repoPath },\n    );\n  }\n\n  return { canWrite: !!result.permissions?.push };\n};\n\n/**\n * Look for the fork at the name the instance gives it by default, which is the parent’s. This is\n * where it is unless the contributor renamed it. A repository that happens to share the name but\n * isn’t a fork of the configured one is ignored.\n * @returns {Promise<RepositoryPath | undefined>} The fork, or `undefined` if it isn’t there.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGet\n */\nexport const fetchForkByName = async () => {\n  const { owner, repo } = repository;\n  const userName = /** @type {string} */ (user.account?.login);\n\n  const response = /** @type {Response} */ (\n    await fetchAPI(`/repos/${encodeURIComponent(userName)}/${repo}`, { responseType: 'raw' })\n  );\n\n  if (!response.ok) {\n    return undefined;\n  }\n\n  const result = await response.json();\n  const parent = result.parent?.full_name?.toLowerCase();\n\n  if (!result.fork || parent !== `${owner}/${repo}`.toLowerCase()) {\n    return undefined;\n  }\n\n  // The instance 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  if (result.owner?.login?.toLowerCase() !== userName.toLowerCase()) {\n    return undefined;\n  }\n\n  return toRepositoryPath(result);\n};\n\n/**\n * Look through the forks the signed-in user owns for one of the configured repository, wherever\n * it’s named. This only runs when {@link fetchForkByName} came up empty, so its worst case is the\n * behavior without it: no fork found, and the contributor asked whether to make one.\n * @returns {Promise<RepositoryPath | undefined>} The fork, or `undefined` if there is none.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoSearch\n */\nexport const fetchForkBySearch = async () => {\n  const { owner, repo } = repository;\n  // Nothing here runs before the user has signed in\n  const { id, login } = /** @type {User} */ (user.account);\n  const repoPath = `${owner}/${repo}`.toLowerCase();\n\n  try {\n    const { data = [] } = /** @type {{ data?: Record<string, any>[] }} */ (\n      await fetchAPI(`/repos/search?uid=${id}&exclusive=true&mode=fork&limit=${MAX_FORKS}`)\n    );\n\n    const result = data.find(\n      (item) =>\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        item.owner?.login === login && item.parent?.full_name?.toLowerCase() === repoPath,\n    );\n\n    return result ? toRepositoryPath(result) : undefined;\n  } catch {\n    return undefined;\n  }\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()) ?? fetchForkBySearch();\n\n/**\n * Fetch whether the instance allows repositories to be forked. Forgejo can turn forking off\n * altogether and says so in its repository settings, while Gitea has no such setting. A failure\n * leaves the fork request to say whether it’s allowed.\n * @returns {Promise<boolean>} `false` if forking is turned off.\n * @see https://codeberg.org/api/swagger#/settings/getGeneralRepositorySettings\n */\nexport const fetchForkingAllowed = async () => {\n  if (!instance.isForgejo) {\n    return true;\n  }\n\n  try {\n    const { forks_disabled: disabled } = /** @type {{ forks_disabled?: boolean }} */ (\n      await fetchAPI('/settings/repository')\n    );\n\n    return !disabled;\n  } catch {\n    return true;\n  }\n};\n\n/**\n * Check whether the signed-in user already has a repository of the given name, which is what stops\n * a fork from being created at the default name.\n * @param {string} name Repository name.\n * @returns {Promise<boolean>} `true` if the name is taken.\n */\nconst isRepositoryNameTaken = async (name) => {\n  const userName = /** @type {string} */ (user.account?.login);\n\n  const response = /** @type {Response} */ (\n    await fetchAPI(`/repos/${encodeURIComponent(userName)}/${name}`, { responseType: 'raw' })\n  );\n\n  return response.ok;\n};\n\n/**\n * Fork the configured repository onto the signed-in user’s account. Unlike GitHub, the instance\n * copies the repository before answering, so the fork can be used as soon as the request returns.\n * @returns {Promise<RepositoryPath>} The new fork.\n * @throws {Error} When the fork could not be created.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/createFork\n */\nexport const createFork = async () => {\n  const { owner, repo } = repository;\n  const repoPath = `${owner}/${repo}`;\n  const endpoint = `/repos/${owner}/${repo}/forks`;\n  /** @type {Record<string, any>} */\n  let result;\n\n  try {\n    result = /** @type {Record<string, any>} */ (\n      await fetchAPI(endpoint, { method: 'POST', body: {} })\n    );\n  } catch (/** @type {any} */ ex) {\n    // The instance doesn’t pick another name when the contributor already has an unrelated\n    // repository of the same name, the way GitHub does, so give it one. Any other failure is real:\n    // a fork of the repository already exists, or forking is turned off on the instance\n    if (ex.cause?.status !== 409 || !(await isRepositoryNameTaken(repo))) {\n      // eslint-disable-next-line no-console\n      console.error('Failed to fork the repository.', ex);\n\n      throw createLocalizedError('Failed to fork the repository.', 'open_authoring.fork_failed', {\n        repo: repoPath,\n      });\n    }\n\n    try {\n      result = /** @type {Record<string, any>} */ (\n        await fetchAPI(endpoint, { method: 'POST', body: { name: `${owner}-${repo}` } })\n      );\n    } catch (/** @type {any} */ retryEx) {\n      // eslint-disable-next-line no-console\n      console.error('Failed to fork the repository.', retryEx);\n\n      throw createLocalizedError('Failed to fork the repository.', 'open_authoring.fork_failed', {\n        repo: repoPath,\n      });\n    }\n  }\n\n  return toRepositoryPath(result);\n};\n\n/**\n * Find out whether Forgejo can bring the fork’s copy of the given branch up to date. Forgejo only\n * fast-forwards, and refuses a sync both when the fork has commits of its own on the branch and\n * when there’s nothing to sync, so it’s asked first rather than sent a request it would refuse on\n * every sign-in with an up-to-date fork.\n * @param {RepositoryPath} fork Fork to check.\n * @param {string} branch Branch name.\n * @returns {Promise<'current' | 'behind' | 'diverged'>} Where the fork’s copy stands.\n * @see https://codeberg.org/api/swagger#/repository/repoSyncForkBranchInfo\n */\nconst fetchForgejoSyncState = async ({ owner, repo }, branch) => {\n  const {\n    allowed,\n    fork_commit: forkCommit,\n    base_commit: baseCommit,\n  } = /** @type {{ allowed?: boolean, fork_commit?: string, base_commit?: string }} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/sync_fork/${encodePath(branch)}`)\n  );\n\n  if (forkCommit && forkCommit === baseCommit) {\n    return 'current';\n  }\n\n  return allowed ? 'behind' : 'diverged';\n};\n\n/**\n * Bring the fork’s copy of the configured branch up to date with the configured repository, so a\n * new workflow branch starts from what’s currently on the site and the resulting pull request only\n * contains the entry being edited. The two services ask for this differently: Gitea names the\n * branch in the body, while Forgejo names it in the path and is asked beforehand whether it can do\n * it at all. A failure is logged rather than raised: a fork that has drifted still works, it just\n * makes for a noisier pull request.\n * @param {RepositoryPath} fork Fork to update.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoMergeUpstream\n * @see https://codeberg.org/api/swagger#/repository/repoSyncForkBranch\n */\nexport const syncFork = async (fork) => {\n  const { owner, repo } = fork;\n  // The branch is resolved before the fork is set up\n  const { branch } = /** @type {{ branch: string }} */ (repository);\n  /** @type {Response | undefined} */\n  let response;\n\n  try {\n    if (instance.isForgejo) {\n      const state = await fetchForgejoSyncState(fork, branch);\n\n      if (state === 'current') {\n        return;\n      }\n\n      // The fork has commits of its own on the branch, which is a state the CMS can’t resolve on\n      // the contributor’s behalf\n      if (state === 'diverged') {\n        // eslint-disable-next-line no-console\n        console.warn(\n          `The ${owner}/${repo} fork could not be fast-forwarded to the upstream repository.`,\n        );\n\n        return;\n      }\n    }\n\n    response = /** @type {Response} */ (\n      await fetchAPI(\n        instance.isForgejo\n          ? `/repos/${owner}/${repo}/sync_fork/${encodePath(branch)}`\n          : `/repos/${owner}/${repo}/merge-upstream`,\n        {\n          method: 'POST',\n          ...(instance.isForgejo ? {} : { body: { branch } }),\n          responseType: 'raw',\n        },\n      )\n    );\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.warn(`Failed to sync the ${owner}/${repo} fork with the upstream repository.`, ex);\n\n    return;\n  }\n\n  // Gitea refuses the request when the fork’s commits conflict with the upstream ones, which it\n  // can’t merge\n  if (!response.ok) {\n    // eslint-disable-next-line no-console\n    console.warn(\n      `The ${owner}/${repo} fork could not be fast-forwarded to the upstream repository.`,\n    );\n  }\n};\n\n/**\n * Make sure the fork has its own copy of the configured branch, which is what a workflow branch is\n * created from. A fork that predates the branch — the configured repository renamed its default\n * branch since, say — has no such copy, and the instance can’t be asked to add one, so the\n * contributor has to bring the fork up to date themselves before they can save anything.\n * @param {RepositoryPath} fork Fork to check.\n * @throws {Error} When the fork doesn’t have the branch.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetBranch\n */\nexport const checkForkBranch = async ({ owner, repo }) => {\n  // The branch is resolved before this runs\n  const { branch } = /** @type {{ branch: string }} */ (repository);\n\n  const response = /** @type {Response} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/branches/${encodePath(branch)}`, {\n      responseType: 'raw',\n    })\n  );\n\n  if (!response.ok) {\n    throw createLocalizedError(\n      'The fork does not have the configured branch',\n      'open_authoring.fork_branch_missing',\n      { fork: `${owner}/${repo}`, branch, repo: `${repository.owner}/${repository.repo}` },\n    );\n  }\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.\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  const { canWrite } = await fetchRepositoryAccess();\n\n  // A maintainer keeps working on the configured repository, as if Open Authoring was off\n  if (canWrite) {\n    return;\n  }\n\n  const { owner, repo } = repository;\n\n  // Syncing the fork needs the branch name, which is otherwise resolved later in the data load\n  if (!repository.branch) {\n    await fetchDefaultBranchName();\n  }\n\n  const existingFork = await fetchFork();\n\n  if (existingFork) {\n    await syncFork(existingFork);\n    await checkForkBranch(existingFork);\n    forkedRepository.current = existingFork;\n\n    return;\n  }\n\n  await ensureForkPermission({\n    repoPath: `${owner}/${repo}`,\n    allowForking: await fetchForkingAllowed(),\n  });\n\n  forkedRepository.current = await createFork();\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 { 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 * 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 = (\n  changes,\n  { commitType = 'update', collection, skipCI = undefined },\n) => {\n  const {\n    commit_messages: customCommitMessages = {},\n    skip_ci: skipCIEnabled,\n    automatic_deployments: autoDeploy,\n  } = /** @type {GitBackend} */ (cmsConfig.current?.backend ?? {});\n\n  const { email = '', login = '', name = '' } = /** @type {User} */ (user.account);\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 = { 'author-email': email, 'author-login': login, 'author-name': name };\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  // 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, ...authorValues },\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. To avoid unexpected\n  // data retention, deployments for deletion commits are not skipped.\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 (\n    !['delete', 'deleteMedia'].includes(commitType) &&\n    // Cannot use the `skipCIEnabled` store here because it leads to an uninitialized store error\n    (skipCI ?? (skipCIEnabled === true || autoDeploy === false))\n  ) {\n    message = `[skip ci] ${message}`;\n  }\n\n  return message;\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 * 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 * 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","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","import { encodeBase64 } from '@sveltia/utils/file';\n\nimport { getWorkflowRepository } from '$lib/services/backends/git/gitea/fork';\nimport { fetchBranch, repository } from '$lib/services/backends/git/gitea/repository';\nimport { fetchAPI } from '$lib/services/backends/git/shared/api';\nimport {\n  assertBranchNotMoved,\n  createCommitMessage,\n  fetchPerPathCommits,\n} from '$lib/services/backends/git/shared/commits';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { checkDirectCommitAllowed } from '$lib/services/backends/git/shared/fork';\nimport { repositoryHead } from '$lib/services/backends/git/shared/head';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport { user } from '$lib/services/user/account.svelte';\n\n/**\n * @import { CommitOptions, CommitResults, FileChange, FileCommit, User } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} CommitResponse\n * @property {object} commit Commit information, including the commit SHA and creation date.\n * @property {string} commit.sha Commit SHA.\n * @property {string} commit.created Commit creation date in ISO format.\n * @property {({ path: string, sha: string } | null)[]} files List of saved files, each with its\n * path and SHA. It can be `null` if the file was deleted.\n */\n\n/**\n * Fetch the last commit on the repository.\n * @returns {Promise<{ hash: string, message: string }>} Commit’s SHA-1 hash and message.\n * @throws {Error} When the branch could not be found, or the request failed.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetSingleCommit\n */\nexport const fetchLastCommit = async () => {\n  const { repo, branch } = repository;\n\n  try {\n    const {\n      commit: { id: hash, message },\n    } = /** @type {{ commit: { id: string, message: string }}} */ (await fetchBranch());\n\n    return { hash, message };\n  } catch (/** @type {any} */ ex) {\n    // Only a 404 means the branch is missing. Anything else, like an expired token or an outage,\n    // would be misreported as a missing branch, so pass it on as is\n    if (ex.cause?.status !== 404) {\n      throw ex;\n    }\n\n    throw createLocalizedError('Failed to retrieve the last commit hash.', 'branch_not_found', {\n      repo,\n      branch,\n    });\n  }\n};\n\n/**\n * Get the blob SHA of a file being updated, moved or deleted, as the user knows it. It normally\n * comes with the change, taken from the file cache or the asset list, but it can be missing, e.g.\n * while the cache is still being written after the site data is shown, or once it’s been cleared.\n * Gitea accepts a change without one whatever the file is now, overwriting someone else’s change,\n * so the SHA is then looked up as of the commit the site data reflects rather than the branch head,\n * which keeps the guard working.\n * @param {FileChange} change File change.\n * @param {string} [workflowBranch] Workflow branch the commit lands on, if it isn’t the configured\n * branch.\n * @returns {Promise<string | undefined>} Blob SHA, or `undefined` for a new file.\n * @throws {Error} When the site data hasn’t been loaded, or the lookup failed.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetContents\n */\nconst getKnownSha = async ({ action, path, previousPath, previousSha }, workflowBranch) => {\n  if (action === 'create' || previousSha) {\n    return previousSha;\n  }\n\n  // A workflow branch has moved on from the configured one, so the file is looked up on the branch\n  // the commit lands on, in the repository it lives in. The Editorial Workflow service resolves\n  // these ahead of the commit, so this is a fallback rather than the usual path\n  const { owner, repo } = workflowBranch ? getWorkflowRepository() : repository;\n  const ref = workflowBranch ?? repositoryHead.current;\n  const knownPath = (action === 'move' && previousPath) || path;\n\n  if (!ref) {\n    throw new Error(`The last known version of ${knownPath} could not be determined.`);\n  }\n\n  const { sha } = /** @type {{ sha: string }} */ (\n    await fetchAPI(\n      `/repos/${owner}/${repo}/contents/${encodePath(knownPath)}?ref=${encodeURIComponent(ref)}`,\n    )\n  );\n\n  return sha;\n};\n\n/**\n * Save entries or assets remotely.\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 * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoChangeFiles\n */\nexport const commitChanges = async (changes, options) => {\n  checkDirectCommitAllowed(options);\n\n  // A workflow branch lives in the contributor’s fork with Open Authoring, while the configured\n  // branch is only ever committed to by someone who can write to the configured repository\n  const { owner, repo } = options.branch ? getWorkflowRepository() : repository;\n  // An Editorial Workflow change lands on a workflow branch rather than the configured one\n  const { branch = repository.branch, startBranch } = options;\n  const commitMessage = createCommitMessage(changes, options);\n  const { name, email } = /** @type {User} */ (user.account);\n  const date = new Date().toJSON();\n\n  // The API has no branch-level guard like GitHub’s `expectedHeadOid`, but an update, a move or a\n  // deletion carries the blob SHA of the file as the user knows it, taken from the cached file list\n  // rather than looked up now, so the commit is refused if someone else has changed the file since.\n  // Gitea doesn’t insist on one, so it’s never left out\n  const files = await Promise.all(\n    changes.map(async (change) => {\n      const { action, path, previousPath, data = '' } = change;\n\n      const [content, sha] = await Promise.all([\n        encodeBase64(data),\n        getKnownSha(change, options.branch),\n      ]);\n\n      return {\n        operation: action === 'move' ? 'update' : action,\n        path,\n        content,\n        from_path: previousPath,\n        sha,\n      };\n    }),\n  );\n\n  // The guard is about the configured branch. A workflow branch is guarded by the Editorial\n  // Workflow service instead, which checks it for someone else’s commit before the save and reads\n  // the blob SHAs at the commit the entry was loaded or saved at\n  const expectedHead = options.branch ? undefined : repositoryHead.current;\n  /** @type {CommitResponse} */\n  let response;\n\n  try {\n    response = /** @type {CommitResponse} */ (\n      await fetchAPI(`/repos/${owner}/${repo}/contents`, {\n        method: 'POST',\n        body: {\n          // `new_branch` creates the target branch from `branch` as part of the commit.\n          // Gitea/Forgejo rejects it outright once the branch exists. That’s left to the caller to\n          // sort out, because only the Editorial Workflow service can tell whether the branch is a\n          // leftover to start over from or someone’s work in progress to commit onto\n          ...(startBranch ? { branch: startBranch, new_branch: branch } : { branch }),\n          author: { name, email },\n          committer: { name, email },\n          dates: { author: date, committer: date },\n          message: commitMessage,\n          files,\n        },\n      })\n    );\n  } catch (/** @type {any} */ ex) {\n    // A changed file is refused with a 409 Conflict on Forgejo and a 422 Unprocessable Entity on\n    // Gitea, and a file someone else has created at the same path with a 422 on both\n    if (expectedHead && [409, 422].includes(ex.cause?.status)) {\n      await assertBranchNotMoved(expectedHead, fetchLastCommit);\n    }\n\n    throw ex;\n  }\n\n  const { commit, files: savedFiles } = response;\n\n  return {\n    sha: commit.sha,\n    date: new Date(commit.created),\n    files: Object.fromEntries(\n      savedFiles.map((file, index) => [\n        file?.path ?? changes[index].path,\n        { sha: file?.sha ?? '' },\n      ]),\n    ),\n  };\n};\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.gitea.com/api/next/#tag/repository/operation/repoGetAllCommits\n */\nexport const fetchFileCommits = async (paths) => {\n  const { owner, repo, branch } = repository;\n\n  return fetchPerPathCommits(\n    paths,\n    (path) =>\n      /** @type {Promise<any[]>} */ (\n        fetchAPI(\n          `/repos/${owner}/${repo}/commits` +\n            `?sha=${encodeURIComponent(branch ?? '')}` +\n            `&path=${encodeURIComponent(path)}&limit=100`,\n        )\n      ),\n    (commit) => ({\n      sha: commit.sha,\n      authorName: commit.commit?.author?.name ?? '',\n      authorEmail: commit.commit?.author?.email,\n      authorAvatarURL: commit.author?.avatar_url,\n      authorLogin: commit.author?.login,\n      date: new Date(commit.commit?.author?.date ?? commit.created),\n    }),\n  );\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","/**\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","/**\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 { getDirName } from '$lib/services/utils/file';\n\n/**\n * @import { Entry, UnpublishedEntry } from '$lib/types/private';\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’s file is stored in. For a multi-file i18n entry, the first locale’s file\n * is used.\n * @param {Entry | UnpublishedEntry} entry Entry.\n * @returns {string} Folder path, or an empty string if the entry is at the repository root.\n */\nexport const getEntryFolderPath = (entry) => getDirName(Object.values(entry.locales)[0].path);\n","import { getCollection } from '$lib/services/contents/collection';\nimport { getCollectionFile } from '$lib/services/contents/collection/files';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\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      parsedByPath.set(path, [...(parsedByPath.get(path) ?? []), 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 */\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 * @returns {Promise<{ entries: Entry[], errors: Error[] }>} Parsed entries, and errors encountered\n * while parsing them.\n */\nconst parseEntryFiles = async ({ entryFiles, changedPaths }) => {\n  const previous = allEntries.current;\n\n  if (!changedPaths || !previous.length) {\n    return prepareEntries(entryFiles);\n  }\n\n  const { reusedEntries, dirtyFiles } = planEntryReparse({ entryFiles, previous, changedPaths });\n  const { entries: parsedEntries, errors } = await prepareEntries(dirtyFiles);\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 * @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}) => {\n  const { entries, errors } = await parseEntryFiles({\n    entryFiles: entryFiles.map(\n      (fileInfo) => /** @type {BaseEntryListItem} */ (parseFileInfo({ fileInfo, fetchedFileMap })),\n    ),\n    changedPaths,\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';\nimport { 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 { 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 */\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]) => ({\n        path,\n        name: getPathInfo(path).basename,\n        ...data,\n      })),\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 * 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 */\nexport const updateCache = async ({\n  cacheDB,\n  allFiles,\n  cachedFiles,\n  fetchingFiles,\n  fetchedFileMap,\n}) => {\n  const usedPaths = new Set(allFiles.map(({ path }) => path));\n  const unusedPaths = Object.keys(cachedFiles).filter((path) => !usedPaths.has(path));\n\n  await Promise.all([\n    // Save new entry caches\n    fetchingFiles.length ? cacheDB.saveEntries(Object.entries(fetchedFileMap)) : 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.\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      const cachedFileEntries = await cacheDB.entries();\n      const metaEntries = await metaDB.entries();\n\n      return { metaEntries, cachedFileEntries };\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 {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  fetchFileMetadata,\n  log,\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({ cacheDB, allFiles, cachedFiles, fetchingFiles, fetchedFileMap });\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({ cacheDB, allFiles, cachedFiles, fetchingFiles, fetchedFileMap });\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  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to update the file cache.', ex);\n\n    return;\n  }\n\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};\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) =>\n        /** @type {RepositoryContentsMap} */ (\n          convertKeys(await fetchFileContents(toRepoFiles(files, rootDir)), (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  cacheFiles,\n  completeMetadata,\n  getFileList,\n  readDatabaseEntries,\n  restoreCachedFileData,\n  updateCache,\n} from '$lib/services/backends/git/shared/file-cache';\nimport { 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 */\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 * @typedef {(fetchingFiles: BaseFileListItem[]) => 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, 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  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));\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 */\nconst finishLoad = async ({\n  data,\n  parseKey,\n  metaDB,\n  lastConfigHash,\n  lastCommitHash,\n  startCacheUpdate,\n  log,\n  readyMessage,\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 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 = { 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    cachedFileEntries,\n    fetchFileContents,\n    fetchFileMetadata,\n    log,\n  });\n\n  const { entries, errors, assets, configFiles } = await parseFiles({\n    fileList,\n    fetchedFileMap,\n    changedPaths: incremental ? changedPaths : undefined,\n  });\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        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 { getPathInfo } from '@sveltia/utils/file';\n\n/**\n * @import { BaseFileListItemProps } from '$lib/types/private';\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 = 0 }) => ({ path, sha, size, name: getPathInfo(path).basename }));\n","/* eslint-disable no-await-in-loop */\n\nimport { decodeBase64, getPathInfo } from '@sveltia/utils/file';\n\nimport { fetchLastCommit } from '$lib/services/backends/git/gitea/commits';\nimport {\n  getWorkflowRepository,\n  initOpenAuthoring,\n  isOpenAuthoringConfigured,\n} from '$lib/services/backends/git/gitea/fork';\nimport { checkInstanceVersion, instance } from '$lib/services/backends/git/gitea/instance';\nimport {\n  checkBranchAccess,\n  checkRepositoryAccess,\n  fetchDefaultBranchName,\n  repository,\n} from '$lib/services/backends/git/gitea/repository';\nimport { 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 { fetchRepositoryFiles } from '$lib/services/backends/git/shared/files';\nimport { toFileListItems } from '$lib/services/backends/git/shared/tree';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport { getRootDir } from '$lib/services/backends/root-dir';\nimport { dataLoadedProgress } from '$lib/services/contents';\n\n/**\n * @import {\n * Asset,\n * BaseFileListItem,\n * BaseFileListItemProps,\n * RepositoryContentsMap,\n * } from '$lib/types/private';\n */\n\n/**\n * @typedef {{ type: string, path: string, sha: string, size: number }} PartialGitEntry\n */\n\n/**\n * An item in a bulk file contents response. Gitea returns the file path and Forgejo the blob SHA,\n * which is what each of them takes as the identifier in the request as well.\n * @typedef {{\n * path?: string,\n * sha?: string,\n * content?: string | null,\n * encoding?: 'base64' | null,\n * } | null} PartialContentsListItem\n */\n\n/**\n * The limits an instance applies to an API response, which it enforces by silently returning less\n * than what was asked for.\n * @typedef {object} ApiSettings\n * @property {number} [default_paging_num] Default number of items per page.\n * @property {number} [max_response_items] Maximum number of items in a response.\n * @property {number} [default_max_blob_size] Maximum size of a single blob whose content is\n * returned.\n * @property {number} [default_max_response_size] Maximum combined size of the contents in one\n * response. Gitea only; Forgejo has no such limit.\n */\n\n/**\n * Maximum size of a single blob whose content an instance returns, which is 10 MiB by default. Used\n * when the instance doesn’t report the limit it actually applies.\n * @see https://docs.gitea.com/administration/config-cheat-sheet\n */\nconst DEFAULT_MAX_BLOB_SIZE = 10485760;\n/**\n * Directories recently looked up at a commit, with their tree SHAs. The check for remote changes\n * looks up the old and new heads at the same time, so more than one is kept.\n * @type {Map<string, string | undefined>}\n */\nconst dirLookups = new Map();\n/**\n * Maximum number of entries in {@link dirLookups}.\n */\nconst MAX_DIR_LOOKUPS = 4;\n\n/**\n * Forget the directory lookups. Used in tests.\n */\nexport const _resetDirLookup = () => {\n  dirLookups.clear();\n};\n\n/**\n * Look the tree SHA of a directory up, without the cache of {@link fetchDirSHA}.\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 */\nconst lookUpDirSHA = async (ref, dirPath) => {\n  const { owner, repo } = repository;\n  const { dirname, basename } = getPathInfo(dirPath);\n  const parentPath = dirname ? `/${encodePath(dirname)}` : '';\n\n  // Missing when the parent directory doesn’t exist either\n  const entries = /** @type {{ type: string, name: string, sha: string }[] | undefined} */ (\n    await fetchAPIOrUndefined(\n      `/repos/${owner}/${repo}/contents${parentPath}?ref=${encodeURIComponent(ref)}`,\n    )\n  );\n\n  // A file is returned as a single item rather than a list\n  return Array.isArray(entries)\n    ? entries.find(({ type, name }) => type === 'dir' && name === basename)?.sha\n    : undefined;\n};\n\n/**\n * Find the tree SHA of a directory at the given commit, by listing the directory that holds it.\n * Gitea/Forgejo also resolve a `ref:path` expression in place of a tree SHA, but only with the\n * slashes in the path encoded as `%2F`, which a reverse proxy in front of a self-hosted instance\n * may decode, so the documented contents endpoint is used instead.\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.gitea.com/api/next/#tag/repository/operation/repoGetContentsList\n */\nexport const fetchDirSHA = async (ref, dirPath) => {\n  const key = `${repository.owner}/${repository.repo}:${ref}:${dirPath}`;\n\n  // The tree of a directory at a commit never changes, so the lookup the check for remote changes\n  // has just made is reused by the file list. A branch name moves, so it’s always looked up\n  if (dirLookups.has(key)) {\n    return dirLookups.get(key);\n  }\n\n  const sha = await lookUpDirSHA(ref, dirPath);\n\n  if (/^[\\da-f]{40,64}$/.test(ref)) {\n    dirLookups.set(key, sha);\n\n    // Forget the oldest one\n    if (dirLookups.size > MAX_DIR_LOOKUPS) {\n      dirLookups.delete(/** @type {string} */ (dirLookups.keys().next().value));\n    }\n  }\n\n  return sha;\n};\n\n/**\n * Fetch the repository’s complete file list, and return it in the canonical format. With the\n * `root_dir` backend option, only the files in that directory are listed, which saves listing the\n * whole of a big monorepo; the paths are still relative to the repository root.\n * @param {string} [lastHash] The last commit’s SHA-1 hash.\n * @returns {Promise<BaseFileListItemProps[]>} File list. It’s empty if the root directory doesn’t\n * exist.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/GetTree\n */\nexport const fetchFileList = async (lastHash) => {\n  const { owner, repo, branch } = repository;\n  const commitRef = /** @type {string} */ (lastHash ?? branch);\n  const rootDir = getRootDir();\n  const treeSHA = rootDir ? await fetchDirSHA(commitRef, rootDir) : commitRef;\n\n  if (!treeSHA) {\n    return [];\n  }\n\n  const requestPath = `/repos/${owner}/${repo}/git/trees/${encodePath(treeSHA)}?recursive=1`;\n  const prefix = rootDir ? `${rootDir}/` : '';\n  /** @type {PartialGitEntry[]} */\n  const gitEntries = [];\n  let page = 1;\n\n  for (;;) {\n    // 1000 items per page\n    const { tree, truncated } = /** @type {{ tree: PartialGitEntry[], truncated: boolean }} */ (\n      await fetchAPI(`${requestPath}&page=${page}`)\n    );\n\n    if (tree) {\n      gitEntries.push(...tree.map((entry) => ({ ...entry, path: `${prefix}${entry.path}` })));\n    }\n\n    if (tree && truncated) {\n      page += 1;\n    } else {\n      break;\n    }\n  }\n\n  return toFileListItems(gitEntries);\n};\n\n/**\n * Parse the file contents from the API response.\n * @param {BaseFileListItem[]} fetchingFiles Base file list.\n * @param {Record<string, PartialContentsListItem>} results Results from the API, keyed with a file\n * path. A file the API didn’t return content for is simply absent.\n * @returns {Promise<RepositoryContentsMap>} Parsed file contents map.\n */\nexport const parseFileContents = async (fetchingFiles, results) => {\n  const entries = await Promise.all(\n    fetchingFiles.map(async ({ path, sha, size, type }) => {\n      const item = results[path];\n\n      // A text file the API returned nothing for is left without text and metadata, so it’s not\n      // cached as fetched: an empty text would stand in for its content until the file changes,\n      // and the entry would lose its content the next time it’s saved. It’s requested again on the\n      // next load instead. An asset’s content is never requested, so it’s complete as it is\n      if (!item && type !== 'asset') {\n        return [path, { sha, size: size ?? 0, text: undefined, meta: undefined }];\n      }\n\n      const { content, encoding } = item ?? {};\n\n      const data = {\n        sha,\n        size: size ?? 0,\n        text: content && encoding === 'base64' ? await decodeBase64(content) : '',\n        // Omit commit author/data because it’s costly to fetch commit data for each file\n        meta: {},\n      };\n\n      return [path, data];\n    }),\n  );\n\n  return Object.fromEntries(entries);\n};\n\n/**\n * Fetch the text content of a single file with the raw endpoint, which returns it in full. The bulk\n * endpoints leave the content of an oversized blob empty, and keeping that would wipe the file the\n * next time the entry is saved.\n * @param {string} path File path.\n * @param {string} [ref] Workflow branch to read the file from. Default: the branch configured in\n * the site configuration. A workflow branch lives in the contributor’s fork with Open Authoring,\n * so that’s where a file on one is read from.\n * @returns {Promise<string>} File content.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetRawFile\n * @see https://github.com/go-gitea/gitea/issues/14432\n */\nexport const fetchRawFile = async (path, ref) => {\n  // A workflow branch lives in the contributor’s fork with Open Authoring, so that’s where a file\n  // on one is read from\n  const { owner, repo } = ref ? getWorkflowRepository() : repository;\n  const { branch = '' } = repository;\n\n  return /** @type {Promise<string>} */ (\n    fetchAPI(\n      `/repos/${owner}/${repo}/raw/${encodePath(path)}?ref=${encodeURIComponent(ref ?? branch)}`,\n      { responseType: 'text' },\n    )\n  );\n};\n\n/**\n * Split the given files into batches an instance will return in full. Both Gitea and Forgejo cut a\n * response short rather than reporting an error, so a batch has to stay within the number of items\n * they’re willing to return and, on Gitea, the combined size of the encoded contents.\n * @param {BaseFileListItem[]} files Files to fetch, none of which exceeds the per-blob limit.\n * @param {object} limits Limits reported by the instance.\n * @param {number} limits.maxItems Maximum number of files per batch.\n * @param {number} limits.maxResponseSize Maximum combined size of the encoded contents per batch.\n * @returns {BaseFileListItem[][]} Batches.\n */\nexport const createBatches = (files, { maxItems, maxResponseSize }) => {\n  /** @type {BaseFileListItem[][]} */\n  const batches = [];\n  /** @type {BaseFileListItem[]} */\n  let batch = [];\n  let batchSize = 0;\n\n  files.forEach((file) => {\n    // An instance measures a response by the size of the Base64-encoded contents it returns, and\n    // the encoding inflates a file by four bytes for every three\n    const encodedSize = ((file.size ?? 0) * 4) / 3;\n\n    // Close the current batch before the file that would push it over either limit. A batch is\n    // never left empty, so a file that exceeds a limit on its own still gets a request of its own\n    // instead of looping forever\n    if (batch.length && (batch.length === maxItems || batchSize + encodedSize > maxResponseSize)) {\n      batches.push(batch);\n      batch = [];\n      batchSize = 0;\n    }\n\n    batch.push(file);\n    batchSize += encodedSize;\n  });\n\n  if (batch.length) {\n    batches.push(batch);\n  }\n\n  return batches;\n};\n\n/**\n * Fetch the metadata of entry/asset files as well as text file contents. Gitea and Forgejo have\n * different API endpoints for this, so we handle both cases here.\n * @param {BaseFileListItem[]} fetchingFiles Base file list.\n * @returns {Promise<RepositoryContentsMap>} Fetched contents map.\n * @see https://github.com/go-gitea/gitea/pull/34139\n * @see https://codeberg.org/forgejo/forgejo/pulls/8139\n */\nexport const fetchFileContents = async (fetchingFiles) => {\n  const { owner, repo, branch } = repository;\n  const { isForgejo } = instance;\n\n  const requestPath = isForgejo\n    ? `/repos/${owner}/${repo}/git/blobs`\n    : `/repos/${owner}/${repo}/file-contents?ref=${encodeURIComponent(String(branch))}`;\n\n  // Forgejo uses `sha` as the identifier for files, while Gitea uses `path`. Each item in the\n  // response carries the same field, which is how a result is matched to the file it was requested\n  // for; the position of an item can’t be relied on, as an instance may drop some of them\n  const idField = isForgejo ? 'sha' : 'path';\n  const textFiles = fetchingFiles.filter(({ type }) => type !== 'asset');\n\n  if (!textFiles.length) {\n    return {};\n  }\n\n  dataLoadedProgress.current = 0;\n\n  // Ask the instance for the limits it applies to a response, so a request can be kept within them\n  const {\n    default_paging_num: pagingNum = 30,\n    max_response_items: maxResponseItems = Infinity,\n    default_max_blob_size: maxBlobSize,\n    default_max_response_size: maxResponseSize = Infinity,\n  } = /** @type {ApiSettings} */ (await fetchAPI('/settings/api'));\n\n  // A blob this large comes back with no content at all, so it has to be read separately\n  const blobSizeLimit = Number(maxBlobSize) || DEFAULT_MAX_BLOB_SIZE;\n  const oversizedFiles = textFiles.filter(({ size = 0 }) => size >= blobSizeLimit);\n\n  const batches = createBatches(\n    textFiles.filter(({ size = 0 }) => size < blobSizeLimit),\n    { maxItems: Math.min(pagingNum, maxResponseItems), maxResponseSize },\n  );\n\n  /** @type {Record<string, PartialContentsListItem>} */\n  const results = {};\n  let fetchedCount = 0;\n\n  /**\n   * Update the progress bar to reflect the files fetched so far.\n   * @param {number} count Number of files just fetched.\n   */\n  const advanceProgress = (count) => {\n    fetchedCount += count;\n    dataLoadedProgress.current = Math.ceil((fetchedCount / textFiles.length) * 100);\n  };\n\n  // Use the new bulk API endpoint to fetch multiple files at once. The batches are independent, so\n  // several of them are requested in parallel rather than one after another; a large repository\n  // needs dozens of them, and each is a full round trip to the instance\n  await runConcurrently(batches, async (batch) => {\n    const result = /** @type {PartialContentsListItem[]} */ (\n      await (isForgejo\n        ? fetchAPI(`${requestPath}?shas=${batch.map(({ sha }) => sha).join(',')}`)\n        : fetchAPI(requestPath, {\n            method: 'POST',\n            body: { files: batch.map(({ path }) => path) },\n          }))\n    );\n\n    const itemMap = new Map(result.filter((item) => !!item).map((item) => [item[idField], item]));\n\n    batch.forEach((file) => {\n      const item = itemMap.get(file[idField]);\n\n      if (item) {\n        results[file.path] = item;\n      }\n    });\n\n    advanceProgress(batch.length);\n  });\n\n  const fileMap = await parseFileContents(fetchingFiles, results);\n\n  // Read whatever the bulk endpoints won’t return from the raw endpoint, which has no size cap\n  await runConcurrently(oversizedFiles, async ({ path }) => {\n    // The bulk endpoints weren’t asked for the file, so its metadata is filled in with the text\n    Object.assign(fileMap[path], { text: await fetchRawFile(path), meta: {} });\n    advanceProgress(1);\n  });\n\n  dataLoadedProgress.current = undefined;\n\n  return fileMap;\n};\n\n/**\n * Check that the instance is supported and that the user can read the repository. Neither check is\n * needed until the file contents are requested, so they run alongside the branch and commit\n * requests rather than ahead of them, and alongside each other. An unsupported instance is\n * reported first, though, as it may also be why the repository can’t be read.\n */\nconst checkAccess = async () => {\n  const repositoryAccessPromise = checkRepositoryAccess();\n\n  // The rejection is handled below, once the version has been checked\n  repositoryAccessPromise.catch(() => undefined);\n\n  await checkInstanceVersion();\n  await repositoryAccessPromise;\n};\n\n/**\n * Set up Open Authoring for the signed-in user. The set-up asks the instance for what only a\n * supported version offers, so the version is checked first here rather than alongside the\n * repository, as {@link checkAccess} does.\n */\nconst setUpOpenAuthoring = async () => {\n  await checkInstanceVersion();\n  await initOpenAuthoring();\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: setUpOpenAuthoring,\n    repository,\n    checkAccess,\n    checkBranchAccess,\n    fetchDefaultBranchName,\n    fetchLastCommit,\n    lastCommit,\n    fetchFileList,\n    fetchFileContents,\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 * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetRawFileOrLFS\n */\nexport const fetchBlob = async (asset) => {\n  const { path } = asset;\n  // An asset attached to an unpublished entry only exists on the workflow branch, so that’s where\n  // it has to be read from — in the contributor’s fork with Open Authoring\n  const { owner, repo } = asset.workflow ? getWorkflowRepository() : repository;\n  const ref = asset.workflow?.branch ?? repository.branch;\n\n  return /** @type {Promise<Blob>} */ (\n    fetchAPI(`/repos/${owner}/${repo}/media/${encodePath(String(ref))}/${encodePath(path)}`, {\n      responseType: 'blob',\n    })\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","import { 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 { cmsConfig } from '$lib/services/config';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * CommitOptions,\n * CommitResults,\n * FileChange,\n * RepositoryPath,\n * WorkflowChangedFile,\n * WorkflowPullRequest,\n * WorkflowSaveOptions,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Function to open a pull request on the service.\n * @typedef {(args: { branch: string, title: string, status: WorkflowStatus }) =>\n * Promise<WorkflowPullRequest>} CreatePullRequest\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 */\nexport const deleteRemoteBranch = async ({ branch, path, goneStatuses }) => {\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 {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  createPullRequest,\n}) => {\n  if (openAuthoring.current && status === 'draft') {\n    return createDraftPullRequest({ commit, branch, title });\n  }\n\n  return createPullRequest({ branch, title, status });\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 * @returns {Promise<{ commit: CommitResults, pullRequest: WorkflowPullRequest }>} Commit results\n * and the new or updated pull request.\n */\nexport const saveWorkflowBranch = async (\n  { changes, options, branch, title, status, pullRequest },\n  { commitToNewBranch, commitToExistingBranch, createPullRequest },\n) => {\n  if (pullRequest) {\n    return {\n      commit: await commitToExistingBranch(changes, { ...options, branch }, pullRequest),\n      pullRequest,\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      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 * 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 {() => RepositoryPath} args.getWorkflowRepository Function to get the repository the\n * branch lives in.\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  getWorkflowRepository,\n}) => {\n  const head = await fetchBranchHead(branch);\n\n  // The branch can have gone, e.g. with a pull request merged or closed on the service, which is\n  // worth saying in words rather than with the service’s message about a branch it can’t find\n  if (head === undefined) {\n    throw createLocalizedError('Failed to save the changes.', 'branch_not_found', {\n      repo: getWorkflowRepository().repo,\n      branch,\n    });\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 * 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","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 * 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 { unique } from '@sveltia/utils/array';\nimport { isTextFileType } from '@sveltia/utils/file';\nimport { sleep } from '@sveltia/utils/misc';\nimport mime from 'mime';\n\nimport { fetchRawFile } from '$lib/services/backends/git/gitea/files';\nimport { getWorkflowRepository } from '$lib/services/backends/git/gitea/fork';\nimport { repository } from '$lib/services/backends/git/gitea/repository';\nimport { 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 { PULL_REQUEST_DESCRIPTION } from '$lib/services/backends/git/shared/pull-requests';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport { deleteRemoteBranch } from '$lib/services/backends/git/shared/workflow';\nimport {\n  getAllStatusLabels,\n  getStatusFromLabels,\n  getStatusLabel,\n} from '$lib/services/workflow/labels';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * FileChange,\n * RepositoryPath,\n * WorkflowFile,\n * WorkflowPullRequest,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Number of items an instance returns per page unless configured otherwise, which is also the most\n * it lets a request ask for. A larger `limit` is silently clamped rather than refused.\n * @see https://docs.gitea.com/administration/config-cheat-sheet#api-api\n */\nconst DEFAULT_MAX_RESPONSE_ITEMS = 50;\n/**\n * Maximum number of pages to read from a paginated list. Editorial Workflow is not meant to hold a\n * huge backlog, so this is a safety net against a runaway loop rather than a limit anyone should\n * reach.\n */\nconst MAX_PAGES = 10;\n/**\n * The page size the instance applies, once it has been asked. Every list below is fetched with it,\n * because the instance cuts a larger page short without saying so.\n * @type {number | undefined}\n */\nlet pageSize;\n\n/**\n * Reset the cached page size. Used for testing.\n */\nexport const resetPageSize = () => {\n  pageSize = undefined;\n};\n\n/**\n * Get the page size the instance applies to a list. It’s asked once per session; the default is\n * used if the instance doesn’t report it.\n * @returns {Promise<number>} Page size.\n * @see https://docs.gitea.com/api/next/#tag/settings/operation/getGeneralAPISettings\n */\nconst getPageSize = async () => {\n  if (pageSize === undefined) {\n    const { max_response_items: maxItems } = /** @type {{ max_response_items?: number }} */ (\n      await fetchAPI('/settings/api')\n    );\n\n    pageSize = Number(maxItems) || DEFAULT_MAX_RESPONSE_ITEMS;\n  }\n\n  return pageSize;\n};\n\n/**\n * Fetch the items of a paginated list. The instance clamps the page size to what it’s configured\n * with, so the pages are requested at that size and read until one comes back short, rather than\n * asking for one large page and silently losing whatever didn’t fit.\n * @param {string} path API endpoint path, with any query parameters of its own.\n * @returns {Promise<{ items: Record<string, any>[], complete: boolean }>} Items, and whether they\n * are all of them: the reading stops at {@link MAX_PAGES} pages, which may leave some out.\n */\nexport const fetchPages = async (path) => {\n  const limit = await getPageSize();\n  const separator = path.includes('?') ? '&' : '?';\n  /** @type {Record<string, any>[]} */\n  const items = [];\n\n  for (let page = 1; page <= MAX_PAGES; page += 1) {\n    const result = /** @type {Record<string, any>[]} */ (\n      // eslint-disable-next-line no-await-in-loop\n      await fetchAPI(`${path}${separator}page=${page}&limit=${limit}`)\n    );\n\n    items.push(...result);\n\n    if (result.length < limit) {\n      return { items, complete: true };\n    }\n  }\n\n  return { items, complete: false };\n};\n\n/**\n * Fetch every item of a paginated list, up to {@link MAX_PAGES} pages: see {@link fetchPages}.\n * @param {string} path API endpoint path, with any query parameters of its own.\n * @returns {Promise<Record<string, any>[]>} Items.\n */\nexport const fetchAllPages = async (path) => (await fetchPages(path)).items;\n\n/**\n * Regular expression matching the work-in-progress indicators Gitea/Forgejo accepts at the\n * beginning of a pull request title. There’s no dedicated API field to toggle the draft state; the\n * read-only `draft` property is derived from the title instead. An instance can be configured with\n * its own prefixes, but the two defaults are what a pull request created by the CMS carries.\n * @see https://docs.gitea.com/administration/config-cheat-sheet\n */\nconst WIP_TITLE_REGEX = /^\\s*(?:\\[wip\\]|wip:)\\s*/i;\n/**\n * Prefix added to a pull request title to mark it as a draft.\n */\nconst WIP_TITLE_PREFIX = 'WIP: ';\n\n/**\n * Colors used for the CMS status labels, which have to be created on the instance before they can\n * be applied. The keys are {@link WorkflowStatus} values.\n * @type {Record<string, string>}\n */\nconst STATUS_LABEL_COLORS = {\n  draft: '#ededed',\n  pending_review: '#fbca04',\n  pending_publish: '#0e8a16',\n  pending_deletion: '#d93f0b',\n};\n\n/**\n * Description given to a CMS status label created on the instance.\n */\nconst STATUS_LABEL_DESCRIPTION = 'Editorial Workflow status managed by Sveltia CMS';\n\n/**\n * Remove any work-in-progress indicator from the given pull request title.\n * @param {string} title Raw title.\n * @returns {string} Title without a WIP prefix.\n */\nexport const stripWipPrefix = (title) => {\n  let result = title;\n\n  // Repeat, because an instance accepts more than one prefix and a title can carry a combination\n  while (WIP_TITLE_REGEX.test(result)) {\n    result = result.replace(WIP_TITLE_REGEX, '');\n  }\n\n  return result;\n};\n\n/**\n * Check whether the given pull request was opened from a branch of the configured repository rather\n * than from a fork. The repository IDs are compared rather than the repositories themselves,\n * because the instance always reports them — the head repository is left out of the response when\n * it has been deleted — and the head’s is `-1` until one is resolved, so a pull request whose\n * origin can’t be established is treated as a fork.\n * @param {Record<string, any>} item Pull request.\n * @returns {boolean} `true` if the head branch is on the configured repository.\n */\nexport const isSameRepositoryPullRequest = ({ head, base }) =>\n  typeof head?.repo_id === 'number' && head.repo_id !== -1 && head.repo_id === base?.repo_id;\n\n/**\n * Parse a pull request returned by the REST API.\n * @param {Record<string, any>} item Pull request.\n * @returns {WorkflowPullRequest | undefined} Parsed pull request, or `undefined` if the pull\n * request is not managed by the CMS.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetPullRequest\n */\nexport const parsePullRequest = (item) => {\n  const status = getStatusFromLabels(\n    (item.labels ?? []).map((/** @type {any} */ { name }) => name),\n  );\n\n  if (!status) {\n    return undefined;\n  }\n\n  const { ref: branch, sha: headSHA } = item.head ?? {};\n\n  // A pull request from a fork has its branch in a repository this flow can’t read. Labelling one\n  // by hand would otherwise put a card on the board showing the configured repository’s branch of\n  // the same name, and publishing it would merge the fork’s commits — whatever they touch — rather\n  // than the entry the reviewer saw\n  if (!branch || !isSameRepositoryPullRequest(item)) {\n    return undefined;\n  }\n\n  // A pull request to a branch other than the configured one isn’t the CMS’s either, whatever label\n  // it carries: one whose base branch was changed on the instance 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 (item.base?.ref !== repository.branch) {\n    return undefined;\n  }\n\n  const { full_name: fullName, login, email, id } = item.user ?? {};\n\n  return {\n    number: item.number,\n    nodeId: String(item.id),\n    title: stripWipPrefix(item.title),\n    url: item.html_url,\n    branch,\n    headSHA,\n    status,\n    createdDate: new Date(item.created_at),\n    updatedDate: new Date(item.updated_at),\n    author: login ? { name: fullName || login, email: email ?? '', id, login } : undefined,\n    files: [],\n  };\n};\n\n/**\n * Fetch the commit the given pull request was last updated to, which is the commit it was merged\n * at once it has been. The pull request itself can’t be asked: the head commit it reports is the\n * branch’s current one for as long as the branch exists, on Forgejo and on a single pull request\n * on Gitea alike, which says nothing about what has been committed since the merge. The instance\n * keeps the commit in a `refs/pull/{number}/head` reference on the configured repository instead,\n * which it stops updating once the pull request is closed or merged.\n * @param {number} number Pull request number.\n * @returns {Promise<string | undefined>} Git object ID, or `undefined` if the reference is\n * missing.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetGitRef\n */\nexport const fetchPullRequestHeadRef = async (number) => {\n  const { owner, repo } = repository;\n  const ref = `refs/pull/${number}/head`;\n\n  const result = /** @type {Record<string, any> | Record<string, any>[] | undefined} */ (\n    await fetchAPIOrUndefined(`/repos/${owner}/${repo}/git/${ref}`)\n  );\n\n  if (!result) {\n    return undefined;\n  }\n\n  // The path is a prefix filter, which the instance answers with a list even when a single\n  // reference matches it exactly, so the one asked for is picked out\n  const match = (Array.isArray(result) ? result : [result]).find((item) => item.ref === ref);\n\n  return match?.object?.sha;\n};\n\n/**\n * How many times, and how often, the changed files are read while the instance catches up with the\n * branch. It works out the files from a `refs/pull/{number}/head` reference it moves to the branch\n * head in the background once a commit is pushed, so a list read right after a save can still\n * describe the commit before it.\n */\nconst FILE_LIST_POLL = { attempts: 10, interval: 1000 };\n/**\n * How many times the changed files are read for the board, which only waits a moment for the\n * reference to catch up. A list that still describes another commit then is shown as of that\n * commit: see {@link fetchPullRequestFileList}.\n */\nconst BOARD_FILE_LIST_ATTEMPTS = 3;\n\n/**\n * Get the commit the given changed file was listed at, which the instance spells out in the file’s\n * API link as the `ref` it’s read at.\n * @param {Record<string, any>} file Changed file returned by the REST API.\n * @returns {string | null} Git object ID, or `null` if the link doesn’t name one.\n */\nconst getListedCommit = ({ contents_url: url }) => {\n  try {\n    return new URL(url).searchParams.get('ref');\n  } catch {\n    return null;\n  }\n};\n\n/**\n * Fetch the files the given pull request changes as of the given commit. The instance lists them\n * as of the commit its `refs/pull/{number}/head` reference points at, and names that commit in each\n * file’s link; an empty list names none, so the reference itself is read then. A list that turns\n * out to describe another commit is read again until the reference has caught up with the branch.\n * If it doesn’t, the list can’t vouch for the commit, and is reported as incomplete.\n * @param {number} number Pull request number.\n * @param {string} headSHA Git object ID of the commit.\n * @param {number} [attemptsLeft] Remaining reads, including this one.\n * @returns {Promise<{ files: Record<string, any>[], complete: boolean, commit?: string }>} Files,\n * whether they are every file changed as of the commit, and the commit they were listed at, if\n * they name a single one.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetPullRequestFiles\n */\nexport const fetchChangedFiles = async (\n  number,\n  headSHA,\n  attemptsLeft = FILE_LIST_POLL.attempts,\n) => {\n  const { owner, repo } = repository;\n  const { items, complete } = await fetchPages(`/repos/${owner}/${repo}/pulls/${number}/files`);\n\n  const listedCommits = items.length\n    ? [...new Set(items.map((file) => getListedCommit(file)))]\n    : [await fetchPullRequestHeadRef(number)];\n\n  // The single commit every file was listed at, if they agree on one\n  const commit = listedCommits.length === 1 ? (listedCommits[0] ?? undefined) : undefined;\n  const current = commit === headSHA;\n\n  if (current || attemptsLeft <= 1) {\n    return { files: items, complete: complete && current, commit };\n  }\n\n  await sleep(FILE_LIST_POLL.interval);\n\n  return fetchChangedFiles(number, headSHA, attemptsLeft - 1);\n};\n\n/**\n * Fetch the list of files changed in the given pull request as of its head commit, the one a\n * publish is pinned to: see {@link fetchChangedFiles}. Otherwise a file the head commit adds — an\n * asset, say, which the check before publishing lets through as one of the entry’s — could be\n * missing from the board while the instance catches up with a push. A list that still describes\n * another commit once the wait has run out makes that commit the head on record, so the files are\n * read at it as well and the board shows one commit throughout; publishing it is then refused, as\n * the branch has moved on from it, until the board is reloaded. A list that names no single commit\n * leaves no head on record, which publishing refuses just the same.\n * @param {WorkflowPullRequest} pullRequest Pull request to complete.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetPullRequestFiles\n */\nexport const fetchPullRequestFileList = async (pullRequest) => {\n  const { owner, repo } = repository;\n  const { number, headSHA } = /** @type {{ number: number, headSHA?: string }} */ (pullRequest);\n  /** @type {Record<string, any>[]} */\n  let files;\n\n  if (headSHA) {\n    const result = await fetchChangedFiles(number, headSHA, BOARD_FILE_LIST_ATTEMPTS);\n\n    files = result.files;\n    pullRequest.headSHA = result.commit;\n  } else {\n    files = await fetchAllPages(`/repos/${owner}/${repo}/pulls/${number}/files`);\n  }\n\n  pullRequest.files = files.map(({ filename, status, previous_filename: previousPath }) => ({\n    path: filename,\n    sha: '',\n    size: 0,\n    deleted: status === 'deleted',\n    previousPath: previousPath || undefined,\n  }));\n};\n\n/**\n * Decode the Base64-encoded content of a file as UTF-8 text. Neither Gitea nor Forgejo reports\n * whether a blob is binary, so the decoding itself is the test: an image committed along with the\n * entry simply isn’t valid UTF-8.\n * @param {string} content Base64-encoded content.\n * @returns {string | undefined} Decoded text, or `undefined` if the file is binary.\n */\nexport const decodeFileText = (content) => {\n  try {\n    return new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.fromBase64(content));\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Fetch the content of a single file changed in the given pull request, and populate the\n * {@link WorkflowFile} object in place.\n * @param {WorkflowPullRequest} pullRequest Pull request the file belongs to.\n * @param {WorkflowFile} file File to complete.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetContents\n */\nexport const fetchPullRequestFileContent = async (pullRequest, file) => {\n  // A workflow branch lives in the contributor’s fork with Open Authoring, so that’s where the file\n  // has to be read from. It’s read at the head commit rather than the branch, so the content shown\n  // is that of the commit a publish is pinned to, even if the branch moves on while the board loads\n  const { owner, repo } = getWorkflowRepository();\n  const { path } = file;\n  const ref = pullRequest.headSHA ?? pullRequest.branch;\n\n  const result = /** @type {Record<string, any> | undefined} */ (\n    await fetchAPIOrUndefined(\n      `/repos/${owner}/${repo}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`,\n    )\n  );\n\n  // The file may have been removed from the branch in the meantime\n  if (!result) {\n    file.deleted = true;\n\n    return;\n  }\n\n  const { sha, size, content, encoding } = result;\n\n  Object.assign(file, {\n    sha: sha ?? '',\n    size: Number(size) || 0,\n    text: content && encoding === 'base64' ? decodeFileText(content) : undefined,\n  });\n\n  // An instance omits the content of an oversized blob, and keeping that empty would wipe the file\n  // the next time the entry is saved. Only a text file is worth reading again; the media that make\n  // up most of the oversized blobs have no text to store anyway\n  if (!content && file.size && isTextFileType(mime.getType(path) ?? '')) {\n    file.text = await fetchRawFile(path, ref);\n  }\n};\n\n/**\n * Fetch the content of the files changed in the given pull request. Binary files, such as images,\n * have no text, so only their blob metadata is stored.\n * @param {WorkflowPullRequest} pullRequest Pull request to complete.\n */\nexport const fetchPullRequestFileContents = async (pullRequest) => {\n  await runConcurrently(\n    pullRequest.files.filter(({ deleted }) => !deleted),\n    async (file) => fetchPullRequestFileContent(pullRequest, file),\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.\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.gitea.com/api/next/#tag/repository/operation/repoGetBranch\n */\nexport const fetchBranchHead = async (branch) => {\n  const { owner, repo } = getWorkflowRepository();\n\n  const result = /** @type {{ commit?: { id?: string } } | undefined} */ (\n    await fetchAPIOrUndefined(`/repos/${owner}/${repo}/branches/${encodePath(branch)}`)\n  );\n\n  return result?.commit?.id;\n};\n\n/**\n * Delete the given branch. Failures are ignored, as the branch may already have been deleted when\n * the pull request was merged.\n * @param {string} branch Branch name.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoDeleteBranch\n */\nexport const deleteBranch = async (branch) => {\n  const { owner, repo } = getWorkflowRepository();\n\n  await deleteRemoteBranch({\n    branch,\n    path: `/repos/${owner}/${repo}/branches/${encodePath(branch)}`,\n    goneStatuses: [404],\n  });\n};\n\n/**\n * Create the label for the given status on the repository. Unlike GitHub and GitLab, Gitea/Forgejo\n * silently drops a label name that doesn’t exist yet instead of creating it on the fly.\n * @param {WorkflowStatus} status Status.\n * @see https://docs.gitea.com/api/next/#tag/issue/operation/issueCreateLabel\n */\nexport const createStatusLabel = async (status) => {\n  const { owner, repo } = repository;\n\n  await fetchAPI(`/repos/${owner}/${repo}/labels`, {\n    method: 'POST',\n    body: {\n      name: getStatusLabel(status),\n      color: STATUS_LABEL_COLORS[status],\n      description: STATUS_LABEL_DESCRIPTION,\n    },\n  });\n};\n\n/**\n * Apply the given labels to a pull request, creating the status label on the repository if it turns\n * out to be missing. The label list the request returns is what the instance actually stored, so a\n * dropped status label is detected there rather than with a lookup before every update. A label of\n * the same name defined by the organization that owns the repository is applied too, but it doesn’t\n * count: the pull requests are listed by the IDs of the repository’s own labels, which is all the\n * CMS can read. An organization label’s API link points under `/orgs/`, which tells it apart.\n * @param {number} number Pull request number.\n * @param {string[]} labels Label names to apply.\n * @param {WorkflowStatus} status Status the labels represent.\n * @param {'POST' | 'PUT'} method `POST` to add the labels, `PUT` to replace the whole list.\n * @see https://docs.gitea.com/api/next/#tag/issue/operation/issueAddLabel\n * @see https://docs.gitea.com/api/next/#tag/issue/operation/issueReplaceLabels\n */\nexport const applyLabels = async (number, labels, status, method) => {\n  const { owner, repo } = repository;\n  const path = `/repos/${owner}/${repo}/issues/${number}/labels`;\n  const statusLabel = getStatusLabel(status);\n\n  const result = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(path, { method, body: { labels } })\n  );\n\n  const applied = result.some(\n    ({ name, url }) => name === statusLabel && !String(url ?? '').includes('/api/v1/orgs/'),\n  );\n\n  if (!applied) {\n    await createStatusLabel(status);\n    await fetchAPI(path, { method, body: { labels } });\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.gitea.com/api/next/#tag/issue/operation/issueGetLabels\n */\nexport const updateLabels = async (pullRequest, status) => {\n  const { owner, repo } = repository;\n  const { number } = pullRequest;\n  const cmsLabels = getAllStatusLabels();\n\n  const labels = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/issues/${number}/labels`)\n  );\n\n  const newLabels = [\n    ...labels.map(({ name }) => name).filter((name) => !cmsLabels.includes(name)),\n    getStatusLabel(status),\n  ];\n\n  await applyLabels(/** @type {number} */ (number), newLabels, status, 'PUT');\n};\n\n/**\n * Convert a pull request to a draft, or mark it ready for review. There’s no API field for the\n * draft state, which is derived from the title, so the title is rewritten instead.\n * @param {WorkflowPullRequest} pullRequest Pull request. Its title is the one without a prefix.\n * @param {boolean} isDraft Whether the pull request should be a draft.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoEditPullRequest\n */\nexport const updateDraftState = async (pullRequest, isDraft) => {\n  const { owner, repo } = repository;\n  const { number, title } = pullRequest;\n\n  await fetchAPI(`/repos/${owner}/${repo}/pulls/${number}`, {\n    method: 'PATCH',\n    body: { title: isDraft ? `${WIP_TITLE_PREFIX}${title}` : title },\n  });\n};\n\n/**\n * Create a new pull request for the given workflow branch. The pull request is created as a draft\n * when a newly saved entry 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 * @returns {Promise<WorkflowPullRequest>} Created pull request.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoCreatePullRequest\n */\nexport const createPullRequest = async ({ branch, title, status }) => {\n  const { owner, repo, branch: baseBranch } = repository;\n  const fork = forkedRepository.current;\n  const isDraft = status === 'draft';\n\n  const result = /** @type {Record<string, any>} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/pulls`, {\n      method: 'POST',\n      body: {\n        title: isDraft ? `${WIP_TITLE_PREFIX}${title}` : 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        body: PULL_REQUEST_DESCRIPTION,\n      },\n    })\n  );\n\n  // Labelling a pull request requires write access to the repository, which an Open Authoring\n  // contributor doesn’t have. Their status is read from the pull request itself instead\n  if (!fork) {\n    // The label can’t be set on creation, which takes label IDs rather than names. A brand-new pull\n    // request has no label to preserve, so the status label is added outright rather than replacing\n    // the current list like {@link updateLabels} has to\n    await applyLabels(result.number, [getStatusLabel(status)], status, 'POST');\n  }\n\n  return {\n    number: result.number,\n    nodeId: String(result.id),\n    title,\n    url: result.html_url,\n    branch,\n    headSHA: result.head?.sha,\n    status,\n    createdDate: new Date(result.created_at),\n    updatedDate: new Date(result.updated_at),\n    files: [],\n  };\n};\n\n/**\n * Get the path a change reads the current file from, which is the path it came from when the change\n * renames the entry.\n * @param {FileChange} change Change to be committed.\n * @returns {string} File path.\n */\nconst getSourcePath = ({ action, path, previousPath }) =>\n  action === 'move' && previousPath ? previousPath : path;\n\n/**\n * Fetch the blob SHA of the given file on the given branch or commit.\n * @param {string} path File path.\n * @param {string} ref Branch or commit to read the file from.\n * @param {RepositoryPath} [repository] Repository to read the file from. Defaults to the one the\n * workflow branches live in, which is the contributor’s fork with Open Authoring.\n * @returns {Promise<string | undefined>} Blob SHA, or `undefined` if the file isn’t there.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetContents\n */\nexport const fetchFileSHA = async (path, ref, { owner, repo } = getWorkflowRepository()) => {\n  const result = /** @type {Record<string, any> | undefined} */ (\n    await fetchAPIOrUndefined(\n      `/repos/${owner}/${repo}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`,\n    )\n  );\n\n  return result?.sha;\n};\n\n/**\n * Fill in the blob SHA that each change needs on the branch it lands on. Gitea/Forgejo refuses a\n * commit that updates, moves or deletes a file without the file’s current SHA, and refuses it just\n * as firmly when the SHA is out of date. The CMS’s file cache holds the SHAs on the configured\n * branch, which a workflow branch has moved on from with every earlier save, so they’re read from\n * the branch the commit is about to land on. A save touches a handful of files, and only the ones\n * it doesn’t create need looking up.\n *\n * A file the branch turns out not to have can’t be updated, moved or deleted there, whatever the\n * cache says. That’s what an Open Authoring fork looks like once it has fallen behind: the entry\n * the contributor is editing was added upstream after they forked. The change is reshaped to what\n * the branch can take — writing the file is a creation there, and removing it is nothing at all.\n * @param {FileChange[]} changes Changes to be committed.\n * @param {string} ref Branch the changes land on, or the commit the branch is expected to point\n * at.\n * @returns {Promise<FileChange[]>} Changes, with the SHA of each existing file filled in.\n */\nexport const resolveChangeSHAs = async (changes, ref) => {\n  const paths = unique(\n    changes.filter(({ action }) => action !== 'create').map((change) => getSourcePath(change)),\n  );\n\n  if (!paths.length) {\n    return changes;\n  }\n\n  /** @type {Map<string, string>} */\n  const shaMap = new Map();\n\n  await runConcurrently(paths, async (path) => {\n    const sha = await fetchFileSHA(path, ref);\n\n    if (sha) {\n      shaMap.set(path, sha);\n    }\n  });\n\n  return changes.flatMap((change) => {\n    if (change.action === 'create') {\n      return change;\n    }\n\n    const sha = shaMap.get(getSourcePath(change));\n\n    if (sha) {\n      return { ...change, previousSha: sha };\n    }\n\n    if (change.action === 'delete') {\n      return [];\n    }\n\n    const { previousPath: _previousPath, previousSha: _previousSha, ...rest } = change;\n\n    return { ...rest, action: 'create' };\n  });\n};\n","import { getRootDir } from '$lib/services/backends/root-dir';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\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/**\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 * @returns {string} Prefix, including the trailing slash.\n */\nconst joinPrefix = (rootDir) => {\n  const fork = forkedRepository.current;\n\n  return [WORKFLOW_BRANCH_PREFIX, fork?.owner, fork?.repo, rootDir]\n    .filter(Boolean)\n    .map((segment) => `${segment}/`)\n    .join('');\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 nested collection is a path, and Git\n * can’t hold a branch `cms/pages/about` alongside `cms/pages/about/us`, because the former would\n * have to be both a ref and a directory. So the slashes are percent-encoded, which keeps each entry\n * to a single path segment. `%` is encoded as well, so the encoding can be 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 * 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 { getWorkflowRepository } from '$lib/services/backends/git/gitea/fork';\nimport {\n  createPullRequest,\n  deleteBranch,\n  fetchAllPages,\n  fetchBranchHead,\n  fetchPullRequestFileContents,\n  fetchPullRequestFileList,\n  fetchPullRequestHeadRef,\n  stripWipPrefix,\n  updateDraftState,\n} from '$lib/services/backends/git/gitea/pull-requests';\nimport { repository } from '$lib/services/backends/git/gitea/repository';\nimport { fetchAPI } 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 { encodePath } from '$lib/services/backends/git/shared/url';\nimport { user } from '$lib/services/user/account.svelte';\nimport { getBranchListPrefix } from '$lib/services/workflow/branch';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * ForkRequestState,\n * WorkflowFile,\n * WorkflowPullRequest,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Fetch the Editorial Workflow branches in the contributor’s fork. With Open Authoring the branches\n * are the source of truth: a draft has no pull request yet, so listing pull requests alone would\n * miss it.\n * @returns {Promise<Record<string, any>[]>} Branches whose name starts with the workflow prefix.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoListBranches\n */\nexport const fetchForkBranchList = async () => {\n  const { owner, repo } = getWorkflowRepository();\n  const prefix = getBranchListPrefix();\n  // The instance can’t filter by prefix, so every branch is listed. A fork holds few besides the\n  // workflow ones, so it’s a page or two in practice\n  const branches = await fetchAllPages(`/repos/${owner}/${repo}/branches`);\n\n  return branches.filter(({ name }) => name.startsWith(prefix));\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, to the configured branch. The configured repository can have\n * a branch of the same name, whose pull request isn’t the contributor’s; one they aimed at another\n * branch is their own business, and acting on it — reopening or closing it as the entry moves —\n * would be meddling with a review the CMS knows nothing about; and someone else’s pull request from\n * the contributor’s branch would put their title on the entry, which the contributor could neither\n * convert, reopen nor close.\n * @param {Record<string, any>} item Pull request returned by the REST API.\n * @returns {boolean} Result.\n * @see https://github.com/sveltia/sveltia-cms/security/advisories/GHSA-p8qh-54q9-2qjx\n * @see https://github.com/sveltia/sveltia-cms/security/advisories/GHSA-8h97-74c4-g246\n */\nexport const isForkPullRequest = (item) => {\n  const fork = forkedRepository.current;\n  const userId = user.account?.id;\n\n  return (\n    !!fork &&\n    item.head?.repo?.full_name?.toLowerCase() === `${fork.owner}/${fork.repo}`.toLowerCase() &&\n    item.base?.ref === repository.branch &&\n    userId !== undefined &&\n    item.user?.id === userId\n  );\n};\n\n/**\n * Fetch the pull requests the contributor has opened from their fork on the configured repository,\n * in any state. A branch in the fork doesn’t report them, so they’re looked up from the configured\n * repository instead, narrowed to the contributor’s own and matched by head branch here. The poster\n * filter is checked again on each one rather than trusted to have applied.\n * @returns {Promise<Map<string, Record<string, any>>>} Map of branch name to the most relevant pull\n * request opened from it, where there is one: the open one if any, otherwise the most recently\n * updated.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoListPullRequests\n */\nexport const fetchForkPullRequestMap = async () => {\n  const { owner, repo } = repository;\n  const login = /** @type {string} */ (user.account?.login);\n\n  const items = await fetchAllPages(\n    `/repos/${owner}/${repo}/pulls?state=all&sort=recentupdate&poster=${encodeURIComponent(login)}`,\n  );\n\n  /** @type {Map<string, Record<string, any>>} */\n  const map = new Map();\n\n  items.filter(isForkPullRequest).forEach((item) => {\n    const branch = item.head.ref;\n    const existing = map.get(branch);\n\n    // The list is sorted by the last update, so the first match is the most recent one. An open\n    // pull request wins over any other, because it’s the one the entry’s status has to reflect\n    if (!existing || (existing.state !== 'open' && item.state === 'open')) {\n      map.set(branch, item);\n    }\n  });\n\n  return map;\n};\n\n/**\n * Parse a branch returned by the REST API.\n * @param {Record<string, any>} node Branch.\n * @param {Record<string, any>} [pullRequest] Pull request opened from the branch, from\n * {@link fetchForkPullRequestMap}.\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, pullRequest) => {\n  const { name: branch, commit } = node;\n  const { id: headSHA, message, timestamp, author } = commit;\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?.merged ? undefined : pullRequest;\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.draft;\n\n  return {\n    number: current?.number,\n    nodeId: current ? String(current.id) : undefined,\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. The prefix that marks a work in\n    // progress is dropped, because it’s written back when the entry returns to the drafting stage —\n    // keeping it would leave the pull request a work in progress on the way out of that stage\n    title: stripWipPrefix(current?.title ?? message ?? ''),\n    url: current?.html_url,\n    branch,\n    headSHA,\n    status: inReview ? 'pending_review' : 'draft',\n    createdDate: new Date(current?.created_at ?? timestamp),\n    updatedDate: new Date(current?.updated_at ?? timestamp),\n    author: author?.name\n      ? { name: author.name, email: author.email ?? '', login: author.username }\n      : undefined,\n    // The files are filled in later: an open pull request reports them, while a branch without one\n    // is compared with the configured branch\n    files: [],\n    // Only a maintainer merges, and a contributor is never one\n    canMerge: false,\n  };\n};\n\n/**\n * Fetch the files a fork branch changes, and populate the {@link WorkflowFile} objects in place. A\n * draft has no pull request to list files from, so the branch is compared with the fork’s copy of\n * the configured branch instead, which it was created from and which is brought up to date with\n * the configured repository on sign-in. The comparison runs in the fork rather than across\n * repositories: Gitea reads the files of each commit from the base repository then, which doesn’t\n * have the commits only the fork holds — a draft’s, for one — and fails with a 500. The comparison\n * reports the files touched by each commit rather than the net change, so the paths are gathered\n * from all of them; a file one of the commits removed since is found to be missing when its\n * content is fetched, and marked as deleted then. Like the content, the files are those of the\n * branch’s head commit as listed, rather than of whatever the branch points at by now.\n * @param {WorkflowPullRequest} pullRequest Branch to complete.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoCompareDiff\n */\nexport const fetchForkBranchFileList = async (pullRequest) => {\n  const { owner, repo } = getWorkflowRepository();\n  const base = encodePath(/** @type {string} */ (repository.branch));\n  const head = encodePath(pullRequest.headSHA ?? pullRequest.branch);\n\n  const { commits = [] } = /** @type {{ commits?: Record<string, any>[] }} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/compare/${base}...${head}`)\n  );\n\n  /** @type {Map<string, WorkflowFile>} */\n  const files = new Map();\n\n  commits.forEach(({ files: commitFiles = [] }) => {\n    commitFiles.forEach((/** @type {any} */ { filename }) => {\n      files.set(filename, { path: filename, sha: '', size: 0, deleted: false });\n    });\n  });\n\n  pullRequest.files = [...files.values()];\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 nodes = await fetchForkBranchList();\n\n  if (!nodes.length) {\n    return [];\n  }\n\n  const pullRequests = await fetchForkPullRequestMap();\n  /** @type {Map<number, string | undefined>} */\n  const mergedHeads = new Map();\n\n  // The commit a pull request was merged at is read from its reference, because the head the pull\n  // request reports follows the branch\n  await runConcurrently(\n    /** @type {Record<string, any>[]} */ (\n      nodes.map(({ name }) => pullRequests.get(name)).filter((item) => !!item?.merged)\n    ),\n    async ({ number }) => {\n      mergedHeads.set(number, await fetchPullRequestHeadRef(number));\n    },\n  );\n\n  const pending = await pruneForkBranches(\n    nodes,\n    (node) => {\n      const pullRequest = pullRequests.get(node.name);\n\n      return pullRequest?.merged && mergedHeads.get(pullRequest.number) === node.commit?.id\n        ? { leftover: node.name }\n        : { pending: parseForkBranch(node, pullRequest) };\n    },\n    deleteBranch,\n  );\n\n  // An open pull request already reports the files it changes, which is cheaper than comparing the\n  // branch with the configured branch. A closed pull request is left to the comparison as well:\n  // its diff is no longer a reliable account of a branch that has moved on since\n  await runConcurrently(pending, async (pullRequest) => {\n    if (pullRequest.status === 'pending_review') {\n      await fetchPullRequestFileList(pullRequest);\n    } else {\n      await fetchForkBranchFileList(pullRequest);\n    }\n\n    await fetchPullRequestFileContents(pullRequest);\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  return pending.filter(({ files }) => files.length);\n};\n\n/**\n * Reopen a pull request that was closed earlier. The author of a pull request is allowed to do\n * this, so a contributor doesn’t need write access to the configured repository for it.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoEditPullRequest\n */\nexport const reopenPullRequest = async (pullRequest) => {\n  const { owner, repo } = repository;\n\n  await fetchAPI(`/repos/${owner}/${repo}/pulls/${pullRequest.number}`, {\n    method: 'PATCH',\n    body: { state: 'open' },\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>} State.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetPullRequest\n */\nconst fetchForkRequestState = async ({ number }) => {\n  const { owner, repo } = repository;\n\n  const item = /** @type {Record<string, any>} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/pulls/${number}`)\n  );\n\n  return {\n    merged: !!item.merged,\n    isEntryRequest: isForkPullRequest(item),\n    /**\n     * Read the head commit the pull request was merged at. It’s read from the pull request’s\n     * reference, because the head the pull request reports follows the branch.\n     * @returns {Promise<string>} Commit SHA.\n     */\n    getMergedSHA: async () => (await fetchPullRequestHeadRef(/** @type {number} */ (number))) ?? '',\n    state: item.state,\n    draft: item.draft,\n  };\n};\n\n/**\n * Bring a pull request in line with the given status, for {@link updateForkStatusWith}.\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`.\n * @param {boolean} [args.draft] Whether the pull request is a work in progress.\n */\nconst applyForkStatus = async ({ pullRequest, status, state, draft }) => {\n  if (status === 'draft') {\n    // Converting the pull request to a work in progress keeps it — and the discussion on it — in\n    // place while taking it out of the maintainers’ review queue\n    if (state === 'open' && !draft) {\n      await updateDraftState(pullRequest, true);\n    }\n  } else {\n    if (state === 'closed') {\n      await reopenPullRequest(pullRequest);\n    }\n\n    if (draft) {\n      await updateDraftState(pullRequest, false);\n    }\n  }\n};\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 work in\n * progress, 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\n * no 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: 'number',\n    createRequest: createPullRequest,\n    fetchRequest: fetchForkRequestState,\n    applyStatus: applyForkStatus,\n    fetchBranchHead,\n    deleteBranch,\n  });\n","import { commitChanges } from '$lib/services/backends/git/gitea/commits';\nimport { getWorkflowRepository } from '$lib/services/backends/git/gitea/fork';\nimport {\n  createPullRequest,\n  deleteBranch,\n  fetchAllPages,\n  fetchBranchHead,\n  fetchChangedFiles,\n  fetchFileSHA,\n  fetchPullRequestFileContents,\n  fetchPullRequestFileList,\n  isSameRepositoryPullRequest,\n  parsePullRequest,\n  resolveChangeSHAs,\n  updateDraftState,\n  updateLabels,\n} from '$lib/services/backends/git/gitea/pull-requests';\nimport { repository } from '$lib/services/backends/git/gitea/repository';\nimport {\n  fetchForkPullRequests,\n  updateForkStatus,\n} from '$lib/services/backends/git/gitea/workflow-fork';\nimport { fetchAPI } from '$lib/services/backends/git/shared/api';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { checkPublishAllowed } from '$lib/services/backends/git/shared/fork';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport {\n  assertBranchAtHead,\n  commitToNewWorkflowBranch,\n  getParentDirs,\n  isSquashMergeEnabled,\n  saveWorkflowBranch,\n  toChangedFilesWithModes,\n} from '$lib/services/backends/git/shared/workflow';\nimport { getAllStatusLabels } from '$lib/services/workflow/labels';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * CommitOptions,\n * CommitResults,\n * FileChange,\n * WorkflowChangedFile,\n * WorkflowMergeState,\n * WorkflowPullRequest,\n * WorkflowSaveOptions,\n * WorkflowStatus,\n * } from '$lib/types/private';\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.\n * @returns {Promise<WorkflowPullRequest[]>} Pull requests.\n * @see https://docs.gitea.com/api/next/#tag/issue/operation/issueListLabels\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoListPullRequests\n */\nexport const fetchLabelledPullRequests = async () => {\n  const { owner, repo } = repository;\n  const statusLabels = getAllStatusLabels();\n\n  // The status labels are matched by the API rather than by {@link parsePullRequest}, so the item\n  // cap applies to the CMS’s own pull requests instead of the repository’s most recently updated\n  // ones, which could otherwise push the unpublished entries out of the result. The pull request\n  // endpoint takes label IDs and matches a pull request carrying any of them, so the IDs are looked\n  // up first. The issue endpoint takes names instead, but only matches an item carrying all of\n  // them, which no pull request does once more than one status label exists\n  const labelIds = (await fetchAllPages(`/repos/${owner}/${repo}/labels`))\n    .filter(({ name }) => statusLabels.includes(name))\n    .map(({ id }) => id);\n\n  // Without a status label on the repository, no pull request can carry one\n  if (!labelIds.length) {\n    return [];\n  }\n\n  const labelQuery = labelIds.map((id) => `&labels=${id}`).join('');\n\n  const items = await fetchAllPages(\n    `/repos/${owner}/${repo}/pulls?state=open&sort=recentupdate${labelQuery}`,\n  );\n\n  // A pull request carrying more than one status label is listed once for each. The list reports\n  // the head commit as of the instance’s own reference, which can trail a push by a moment, so each\n  // match is read on its own below for the branch’s current head\n  const numbers = [...new Set(items.map(({ number }) => /** @type {number} */ (number)))];\n  /** @type {WorkflowPullRequest[]} */\n  const pullRequests = [];\n\n  await runConcurrently(numbers, async (number) => {\n    const item = /** @type {Record<string, any>} */ (\n      await fetchAPI(`/repos/${owner}/${repo}/pulls/${number}`)\n    );\n\n    const pullRequest = parsePullRequest(item);\n\n    if (pullRequest) {\n      pullRequests.push(pullRequest);\n    }\n  });\n\n  pullRequests.sort((a, b) => b.updatedDate.getTime() - a.updatedDate.getTime());\n\n  await runConcurrently(pullRequests, async (pullRequest) => {\n    await fetchPullRequestFileList(pullRequest);\n    await fetchPullRequestFileContents(pullRequest);\n  });\n\n  return pullRequests;\n};\n\n/**\n * Fetch all the unpublished entries of the signed-in user: the pull requests on the configured\n * repository that carry a CMS status label, or, for an Open Authoring contributor, the workflow\n * branches in their fork.\n * @returns {Promise<WorkflowPullRequest[]>} Pull requests.\n */\nexport const fetchPullRequests = async () =>\n  openAuthoring.current ? fetchForkPullRequests() : fetchLabelledPullRequests();\n\n/**\n * Fetch the open pull request from the given branch of the configured repository, whichever branch\n * it goes to. This is asked about a branch the CMS doesn’t know a pull request for, so one found\n * here is a pull request the board doesn’t show. The open pull requests are listed and matched\n * here, because the lookup by base and head branch returns a pull request in any state — after an\n * entry has been published and edited again, that can be the merged one rather than the open one.\n * @param {string} branch Branch name.\n * @returns {Promise<Record<string, any> | undefined>} Pull request, or `undefined` if none is open\n * from the branch.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoListPullRequests\n */\nconst fetchOpenPullRequest = async (branch) => {\n  const { owner, repo } = repository;\n  const items = await fetchAllPages(`/repos/${owner}/${repo}/pulls?state=open&sort=recentupdate`);\n\n  // A pull request from a fork can have a head branch of the same name, but it isn’t this branch\n  return items.find((item) => item.head?.ref === branch && isSameRepositoryPullRequest(item));\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; see {@link commitToNewWorkflowBranch} for a branch that already\n * exists.\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 { branch = '' } = options;\n  // The configured branch is resolved by the time anything is saved, so it’s always there. With\n  // Open Authoring it names the fork’s copy of the branch, which is where the new branch starts\n  const startBranch = /** @type {string} */ (repository.branch);\n  // A branch created from the start branch starts with the same files, so their SHAs are the ones\n  // to commit against\n  const freshChanges = await resolveChangeSHAs(changes, startBranch);\n\n  return commitToNewWorkflowBranch({\n    branch,\n    // Gitea/Forgejo rejects `new_branch` outright once the branch exists\n    branchExistsStatus: 422,\n    /**\n     * Commit the changes on a branch created from the start branch.\n     * @returns {Promise<CommitResults>} Commit results.\n     */\n    commitFromStart: () => commitChanges(freshChanges, { ...options, startBranch }),\n    /**\n     * Commit the changes onto the existing branch. The branch has moved on from the configured\n     * one, so the SHAs come from the branch itself.\n     * @returns {Promise<CommitResults>} Commit results.\n     */\n    commitOnBranch: async () => commitChanges(await resolveChangeSHAs(changes, branch), options),\n    /**\n     * Look up a pull request open from the branch.\n     * @returns {Promise<string | undefined>} Its reference, or `undefined` if there is none.\n     */\n    findOpenPullRequest: async () => {\n      const openPullRequest = await fetchOpenPullRequest(branch);\n\n      return openPullRequest ? `#${openPullRequest.number}` : undefined;\n    },\n    inUseMessage: 'The workflow branch is in use by another pull request.',\n    deleteBranch,\n  });\n};\n\n/**\n * Commit the given changes onto the branch of an existing pull request. GitHub can be told which\n * commit a commit has to go on top of, but Gitea/Forgejo can’t: a commit lands on whatever the\n * branch points at, and only the files it touches are checked against the blob SHAs it carries. So\n * the branch has to point at the commit the entry was loaded or saved at, which the conflict check\n * has just compared it with, or a commit pushed since — one the board never showed, say, because\n * the instance was still catching up with it — would go out with the save, vouched for by the head\n * recorded afterwards. Without a head on record there’s nothing to compare, which is refused just\n * the same. The blob SHAs are read at that commit too, so a push that lands in the last moment and\n * touches the same files makes the instance refuse the save.\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 branch is gone, or points at another commit than the one on record.\n */\nconst commitToExistingBranch = async (changes, options, pullRequest) => {\n  const { branch = '' } = options;\n\n  const headSHA = await assertBranchAtHead({\n    branch,\n    headSHA: pullRequest.headSHA,\n    fetchBranchHead,\n    getWorkflowRepository,\n  });\n\n  return commitChanges(await resolveChangeSHAs(changes, headSHA), options);\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.\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, { commitToNewBranch, commitToExistingBranch, createPullRequest });\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 work-in-progress 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 = async (pullRequest, status) => {\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 title, so moving between the\n  // 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 * Map of the file statuses the REST API reports to {@link WorkflowChangedFile} ones. A copy adds a\n * file; `changed` and `unchanged` both modify it, the latter being what a binary file or a change\n * of mode alone is reported as.\n * @type {Record<string, WorkflowChangedFile['status']>}\n */\nconst REST_FILE_STATUSES = {\n  added: 'added',\n  copied: 'added',\n  deleted: 'removed',\n  renamed: 'renamed',\n};\n\n/**\n * Map of the content types the REST API reports to Git file modes. The API doesn’t tell an\n * executable file from a regular one, which makes no difference here: both are regular files.\n * @type {Record<string, string>}\n */\nconst CONTENT_TYPE_MODES = {\n  file: '100644',\n  symlink: '120000',\n  submodule: '160000',\n  dir: '040000',\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 changed file list leaves the mode out, so the folders holding\n * the files are listed 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.gitea.com/api/next/#tag/repository/operation/repoGetContentsList\n */\nconst fetchFileModes = async ({ headSHA, paths }) => {\n  const { owner, repo } = repository;\n  /** @type {Map<string, string>} */\n  const modes = new Map();\n\n  await runConcurrently(getParentDirs(paths), async (dir) => {\n    const entries = /** @type {Record<string, any>[]} */ (\n      await fetchAPI(\n        `/repos/${owner}/${repo}/contents${dir ? `/${encodePath(dir)}` : ''}` +\n          `?ref=${encodeURIComponent(headSHA)}`,\n      )\n    );\n\n    entries.forEach(({ path, type }) => {\n      if (type in CONTENT_TYPE_MODES) {\n        modes.set(path, CONTENT_TYPE_MODES[type]);\n      }\n    });\n  });\n\n  return modes;\n};\n\n/**\n * Read the pull request afresh right before it’s merged: where it goes, the commit its branch\n * points at, and the files it changes as of that commit. The merge is pinned to the commit, so the\n * files describe exactly what the merge would bring in, even if the branch moves on meanwhile.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {Promise<WorkflowMergeState>} State.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoGetPullRequest\n */\nexport const fetchMergeState = async (pullRequest) => {\n  const { owner, repo } = repository;\n  const { number } = /** @type {{ number: number }} */ (pullRequest);\n\n  // The head commit of a single pull request is the branch’s own, read when asked\n  const item = /** @type {Record<string, any>} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/pulls/${number}`)\n  );\n\n  const headSHA = /** @type {string | undefined} */ (item.head?.sha);\n\n  // The pull request is read from the configured repository, which is its base repository by\n  // definition. Its name isn’t compared: the instance redirects a renamed repository, whose new\n  // name the pull request would carry\n  const onConfiguredBranches =\n    item.base?.ref === repository.branch && isSameRepositoryPullRequest(item);\n\n  if (!headSHA || !onConfiguredBranches) {\n    return { headSHA, onConfiguredBranches: false, files: [], complete: false };\n  }\n\n  // The branch has moved on from the commit on record, which the check refuses outright, so there’s\n  // no point in waiting for the file list of a commit that won’t be merged. The list is reported as\n  // complete, or the check would put the refusal down to changes it can’t show instead\n  if (headSHA !== pullRequest.headSHA) {\n    return { headSHA, onConfiguredBranches, files: [], complete: true };\n  }\n\n  const { files, complete } = await fetchChangedFiles(number, headSHA);\n\n  return {\n    headSHA,\n    onConfiguredBranches,\n    files: await toChangedFilesWithModes(files, {\n      statusMap: REST_FILE_STATUSES,\n      headSHA,\n      fetchFileModes,\n    }),\n    complete,\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.gitea.com/api/next/#tag/repository/operation/repoGetContents\n */\nexport const fetchUnchangedPaths = async ({ headSHA, paths }) => {\n  const { branch } = /** @type {{ branch: string }} */ (repository);\n  /** @type {Set<string>} */\n  const unchanged = new Set();\n\n  await runConcurrently(paths, async (path) => {\n    const [base, head] = await Promise.all([\n      fetchFileSHA(path, branch, repository),\n      fetchFileSHA(path, headSHA, repository),\n    ]);\n\n    if (base === head) {\n      unchanged.add(path);\n    }\n  });\n\n  return paths.filter((path) => unchanged.has(path));\n};\n\n/**\n * Check whether the given pull request has been merged. The endpoint answers with a status rather\n * than a body: `204 No Content` when it has, `404 Not Found` when it hasn’t.\n * @param {number} number Pull request number.\n * @returns {Promise<boolean>} `true` if the pull request has been merged.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoPullRequestIsMerged\n */\nconst isPullRequestMerged = async (number) => {\n  const { owner, repo } = repository;\n\n  const response = /** @type {Response} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/pulls/${number}/merge`, { responseType: 'raw' })\n  );\n\n  return response.ok;\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 the instance refuse the merge rather than take it along unseen.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoMergePullRequest\n */\nexport const publish = async (pullRequest) => {\n  checkPublishAllowed();\n\n  const { owner, repo } = repository;\n  const { number } = pullRequest;\n  const squash = isSquashMergeEnabled();\n\n  // A successful merge comes back as `200 OK` with an empty body, which can’t be parsed as JSON, so\n  // the response is taken as is and the error case is handled here\n  const response = /** @type {Response} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/pulls/${number}/merge`, {\n      method: 'POST',\n      responseType: 'raw',\n      body: {\n        // These fields were named in Pascal case until Gitea gave them snake case JSON names. A\n        // current Gitea accepts either spelling, while an older one and Forgejo only take the\n        // original names\n        Do: squash ? 'squash' : 'merge',\n        MergeTitleField: pullRequest.title,\n        MergeMessageField: '',\n        // Answered with `409 Conflict` when the branch points elsewhere\n        head_commit_id: pullRequest.headSHA,\n      },\n    })\n  );\n\n  // Everything that stops a merge comes back as `405 Method Not Allowed`, including the pull\n  // request having been merged already — by a maintainer working on the instance while this board\n  // was open, say. That’s the outcome the user asked for, so it’s the branch cleanup below that’s\n  // left to do rather than an error to report. Anything else the status covers, such as a failing\n  // check or a conflict, is a real refusal\n  if (response.status === 405 && (await isPullRequestMerged(/** @type {number} */ (number)))) {\n    await deleteBranch(pullRequest.branch);\n\n    return;\n  }\n\n  if (!response.ok) {\n    const { message } = await response.json().catch(() => ({}));\n\n    throw new Error('Failed to merge the pull request', {\n      cause: { status: response.status, message },\n    });\n  }\n\n  await deleteBranch(pullRequest.branch);\n};\n\n/**\n * Close the pull request without merging it, and delete the workflow branch.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @see https://docs.gitea.com/api/next/#tag/repository/operation/repoEditPullRequest\n */\nexport const discard = async (pullRequest) => {\n  const { owner, repo } = repository;\n\n  // An Open Authoring draft has no pull request yet, so deleting the branch is all there is to do\n  if (pullRequest.number !== undefined) {\n    try {\n      await fetchAPI(`/repos/${owner}/${repo}/pulls/${pullRequest.number}`, {\n        method: 'PATCH',\n        body: { state: 'closed' },\n      });\n    } catch (/** @type {any} */ ex) {\n      // The pull request was merged after the board was loaded, which the instance reports as a\n      // precondition failure on any state change. There’s nothing left to close, and the branch is\n      // still worth tidying up, so carry on\n      if (ex.cause?.status !== 412) {\n        throw ex;\n      }\n    }\n  }\n\n  await deleteBranch(pullRequest.branch);\n};\n\n/**\n * Gitea/Forgejo’s Editorial Workflow implementation.\n * @type {import('$lib/types/private').WorkflowBackendService}\n */\nexport default {\n  fetchPullRequests,\n  savePullRequest,\n  updateStatus,\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","/**\n * @import { CmsConfig, Collection } from '$lib/types/public';\n */\n\n/**\n * Publish modes an entry can be saved with.\n * @typedef {'simple' | 'editorial_workflow'} PublishMode\n */\n\n/**\n * Get the publish mode a collection uses. The collection-level `publish_mode` option overrides the\n * site-level one, so Editorial Workflow can be enabled for some collections only, or turned off for\n * a collection while it’s enabled everywhere else.\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, which\n * is what a collection without the option, such as the singleton collection, falls back to.\n * @returns {PublishMode} Publish mode. An empty string at the site level is the same as `simple`.\n * @see https://github.com/decaporg/decap-cms/issues/1571\n */\nexport const getPublishMode = ({ cmsConfig, collection }) =>\n  collection?.publish_mode || cmsConfig?.publish_mode || 'simple';\n\n/**\n * Check whether Editorial 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 the workflow.\n */\nexport const isWorkflowConfigured = (cmsConfig) =>\n  getPublishMode({ cmsConfig }) === 'editorial_workflow' ||\n  // The parser runs on the raw configuration, where the collections may not be a list at all\n  (Array.isArray(cmsConfig?.collections) &&\n    cmsConfig.collections.some(\n      (collection) =>\n        // A divider has no publish mode\n        !('divider' in collection) &&\n        getPublishMode({ cmsConfig, collection }) === 'editorial_workflow',\n    ));\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { getTokenPageURL, signIn, signOut } from '$lib/services/backends/git/gitea/auth';\nimport {\n  commitChanges,\n  fetchFileCommits,\n  fetchLastCommit,\n} from '$lib/services/backends/git/gitea/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/gitea/constants';\nimport { fetchBlob, fetchDirSHA, fetchFiles } from '$lib/services/backends/git/gitea/files';\nimport { getBaseURLs, repository } from '$lib/services/backends/git/gitea/repository';\nimport workflow from '$lib/services/backends/git/gitea/workflow';\nimport { initGitBackend } from '$lib/services/backends/git/shared/init';\nimport { cmsConfig } from '$lib/services/config';\nimport { isWorkflowConfigured } from '$lib/services/workflow/config';\n\n/**\n * @import { BackendService, RepositoryInfo } from '$lib/types/private';\n */\n\n/**\n * Initialize the Gitea/Forgejo backend.\n * @returns {RepositoryInfo | undefined} Repository info, or nothing when the configured backend is\n * not Gitea/Forgejo.\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    // https://HOSTNAME/api/v1 or https://HOSTNAME/PATH/api/v1\n    api_root: restApiRoot = DEFAULT_API_ROOT,\n    include_credentials: includeCredentials = false,\n  } = backend;\n\n  const [owner, repo] = /** @type {string} */ (projectPath).split('/');\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    authPath,\n    tokenPath: '/access_token',\n    api: {\n      clientId,\n      // Editorial Workflow stores the status of an unpublished entry as a label on the pull\n      // request, and labels live under the issue scope. It’s only requested when the feature is\n      // enabled — which a single collection can do on its own — so a regular setup doesn’t have to\n      // ask for more than it uses\n      authScope: [\n        'read:repository',\n        'write:repository',\n        ...(isWorkflowConfigured(cmsConfig.current) ? ['read:issue', 'write:issue'] : []),\n        'read:user',\n      ].join(','),\n      restBaseURL: stripSlashes(restApiRoot),\n      includeCredentials,\n    },\n  });\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  init,\n  signIn,\n  signOut,\n  fetchFiles,\n  fetchLastCommit,\n  fetchBlob,\n  fetchDirSHA,\n  commitChanges,\n  fetchFileCommits,\n  workflow,\n};\n","export const BACKEND_NAME = 'github';\nexport const BACKEND_LABEL = 'GitHub';\n\nexport const DEFAULT_API_ROOT = 'https://api.github.com';\nexport const DEFAULT_AUTH_ROOT = 'https://api.netlify.com';\nexport const DEFAULT_AUTH_PATH = 'auth';\nexport const DEFAULT_PKCE_AUTH_ROOT = 'https://github.com';\nexport const DEFAULT_PKCE_AUTH_PATH = 'login/oauth/authorize';\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { DEFAULT_API_ROOT } from '$lib/services/backends/git/github/constants';\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. This is required because, unlike other backends, the\n * default `api_root` for GitHub does not end with `/api/v3`, which may lead to misconfigured URLs.\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) => {\n  url = stripSlashes(url);\n\n  if (url === DEFAULT_API_ROOT) {\n    // Default API root for GitHub is https://api.github.com\n    return url;\n  }\n\n  if (url.endsWith('/api/v3')) {\n    // Already normalized\n    return url;\n  }\n\n  if (url.endsWith('/api')) {\n    return `${url}/v3`;\n  }\n\n  return `${url}/api/v3`;\n};\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) => {\n  url = stripSlashes(url);\n\n  if (url === DEFAULT_API_ROOT) {\n    // Default GraphQL API root for GitHub is https://api.github.com/graphql\n    return `${url}/graphql`;\n  }\n\n  if (url.endsWith('/graphql')) {\n    // Already normalized\n    return url;\n  }\n\n  if (url.endsWith('/api/v3')) {\n    // Replace the REST API v3 endpoint with the GraphQL endpoint\n    return url.replace(/\\/v3$/, '/graphql');\n  }\n\n  if (url.endsWith('/api')) {\n    return `${url}/graphql`;\n  }\n\n  return `${url}/api/graphql`;\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","import { getUserProfile } from '$lib/services/backends/git/github/user';\nimport { signInToBackend } 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} repoURL Repository URL, e.g. `https://github.com/owner/repo`.\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 = (repoURL) => {\n  const { origin } = new URL(repoURL);\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.\n * @param {SignInOptions} options Options.\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 signIn = (options) => signInToBackend({ options, getUserProfile });\n\nexport { signOut } from '$lib/services/backends/git/shared/auth';\n","import { recordBranchAccess } from '$lib/services/backends/branch-access';\nimport { fetchAPI, fetchGraphQL, graphqlVars } 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  applyDefaultBranch,\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 = (repoURL, branch) => ({\n  treeBaseURL: branch ? `${repoURL}/tree/${branch}` : repoURL,\n  blobBaseURL: branch ? `${repoURL}/blob/${branch}` : '',\n  commitBaseURL: `${repoURL}/commit`,\n});\n\n/**\n * HTTP statuses that mean the signed-in user can’t see the repository at all. A private repository\n * answers a request from someone without access with a 404 rather than a 403, so its existence\n * isn’t leaked. A 401 means the token has expired or been revoked.\n */\nconst NO_ACCESS_STATUSES = [401, 403, 404];\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 * Check if the user has write access to the current repository, which takes the write, maintain or\n * admin role, like Netlify/Decap CMS requires. The repository reports the authenticated user’s own\n * permissions, however they’re granted, including through an organization team. Asking the\n * collaborator endpoint instead would let a read-only collaborator in.\n * @throws {Error} If the user can’t push to the repository, or the access couldn’t be checked.\n * @see https://docs.github.com/en/rest/repos/repos#get-a-repository\n */\nexport const checkRepositoryAccess = async () => {\n  const { owner, repo } = repository;\n\n  const response = /** @type {Response} */ (\n    await fetchAPI(`/repos/${owner}/${repo}`, {\n      headers: { Accept: 'application/json' },\n      responseType: 'raw',\n    })\n  );\n\n  // A rate limit or an outage leaves the question unanswered. Reading that as “no access” would\n  // clear the credentials and sign the user out over something passing, so report it as a failed\n  // check instead. A `raw` response skips the token refresh, so an expired token (401) still counts\n  // as no access, sending the user back to the sign-in form\n  if (!response.ok && (!NO_ACCESS_STATUSES.includes(response.status) || isRateLimited(response))) {\n    throw createLocalizedError(\n      'Failed to check the repository permission.',\n      'open_authoring.permission_check_failed',\n      { repo: `${owner}/${repo}` },\n    );\n  }\n\n  const { permissions } = response.ok\n    ? /** @type {{ permissions?: { push?: boolean } }} */ (await response.json())\n    : {};\n\n  if (!permissions?.push) {\n    throw createLocalizedError(NOT_COLLABORATOR_ERROR_MESSAGE, 'repository_no_access', { repo });\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 { _ } from '@sveltia/i18n';\n\nimport {\n  fetchDefaultBranchName,\n  isRateLimited,\n  repository,\n} from '$lib/services/backends/git/github/repository';\nimport { fetchAPI, fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport {\n  ensureForkPermission,\n  isOpenAuthoringConfiguredFor,\n  pollForFork,\n  resolveWorkflowRepository,\n  runOpenAuthoringSetUp,\n} from '$lib/services/backends/git/shared/fork';\nimport { user } from '$lib/services/user/account.svelte';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\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 * HTTP statuses that mean the signed-in user can’t see the repository at all. A private repository\n * answers a request from someone without access with a 404 rather than a 403, so its existence\n * isn’t leaked.\n */\nconst NO_ACCESS_STATUSES = [403, 404];\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  const { owner, repo } = repository;\n  const repoPath = `${owner}/${repo}`.toLowerCase();\n\n  try {\n    const invitations = /** @type {Record<string, any>[]} */ (\n      await fetchAPI('/user/repository_invitations')\n    );\n\n    return invitations.some(\n      ({ repository: invited }) => invited?.full_name?.toLowerCase() === repoPath,\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<string>} Message to show.\n */\nconst getNoAccessMessage = async (response) => {\n  const { owner, repo } = repository;\n  const repoPath = `${owner}/${repo}`;\n\n  if (await hasPendingInvitation()) {\n    return _('open_authoring.invitation_pending', { values: { repo: repoPath } });\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 _('open_authoring.private_repo_scope_required', { values: { repo: repoPath } });\n  }\n\n  return _('repository_no_access', { values: { repo: repoPath } });\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. Both come from the repository itself,\n * which reports the authenticated user’s own permissions. Asking the collaborator endpoint instead\n * would need administrator access to answer, so a maintainer who merely has write access would be\n * turned away as though they had none.\n * @returns {Promise<{ canWrite: boolean, allowForking: 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 * @see https://docs.github.com/en/rest/repos/repos#get-a-repository\n */\nexport const fetchRepositoryAccess = async () => {\n  const { owner, repo } = repository;\n  const repoPath = `${owner}/${repo}`;\n\n  const response = /** @type {Response} */ (\n    await fetchAPI(`/repos/${owner}/${repo}`, {\n      headers: { Accept: 'application/json' },\n      responseType: 'raw',\n    })\n  );\n\n  if (response.ok) {\n    const {\n      permissions,\n      private: isPrivate,\n      owner: repoOwner,\n      allow_forking: allowForking,\n    } = await response.json();\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 (isPrivate && repoOwner?.type === 'User') {\n      // eslint-disable-next-line no-console\n      console.warn(\n        `Open Authoring is enabled, but the ${repoPath} repository is private and owned by a ` +\n          'personal account. GitHub does not allow read-only collaborators there, so everyone ' +\n          'who can sign in can also write to the repository and no one is treated as a ' +\n          'contributor. Transfer the repository to an organization to use Open Authoring with it.',\n      );\n    }\n\n    // `push` covers the write, maintain and admin roles\n    return { canWrite: !!permissions?.push, allowForking: allowForking !== false };\n  }\n\n  // Open Authoring still needs the contributor to be able to read the repository, so being unable\n  // to see it is a dead end rather than a reason to fall back to a fork\n  if (NO_ACCESS_STATUSES.includes(response.status) && !isRateLimited(response)) {\n    throw new Error('No access to the repository', {\n      cause: new Error(await getNoAccessMessage(response)),\n    });\n  }\n\n  // A rate limit or an outage leaves the question unanswered. Reading that as “no write access”\n  // would send a maintainer down the fork path over something passing, and offer to create a copy\n  // of a repository they can already write to, so make the failure visible instead\n  throw createLocalizedError(\n    'Failed to check the repository permission.',\n    'open_authoring.permission_check_failed',\n    { repo: repoPath },\n  );\n};\n\n/**\n * Look for the fork at the name GitHub gives it by default, which is the parent’s. This is where it\n * is unless the contributor renamed it, or already had a repository of that name when the fork was\n * made, in which case GitHub added a suffix. A repository that happens to share the name but isn’t\n * a fork of the configured one is ignored.\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 */\nexport const fetchForkByName = async () => {\n  const { owner, repo } = repository;\n  const userName = /** @type {string} */ (user.account?.login);\n\n  const response = /** @type {Response} */ (\n    await fetchAPI(`/repos/${encodeURIComponent(userName)}/${repo}`, {\n      headers: { Accept: 'application/json' },\n      responseType: 'raw',\n    })\n  );\n\n  if (!response.ok) {\n    return undefined;\n  }\n\n  const result = await response.json();\n  const parent = result.parent?.full_name?.toLowerCase();\n\n  // GitHub redirects a repository that has been transferred, so check that the fork found is still\n  // the user’s own, the way {@link fetchForkFromNetwork} does\n  if (\n    !result.fork ||\n    parent !== `${owner}/${repo}`.toLowerCase() ||\n    result.owner?.login?.toLowerCase() !== userName.toLowerCase()\n  ) {\n    return undefined;\n  }\n\n  const [forkOwner, forkRepo] = result.full_name.split('/');\n\n  return { owner: forkOwner, repo: forkRepo };\n};\n\nconst FETCH_USER_FORK_QUERY = `\n  query($owner: String!, $repo: String!) {\n    repository(owner: $owner, name: $repo) {\n      forks(ownerAffiliations: [OWNER], first: 1) {\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, so its worst case is the behavior without\n * it: no fork found, and the contributor asked whether to make 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  try {\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    const [forkOwner, forkRepo] = node.nameWithOwner.split('/');\n\n    return { owner: forkOwner, repo: forkRepo };\n  } catch {\n    return undefined;\n  }\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 attempts remaining, used for the recursive retry.\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(`/repos/${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(`/repos/${owner}/${repo}/forks`, { method: 'POST' })\n    );\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.error('Failed to fork the repository.', ex);\n\n    throw createLocalizedError('Failed to fork the repository.', 'open_authoring.fork_failed', {\n      repo: `${owner}/${repo}`,\n    });\n  }\n\n  const [forkOwner, forkRepo] = result.full_name.split('/');\n  /** @type {RepositoryPath} */\n  const fork = { owner: forkOwner, repo: forkRepo };\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 with the configured repository, so a\n * new workflow branch starts from what’s currently on the site and the resulting pull request only\n * contains the entry being edited. A failure is logged rather than raised: a fork that has drifted\n * still works, it just makes for a noisier pull request.\n * @param {RepositoryPath} fork Fork to update.\n * @see https://docs.github.com/en/rest/branches/branches#sync-a-fork-branch-with-the-upstream-repository\n */\nexport const syncFork = async ({ owner, repo }) => {\n  /** @type {Response | undefined} */\n  let response;\n\n  try {\n    response = /** @type {Response} */ (\n      await fetchAPI(`/repos/${owner}/${repo}/merge-upstream`, {\n        method: 'POST',\n        body: { branch: repository.branch },\n        responseType: 'raw',\n      })\n    );\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.warn(`Failed to sync the ${owner}/${repo} fork with the upstream repository.`, ex);\n\n    return;\n  }\n\n  // The request answers with a conflict when the fork has commits of its own on the branch, which\n  // is a state the CMS can’t resolve on the contributor’s behalf\n  if (!response.ok) {\n    // eslint-disable-next-line no-console\n    console.warn(\n      `The ${owner}/${repo} fork could not be fast-forwarded to the upstream repository.`,\n    );\n  }\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.\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  const { canWrite, allowForking } = await fetchRepositoryAccess();\n\n  // A maintainer keeps working on the configured repository, as if Open Authoring was off\n  if (canWrite) {\n    return;\n  }\n\n  const { owner, repo } = repository;\n  const repoPath = `${owner}/${repo}`;\n\n  // Syncing the fork needs the branch name, which is otherwise resolved later in the data load\n  if (!repository.branch) {\n    await fetchDefaultBranchName();\n  }\n\n  const existingFork = await fetchFork();\n\n  if (existingFork) {\n    await syncFork(existingFork);\n    forkedRepository.current = existingFork;\n\n    return;\n  }\n\n  // Forking is turned off by default on a private repository, and can be turned off on a public one\n  await ensureForkPermission({ repoPath, allowForking });\n\n  forkedRepository.current = await createFork();\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","/**\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","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","import { encodeBase64 } from '@sveltia/utils/file';\n\nimport { getWorkflowRepository } 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 { fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport {\n  assertBranchNotMoved,\n  createCommitMessage,\n  dedupeFileCommits,\n} from '$lib/services/backends/git/shared/commits';\nimport { createLocalizedError } from '$lib/services/backends/git/shared/errors';\nimport { checkDirectCommitAllowed } from '$lib/services/backends/git/shared/fork';\nimport { repositoryHead } from '$lib/services/backends/git/shared/head';\nimport { getByteSize } from '$lib/services/utils/file';\n\n/**\n * @import { CommitOptions, CommitResults, FileChange, FileCommit } from '$lib/types/private';\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 workflow branches — the contributor’s fork with Open\n * Authoring, and the configured repository otherwise.\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 } = branchName ? getWorkflowRepository() : repository;\n  const branch = branchName ?? 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 createLocalizedError('Failed to retrieve the last commit hash.', 'repository_not_found', {\n      repo,\n    });\n  }\n\n  if (!result.repository.ref) {\n    throw createLocalizedError('Failed to retrieve the last commit hash.', 'branch_not_found', {\n      repo,\n      branch,\n    });\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 * A file addition in a commit mutation, along with the change it comes from.\n * @typedef {object} FileAddition\n * @property {number} index Index of the addition in the changeset, which is used to alias the file\n * in the query for its new SHA.\n * @property {string} path File path.\n * @property {string} contents Base64-encoded file contents.\n * @property {FileChange['data']} data Original file data.\n */\n\n/**\n * Split file additions into groups, each of which is committed in a single mutation. Assets come\n * first and text files like entries last, so an entry never lands in the repository before the\n * files it refers to. The deletions go into the last commit, so a file that is deleted and added\n * again at the same path, which GitHub resolves within a single commit, goes into the last group\n * as well, however large it is; 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 {FileAddition[][]} Groups of file additions. There is always at least one group, which\n * can be empty, so a changeset with only deletions is still committed.\n */\nexport const splitAdditions = (additions, deletedPaths = new Set()) => {\n  /** @type {FileAddition[][]} */\n  const groups = [[]];\n  let size = 0;\n\n  additions\n    .filter(({ path }) => !deletedPaths.has(path))\n    .toSorted((a, b) => Number(typeof a.data === 'string') - Number(typeof b.data === 'string'))\n    .forEach((addition) => {\n      const { length } = addition.contents;\n\n      // A single file over the limit goes on its own\n      if (size && size + length > MAX_COMMIT_PAYLOAD_SIZE) {\n        groups.push([]);\n        size = 0;\n      }\n\n      /** @type {FileAddition[]} */ (groups.at(-1)).push(addition);\n      size += length;\n    });\n\n  /** @type {FileAddition[]} */ (groups.at(-1)).push(\n    ...additions.filter(({ path }) => deletedPaths.has(path)),\n  );\n\n  return groups;\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 {boolean} args.onWorkflowBranch Whether the commit goes to an Editorial Workflow branch.\n * @returns {Promise<Record<string, any>>} Commit, including the new file SHAs aliased as\n * `file_{index}`.\n */\nconst createCommit = async ({\n  owner,\n  repo,\n  branch,\n  expectedHeadOid,\n  additions,\n  deletions,\n  message,\n  onWorkflowBranch,\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: { headline: message },\n  };\n\n  try {\n    const {\n      createCommitOnBranch: { commit },\n    } = /** @type {{ createCommitOnBranch: { commit: Record<string, any> }}} */ (\n      await fetchGraphQL(query, { input })\n    );\n\n    return commit;\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(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.\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, while the configured\n  // branch is only ever committed to by someone who can write to the configured repository\n  const { owner, repo } = options.branch ? getWorkflowRepository() : repository;\n  const branch = /** @type {string} */ (options.branch ?? 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  const groups = splitAdditions(additions, new Set(deletions.map(({ path }) => path)));\n  const message = createCommitMessage(changes, options);\n  let expectedHeadOid = await getExpectedHeadOid(options);\n  /** @type {Record<string, any>} */\n  let commit = {};\n  /** @type {Record<string, any>} */\n  const fileShas = {};\n\n  // Commit the groups one by one, each on top of the previous one. The deletions go into the last\n  // commit along with the entries, so a file isn’t removed before the entry stops referring to it\n  // eslint-disable-next-line no-restricted-syntax\n  for (const [groupIndex, group] of groups.entries()) {\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: group,\n        deletions: groupIndex === groups.length - 1 ? deletions : [],\n        message,\n        onWorkflowBranch: !!options.branch,\n      });\n    } catch (ex) {\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 under\n      // the same paths instead, with the same content, along with the entry. A workflow branch\n      // isn’t tracked this way; it’s reset from scratch when no pull request comes out of it\n      if (groupIndex > 0 && !options.branch) {\n        repositoryHead.current = expectedHeadOid;\n      }\n\n      throw ex;\n    }\n\n    Object.assign(fileShas, commit);\n    expectedHeadOid = commit.oid;\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/**\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: 100, path: ${JSON.stringify(path)}) {\n              nodes {\n                oid\n                author {\n                  name\n                  email\n                  avatarUrl\n                  user { login }\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        sha: node.oid,\n        authorName: node.author.name,\n        authorEmail: node.author.email,\n        authorAvatarURL: node.author.avatarUrl,\n        authorLogin: node.author.user?.login,\n        date: new Date(node.committedDate),\n      })),\n    ),\n  );\n};\n","import { 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} [url] URL reported alongside the candidate, if any.\n * @property {DeployState} state Normalized state.\n * @property {string} [description] Message the provider attached to the candidate, used to spot a\n * 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  // @ts-ignore The option is GitHub/GitLab only\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 | 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    url: best.url,\n    context: best.name,\n    checkedTime: Date.now(),\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","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 { findURLInSummary, resolveDeployments } from '$lib/services/backends/git/shared/deployment';\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  const { owner, repo } = repository;\n\n  return /** @type {Promise<Response>} */ (\n    fetchAPI(`/repos/${owner}/${repo}/dispatches`, {\n      method: 'POST',\n      body: { event_type: 'sveltia-cms-publish' },\n      responseType: 'raw',\n    })\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  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      (commit?.status?.contexts ?? []).forEach(\n        (/** @type {Record<string, any>} */ { context, state, targetUrl, description }) => {\n          const mapped = STATUS_STATE_MAP[state];\n\n          if (mapped) {\n            candidateMap[sha].push({\n              name: context ?? '',\n              url: targetUrl ?? undefined,\n              state: mapped,\n              description: description ?? undefined,\n              source: 'status',\n            });\n          }\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      (commit?.deployments?.nodes ?? []).forEach(\n        (/** @type {Record<string, any>} */ { environment, latestStatus }) => {\n          const mapped = DEPLOYMENT_STATE_MAP[latestStatus?.state];\n\n          if (mapped) {\n            candidateMap[sha].push({\n              name: environment ?? '',\n              url: latestStatus?.environmentUrl ?? undefined,\n              state: mapped,\n              description: latestStatus?.description ?? undefined,\n              source: 'deployment',\n            });\n          }\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      (commit?.checkSuites?.nodes ?? []).forEach((/** @type {Record<string, any>} */ suite) => {\n        (suite?.checkRuns?.nodes ?? []).forEach(\n          (\n            /** @type {Record<string, any>} */ { name, status, conclusion, detailsUrl, summary },\n          ) => {\n            // A run that hasn’t finished has no conclusion yet, so the status carries the state\n            const mapped = status === 'COMPLETED' ? CHECK_CONCLUSION_MAP[conclusion] : 'pending';\n\n            if (mapped) {\n              candidateMap[sha].push({\n                name: name ?? '',\n                // A URL published in the output is the provider saying where the site went, so it’s\n                // taken at face value. The check’s own link is usually a build page, and is trusted\n                // only when the run names itself a preview, as AWS Amplify’s does\n                url:\n                  findURLInSummary(summary, detailsUrl) ??\n                  (PREVIEW_CHECK_NAME_REGEX.test(name ?? '')\n                    ? (detailsUrl ?? undefined)\n                    : undefined),\n                state: mapped,\n                source: 'check',\n              });\n            }\n          },\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    Object.values(SOURCES).map(async ({ selection, parse }) => {\n      try {\n        const commits = await fetchCommits(shas, selection);\n\n        shas.forEach((sha, index) => parse(commits[index], sha, candidateMap));\n      } catch (ex) {\n        // A missing or restricted field shouldn’t take the other sources down with it\n        // eslint-disable-next-line no-console\n        console.warn('Failed to fetch the deployment info.', ex);\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","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 mime from 'mime';\n\nimport { fetchLastCommit } from '$lib/services/backends/git/github/commits';\nimport {\n  getWorkflowRepository,\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 { toFileListItems } from '$lib/services/backends/git/shared/tree';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport { getRootDir } from '$lib/services/backends/root-dir';\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 { owner, repo } = repository;\n  const query = recursive ? '?recursive=1' : '';\n\n  return /** @type {{ tree: GitTreeEntry[], truncated: boolean }} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/git/trees/${encodePath(treeRef)}${query}`)\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          }\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(`/repos/${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 } = commit;\n      const user = author?.user;\n\n      return [\n        [\n          path,\n          {\n            // The author can be `null` when the commit has no valid author info\n            commitAuthor: 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    checkAccess: 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, which lives in the\n  // contributor’s fork with Open Authoring, so the blob has to be read from there\n  const { owner, repo } = asset.workflow ? getWorkflowRepository() : repository;\n  const { sha, path } = 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  // Handle SVG and other non-binary files\n  if (response.headers.get('Content-Type') !== 'application/octet-stream') {\n    return new Blob([await response.text()], { type: mime.getType(path) ?? 'text/plain' });\n  }\n\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 * The URL of the GitHub status dashboard.\n */\nexport const STATUS_DASHBOARD_URL = 'https://www.githubstatus.com/';\n\n/**\n * The URL to check the GitHub service status.\n */\nconst STATUS_CHECK_URL = 'https://www.githubstatus.com/api/v2/status.json';\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 = async () => {\n  try {\n    const {\n      status: { indicator },\n    } = /** @type {{ status: { indicator: string }}} */ (await sendRequest(STATUS_CHECK_URL));\n\n    if (indicator === 'none') {\n      return 'none';\n    }\n\n    if (indicator === 'minor') {\n      return 'minor';\n    }\n\n    if (indicator === 'major' || indicator === 'critical') {\n      return 'major';\n    }\n  } catch {\n    //\n  }\n\n  return 'unknown';\n};\n","import { fetchBlobText } from '$lib/services/backends/git/github/files';\nimport { getWorkflowRepository } 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 { PULL_REQUEST_DESCRIPTION } from '$lib/services/backends/git/shared/pull-requests';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport { deleteRemoteBranch } from '$lib/services/backends/git/shared/workflow';\nimport { getAllStatusLabels, getStatusLabel } from '$lib/services/workflow/labels';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { WorkflowFile, WorkflowPullRequest, WorkflowStatus } 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 * Convert the changed files of a pull request or comparison, as listed by the REST API, to workflow\n * files.\n * @param {Record<string, any>[]} files Files.\n * @returns {WorkflowFile[]} Files.\n */\nexport const parseRestFiles = (files) =>\n  files.map(({ filename, status, previous_filename: previousPath }) => ({\n    path: filename,\n    sha: '',\n    size: 0,\n    deleted: status === 'removed',\n    previousPath,\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 { owner, repo } = repository;\n\n  const files = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(\n      `/repos/${owner}/${repo}/pulls/${pullRequest.number}/files?per_page=${MAX_ITEMS.files}`,\n    )\n  );\n\n  pullRequest.files = parseRestFiles(files);\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  // A workflow branch lives in the contributor’s fork with Open Authoring, so that’s where the\n  // blobs have to be read from\n  const workflowRepository = getWorkflowRepository();\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.\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 } = getWorkflowRepository();\n\n  const { repository: result } = /** @type {{ repository: Record<string, any> }} */ (\n    await fetchGraphQL(FETCH_BRANCH_HEAD_QUERY, { owner, repo, branch: `refs/heads/${branch}` })\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 { owner, repo } = getWorkflowRepository();\n\n  await deleteRemoteBranch({\n    branch,\n    path: `/repos/${owner}/${repo}/git/refs/heads/${encodePath(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  const { owner, repo } = repository;\n  const cmsLabels = getAllStatusLabels();\n\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(`/repos/${owner}/${repo}/pulls/${pullRequest.number}`)\n  );\n\n  const newLabels = [\n    ...labels.map(({ name }) => name).filter((name) => !cmsLabels.includes(name)),\n    getStatusLabel(status),\n  ];\n\n  await fetchAPI(`/repos/${owner}/${repo}/issues/${pullRequest.number}`, {\n    method: 'PATCH',\n    body: { labels: newLabels },\n  });\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 * @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 }) => {\n  const { owner, repo, branch: baseBranch } = repository;\n  const fork = forkedRepository.current;\n  const isDraft = status === 'draft';\n\n  const result = /** @type {Record<string, any>} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/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: isDraft,\n        body: PULL_REQUEST_DESCRIPTION,\n      },\n    })\n  );\n\n  /** @type {WorkflowPullRequest} */\n  const pullRequest = {\n    number: result.number,\n    nodeId: result.node_id,\n    title: result.title,\n    url: result.html_url,\n    branch,\n    headSHA: result.head?.sha,\n    status,\n    createdDate: new Date(result.created_at),\n    updatedDate: new Date(result.updated_at),\n    files: [],\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(`/repos/${owner}/${repo}/issues/${result.number}/labels`, {\n      method: 'POST',\n      body: { labels: [getStatusLabel(status)] },\n    });\n  }\n\n  return pullRequest;\n};\n\n/**\n * Reopen a pull request that was closed earlier.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @see https://docs.github.com/en/rest/pulls/pulls#update-a-pull-request\n */\nexport const reopenPullRequest = async (pullRequest) => {\n  const { owner, repo } = repository;\n\n  await fetchAPI(`/repos/${owner}/${repo}/pulls/${pullRequest.number}`, {\n    method: 'PATCH',\n    body: { state: 'open' },\n  });\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  parseRestFiles,\n  reopenPullRequest,\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 { encodePath } from '$lib/services/backends/git/shared/url';\nimport { user } from '$lib/services/user/account.svelte';\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 { owner, repo, 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 = encodePath(/** @type {string} */ (baseBranch));\n  const head = `${encodeURIComponent(headOwner)}:${encodePath(pullRequest.branch)}`;\n\n  const { files = [] } = /** @type {{ files?: Record<string, any>[] }} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/compare/${base}...${head}?per_page=${MAX_ITEMS.files}`)\n  );\n\n  pullRequest.files = parseRestFiles(files);\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 {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`.\n * @param {boolean} [args.draft] Whether the pull request is a draft.\n */\nconst applyForkStatus = async ({ pullRequest, status, state, draft }) => {\n  if (status === 'draft') {\n    // Converting the pull request to a draft keeps it — and the discussion on it — in place while\n    // taking it out of the maintainers’ review queue\n    if (state === 'OPEN' && !draft) {\n      await updateDraftState(pullRequest, true);\n    }\n  } else {\n    if (state === 'CLOSED') {\n      await reopenPullRequest(pullRequest);\n    }\n\n    if (draft) {\n      await updateDraftState(pullRequest, false);\n    }\n  }\n};\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 { commitChanges } from '$lib/services/backends/git/github/commits';\nimport { 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  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 } from '$lib/services/backends/git/shared/fork';\nimport { encodePath } from '$lib/services/backends/git/shared/url';\nimport {\n  getParentDirs,\n  isSquashMergeEnabled,\n  openWorkflowPullRequest,\n  toChangedFilesWithModes,\n} from '$lib/services/backends/git/shared/workflow';\nimport { getAllStatusLabels, getStatusFromLabels } from '$lib/services/workflow/labels';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * CommitResults,\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  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 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 * @returns {string} GraphQL query.\n * @see https://docs.github.com/en/graphql/reference/objects#pullrequest\n */\nconst getFetchPullRequestsQuery = () => `\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    }\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  const { login, name, email, databaseId } = node.author ?? {};\n\n  return {\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: login ? { name: name ?? login, email: email ?? '', id: databaseId, login } : undefined,\n    files: parseFileNodes(node.files?.nodes ?? []),\n  };\n};\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, whose branch lives in a\n  // repository this flow can’t read. Labelling one by hand would otherwise put a card on the board\n  // with every file reported as deleted, because the branch isn’t on the configured repository\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(node.labels.nodes.map((/** @type {any} */ l) => l.name));\n\n  if (!status) {\n    return undefined;\n  }\n\n  return toPullRequest(node, status);\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.\n * @returns {Promise<WorkflowPullRequest[]>} Pull requests.\n */\nconst fetchLabelledPullRequests = async () => {\n  const { repository: result } = /** @type {{ repository: Record<string, any> }} */ (\n    await fetchGraphQL(getFetchPullRequestsQuery())\n  );\n\n  const pullRequests = /** @type {WorkflowPullRequest[]} */ (\n    (result?.pullRequests?.nodes ?? []).map(parsePullRequest).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.\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    }\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  const { owner, repo } = repository;\n\n  await fetchAPI(`/repos/${owner}/${repo}/git/refs/heads/${encodePath(branch)}`, {\n    method: 'PATCH',\n    body: { sha, force: true },\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\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  const sha = base.ref.target.oid;\n\n  try {\n    await fetchGraphQL(CREATE_REF_MUTATION, {\n      input: { repositoryId: fork.id, name: `refs/heads/${branch}`, oid: sha },\n    });\n  } catch (/** @type {any} */ ex) {\n    const message = ex.cause?.message ?? '';\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.', { cause: new Error(message || ex.message) });\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 = async (pullRequest, status) => {\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 mutation at all\n  if (isDraft !== (pullRequest.status === 'draft')) {\n    await updateDraftState(pullRequest, isDraft);\n  }\n\n  return { ...pullRequest, status, updatedDate: new Date() };\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.\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 ({ changes, options, branch, title, status, pullRequest }) => {\n  // A save onto an existing pull request goes on top of the commit the entry was loaded or saved\n  // at, which the conflict check has just compared with the branch, rather than whatever the branch\n  // points at by the time the commit is made. A commit pushed in between makes GitHub refuse the\n  // save, instead of being taken along unseen and vouched for by the head recorded afterwards\n  const { headOid } = pullRequest ? { headOid: pullRequest.headSHA } : await createBranch(branch);\n  /** @type {CommitResults} */\n  let commit;\n\n  try {\n    commit = await commitChanges(changes, { ...options, branch, headOid });\n  } catch (ex) {\n    // The branch can have gone, e.g. with a pull request merged or closed on GitHub, which is\n    // worth saying in words rather than with GitHub’s message about a ref it can’t resolve. A\n    // lookup that fails says nothing about the branch, so GitHub’s error is passed on then\n    const branchGone =\n      !!pullRequest &&\n      (await fetchBranchHead(branch).then(\n        (head) => head === undefined,\n        () => false,\n      ));\n\n    if (branchGone) {\n      throw createLocalizedError('Failed to save the changes.', 'branch_not_found', {\n        repo: getWorkflowRepository().repo,\n        branch,\n      });\n    }\n\n    throw ex;\n  }\n\n  if (pullRequest) {\n    return { commit, pullRequest };\n  }\n\n  return {\n    commit,\n    pullRequest: await openWorkflowPullRequest({\n      commit,\n      branch,\n      title,\n      status,\n      createPullRequest,\n    }),\n  };\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 { owner, repo, branch } = repository;\n\n  const { head, base } = /** @type {Record<string, any>} */ (\n    await fetchAPI(`/repos/${owner}/${repo}/pulls/${pullRequest.number}`)\n  );\n\n  const headSHA = /** @type {string | undefined} */ (head?.sha);\n  const fullName = `${owner}/${repo}`.toLowerCase();\n\n  const onConfiguredBranches =\n    base?.ref === branch &&\n    base?.repo?.full_name?.toLowerCase() === fullName &&\n    head?.repo?.full_name?.toLowerCase() === fullName;\n\n  if (!headSHA || !onConfiguredBranches) {\n    return { headSHA, onConfiguredBranches: false, files: [], complete: false };\n  }\n\n  const { files = [] } = /** @type {{ files?: Record<string, any>[] }} */ (\n    await fetchAPI(\n      `/repos/${owner}/${repo}/compare/${encodePath(/** @type {string} */ (branch))}...${headSHA}`,\n    )\n  );\n\n  return {\n    headSHA,\n    onConfiguredBranches,\n    files: await toChangedFilesWithModes(files, {\n      statusMap: REST_FILE_STATUSES,\n      headSHA,\n      fetchFileModes,\n    }),\n    complete: files.length < MAX_COMPARE_FILES,\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.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @see https://docs.github.com/en/rest/pulls/pulls#merge-a-pull-request\n */\nexport const publish = async (pullRequest) => {\n  checkPublishAllowed();\n\n  const { owner, repo } = repository;\n  const squash = isSquashMergeEnabled();\n\n  await fetchAPI(`/repos/${owner}/${repo}/pulls/${pullRequest.number}/merge`, {\n    method: 'PUT',\n    body: {\n      merge_method: squash ? 'squash' : 'merge',\n      commit_title: pullRequest.title,\n      sha: pullRequest.headSHA,\n    },\n  });\n\n  await deleteBranch(pullRequest.branch);\n};\n\n/**\n * Close the pull request without merging it, and delete the workflow branch.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @see https://docs.github.com/en/rest/pulls/pulls#update-a-pull-request\n */\nexport const discard = async (pullRequest) => {\n  const { owner, repo } = repository;\n\n  // An Open Authoring draft has no pull request yet, so deleting the branch is all there is to do\n  if (pullRequest.number !== undefined) {\n    await fetchAPI(`/repos/${owner}/${repo}/pulls/${pullRequest.number}`, {\n      method: 'PATCH',\n      body: { state: 'closed' },\n    });\n  }\n\n  await deleteBranch(pullRequest.branch);\n};\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  fetchBranchHead,\n  fetchMergeState,\n  fetchUnchangedPaths,\n  publish,\n  discard,\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  DEFAULT_PKCE_AUTH_PATH,\n  DEFAULT_PKCE_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 { cmsConfig } from '$lib/services/config';\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    auth_type: authType = '',\n    // @ts-ignore PKCE is not yet supported\n    base_url: authRoot = authType === 'pkce' ? DEFAULT_PKCE_AUTH_ROOT : DEFAULT_AUTH_ROOT,\n    // @ts-ignore PKCE is not yet supported\n    auth_endpoint: authPath = authType === 'pkce' ? DEFAULT_PKCE_AUTH_PATH : 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\n    auth_scope: authScope = 'repo',\n  } = backend;\n\n  const [owner, repo] = /** @type {string} */ (projectPath).split('/');\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    authPath,\n    tokenPath: '/access_token',\n    api: {\n      clientId,\n      authScope: `${authScope},user`,\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","export const BACKEND_NAME = 'gitlab';\nexport const BACKEND_LABEL = 'GitLab';\n\nexport const DEFAULT_API_ROOT = 'https://gitlab.com/api/v4';\nexport const DEFAULT_AUTH_ROOT = 'https://api.netlify.com';\nexport const DEFAULT_AUTH_PATH = 'auth';\nexport const DEFAULT_PKCE_AUTH_ROOT = 'https://gitlab.com';\nexport const DEFAULT_PKCE_AUTH_PATH = 'oauth/authorize';\n","import { BACKEND_NAME } from '$lib/services/backends/git/gitlab/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 GitLab REST API.\n * @param {AuthTokens} tokens Authentication tokens.\n * @returns {Promise<User>} User information.\n * @see https://docs.gitlab.com/api/users.html#list-current-user\n */\nexport const getUserProfile = (tokens) =>\n  fetchUserProfile(tokens, BACKEND_NAME, {\n    name: 'name',\n    login: 'username',\n    profileURL: 'web_url',\n  });\n","import { getUserProfile } from '$lib/services/backends/git/gitlab/user';\nimport { signInToBackend } from '$lib/services/backends/git/shared/auth';\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 GitLab.\n * @param {string} repoURL Repository URL, e.g. `https://gitlab.com/owner/repo`.\n * @returns {string} URL to create a new PAT.\n * @see https://docs.gitlab.com/user/profile/personal_access_tokens/\n */\nexport const getTokenPageURL = (repoURL) => {\n  const { origin } = new URL(repoURL);\n\n  const params = new URLSearchParams({\n    name: 'Sveltia CMS',\n    scopes: 'api,read_user',\n  });\n\n  return `${origin}/-/user_settings/personal_access_tokens?${params}`;\n};\n\n/**\n * Sign in with the GitLab REST API.\n * @param {SignInOptions} options Options.\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 signIn = (options) => signInToBackend({ options, getUserProfile });\n\nexport { signOut } from '$lib/services/backends/git/shared/auth';\n","import { recordBranchAccess } from '$lib/services/backends/branch-access';\nimport { fetchAPI, fetchGraphQL, graphqlVars } 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  applyDefaultBranch,\n  REPOSITORY_INFO_PLACEHOLDER,\n} from '$lib/services/backends/git/shared/repository';\n\n/**\n * @import { RepositoryBaseURLs, RepositoryInfo, RepositoryPath } from '$lib/types/private';\n */\n\n/**\n * Regular expression to split a GitLab project path into a namespace and a project name. In GitLab\n * terminology, an owner is called a namespace, and a repository is called a project. A namespace\n * can contain a group and a subgroup concatenated with a `/` so we cannot simply use `split('/')`\n * here. A project name should not contain a `/`.\n * @see https://docs.gitlab.com/user/namespace/\n * @see https://gitlab.com/gitlab-org/gitlab/-/merge_requests/80055\n */\nconst REPO_PATH_REGEX = /(?<owner>.+)\\/(?<repo>[^/]+)$/;\n\n/** @type {RepositoryInfo} */\nexport const repository = { ...REPOSITORY_INFO_PLACEHOLDER };\n\n/**\n * Split a full project path, such as `group/subgroup/project`, into a namespace and a project name.\n * @param {string} path Full project path.\n * @returns {RepositoryPath} Namespace and project name. Both are `undefined` if the path doesn’t\n * contain a slash.\n */\nexport const parseProjectPath = (path) =>\n  /** @type {RepositoryPath} */ (path.match(REPO_PATH_REGEX)?.groups ?? {});\n\n/**\n * Get the URL-encoded project identifier used in the REST API paths, e.g. the `group/project` path\n * with the slash percent-encoded.\n * @param {RepositoryPath} [repoPath] Project to address. Default: the configured project. With Open\n * Authoring the contributor’s fork is passed here, as that’s where their branches live.\n * @returns {string} Project ID.\n */\nexport const getProjectId = (repoPath) => {\n  const { owner, repo } = repoPath ?? repository;\n\n  return encodeURIComponent(`${owner}/${repo}`);\n};\n\n/**\n * Get the REST API path of the given branch.\n * @param {string} branch Branch name.\n * @param {RepositoryPath} [repoPath] Project holding the branch. Default: the configured project.\n * @returns {string} Path.\n * @see https://docs.gitlab.com/api/branches/\n */\nexport const getBranchPath = (branch, repoPath) =>\n  `/projects/${getProjectId(repoPath)}/repository/branches/${encodeURIComponent(branch)}`;\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 = (repoURL, branch) => ({\n  treeBaseURL: branch ? `${repoURL}/-/tree/${branch}` : repoURL,\n  blobBaseURL: branch ? `${repoURL}/-/blob/${branch}` : '',\n  commitBaseURL: `${repoURL}/-/commit`,\n});\n\nconst FETCH_USER_PERMISSIONS_QUERY = `\n  query($fullPath: ID!) {\n    project(fullPath: $fullPath) {\n      userPermissions {\n        pushCode\n      }\n    }\n  }\n`;\n\n/**\n * Ask what the signed-in user may do with the configured project: whether they can see it at all,\n * and whether they can push to it, which takes the Developer role or higher, like Netlify/Decap CMS\n * requires. The permission reflects the user’s effective role, however it’s granted: direct\n * membership, a parent group, or a group invited to the project or to a parent group. It also works\n * for service accounts, which the members API doesn’t return.\n * @returns {Promise<{ found: boolean, canPush: boolean }>} Whether the project is visible to the\n * user, and whether they can push to it. Open Authoring tells the two apart — a contributor can\n * read the project but not push to it — while the regular access check needs both.\n * @see https://docs.gitlab.com/api/graphql/reference/#projectpermissions\n * @see https://docs.gitlab.com/user/permissions/\n */\nexport const fetchProjectPermissions = async () => {\n  const result = /** @type {{ project: { userPermissions: { pushCode: boolean } } | null }} */ (\n    await fetchGraphQL(FETCH_USER_PERMISSIONS_QUERY)\n  );\n\n  return { found: !!result.project, canPush: !!result.project?.userPermissions.pushCode };\n};\n\n/**\n * Check if the user has write access to the current repository.\n * @throws {Error} If the user can’t push to the repository.\n */\nexport const checkRepositoryAccess = async () => {\n  const { repo } = repository;\n\n  if (!(await fetchProjectPermissions()).canPush) {\n    throw createLocalizedError(NOT_COLLABORATOR_ERROR_MESSAGE, 'repository_no_access', { repo });\n  }\n};\n\n/**\n * Check if the user can push to the configured branch, and record it in {@link lockedBranch}. The\n * Developer role is enough to sign in, but a protected branch may only allow Maintainers to push,\n * in which case everything that commits to the branch directly is made read-only up front, rather\n * than failing when the user saves. A failed request leaves the branch writable, as GitLab still\n * refuses a push the user isn’t allowed to make.\n * @see https://docs.gitlab.com/api/branches/#get-single-repository-branch\n * @see https://docs.gitlab.com/user/project/repository/branches/protected/\n */\nexport const checkBranchAccess = async () => {\n  await recordBranchAccess(repository.branch, async (branch) => {\n    const result = /** @type {{ can_push?: boolean }} */ (await fetchAPI(getBranchPath(branch)));\n\n    return { canPush: result.can_push };\n  });\n};\n\nconst FETCH_DEFAULT_BRANCH_NAME_QUERY = `\n  query($fullPath: ID!) {\n    project(fullPath: $fullPath) {\n      repository {\n        rootRef\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 * @see https://docs.gitlab.com/api/graphql/reference/#repository\n */\nexport const fetchDefaultBranchName = async () => {\n  const result = /** @type {{ project: { repository?: { rootRef: string } } }} */ (\n    await fetchGraphQL(FETCH_DEFAULT_BRANCH_NAME_QUERY)\n  );\n\n  const branch = applyDefaultBranch(repository, {\n    found: !!result.project,\n    branch: result.project?.repository?.rootRef,\n    getBaseURLs,\n  });\n\n  Object.assign(graphqlVars, { branch });\n\n  return branch;\n};\n","import {\n  fetchProjectPermissions,\n  getProjectId,\n  parseProjectPath,\n  repository,\n} from '$lib/services/backends/git/gitlab/repository';\nimport { fetchAPI } 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  ensureForkPermission,\n  isOpenAuthoringConfiguredFor,\n  pollForFork,\n  resolveWorkflowRepository,\n  runOpenAuthoringSetUp,\n} from '$lib/services/backends/git/shared/fork';\nimport { user } from '$lib/services/user/account.svelte';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { RepositoryPath } from '$lib/types/private';\n */\n\n/**\n * Maximum number of forks to look at when searching for the signed-in user’s own copy of the\n * configured project. The list is already narrowed to the projects they own.\n */\nconst MAX_FORKS = 100;\n\n/**\n * Numeric project ID of the configured project, which is filled in by\n * {@link fetchProjectDetails} — so it’s only set once the signed-in user turns out to be a\n * contributor, as a maintainer never reaches the code that needs it. A couple of GitLab\n * endpoints — opening a merge request across projects, and comparing a fork’s branch with the\n * configured one — take an ID rather than the encoded path every other request uses. `fork` is the\n * contributor’s fork, recorded while it’s looked up, so a merge request can be checked to have come\n * from it rather than from some other project of theirs.\n * @type {{ base: number | undefined, fork: number | undefined }}\n */\nexport const projectIds = { base: undefined, fork: undefined };\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('gitlab');\n\n/**\n * Get the project 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 project otherwise. Content is always read\n * from the configured project, so this is only for writes and for the branches behind them.\n * @returns {RepositoryPath} Project namespace and name.\n */\nexport const getWorkflowRepository = () => resolveWorkflowRepository(repository);\n\n/**\n * Fetch whether the signed-in user can commit to the configured project. The permission query\n * answers both of the questions the sign-in has: a project it can’t see at all is a dead end, while\n * one the user can read but not push to is what Open Authoring is for.\n * @returns {Promise<{ canWrite: boolean }>} Project access.\n * @throws {Error} When the user has no access to the project, or the answer couldn’t be\n * determined — which is not the same thing.\n */\nexport const fetchRepositoryAccess = async () => {\n  const { owner, repo } = repository;\n  const repoPath = `${owner}/${repo}`;\n  /** @type {{ found: boolean, canPush: boolean }} */\n  let permissions;\n\n  try {\n    permissions = await fetchProjectPermissions();\n  } catch {\n    // A spent rate limit or an outage leaves the question unanswered. Reading that as “no write\n    // access” would send a maintainer down the fork path over something passing, and offer to make\n    // a copy of a project they can already write to, so make the failure visible instead\n    throw createLocalizedError(\n      'Failed to check the repository permission.',\n      'open_authoring.permission_check_failed',\n      { repo: repoPath },\n    );\n  }\n\n  // Open Authoring still needs the contributor to be able to read the project, so being unable to\n  // see it is a dead end rather than a reason to fall back to a fork. The shared message is what\n  // the sign-in flow looks for to drop the cached credentials, the same as the regular access check\n  // does, so the user gets the sign-in form rather than the same error on every reload\n  if (!permissions.found) {\n    throw createLocalizedError(NOT_COLLABORATOR_ERROR_MESSAGE, 'repository_no_access', {\n      repo: repoPath,\n    });\n  }\n\n  return { canWrite: permissions.canPush };\n};\n\n/**\n * Fetch what setting a fork up needs from the configured project: its numeric ID, which a couple of\n * endpoints take instead of the encoded path, and whether it can be forked at all. Only a\n * contributor gets this far, so a maintainer’s sign-in doesn’t pay for the request.\n * @returns {Promise<{ allowForking: boolean }>} Whether the project allows forks.\n * @see https://docs.gitlab.com/api/projects/#get-a-single-project\n */\nexport const fetchProjectDetails = async () => {\n  const { owner, repo } = repository;\n  /** @type {Record<string, any>} */\n  let project;\n\n  try {\n    project = /** @type {Record<string, any>} */ (await fetchAPI(`/projects/${getProjectId()}`));\n  } catch {\n    // Nothing can be set up without the project’s ID, and a spent rate limit or an outage is worth\n    // trying again, so say so rather than letting a bare API error reach the contributor\n    throw createLocalizedError(\n      'Failed to read the repository.',\n      'open_authoring.permission_check_failed',\n      { repo: `${owner}/${repo}` },\n    );\n  }\n\n  const { id, forking_access_level: forkingAccessLevel } = project;\n\n  projectIds.base = id;\n\n  // The feature is reported as `enabled`, `private` or `disabled`. An older instance may not report\n  // it at all, in which case the fork request is left to say whether it’s allowed\n  return { allowForking: forkingAccessLevel !== 'disabled' };\n};\n\n/**\n * Look for the fork at the path GitLab gives it by default, which is the parent’s project name\n * under the contributor’s own namespace. This is where it is unless they renamed or moved it. A\n * project that happens to share the name but isn’t a fork of the configured one is ignored.\n * @returns {Promise<RepositoryPath | undefined>} The fork, or `undefined` if it isn’t there.\n * @see https://docs.gitlab.com/api/projects/#get-a-single-project\n */\nexport const fetchForkByName = async () => {\n  const { owner, repo } = repository;\n  const userName = /** @type {string} */ (user.account?.login);\n  /** @type {Record<string, any>} */\n  let result;\n\n  try {\n    result = /** @type {Record<string, any>} */ (\n      await fetchAPI(`/projects/${getProjectId({ owner: userName, repo })}`)\n    );\n  } catch {\n    // The contributor has no project of that name, which is the common case on a first visit\n    return undefined;\n  }\n\n  const parent = result.forked_from_project?.path_with_namespace?.toLowerCase();\n\n  if (parent !== `${owner}/${repo}`.toLowerCase()) {\n    return undefined;\n  }\n\n  // GitLab keeps a redirect for a project that was renamed or transferred, so the path it resolved\n  // can sit in a namespace other than the one asked for. Everything the CMS writes goes to this\n  // project, so take it only once it’s confirmed to be the signed-in user’s own\n  if (result.namespace?.kind !== 'user' || result.namespace?.full_path !== userName) {\n    return undefined;\n  }\n\n  projectIds.fork = result.id;\n\n  return parseProjectPath(result.path_with_namespace);\n};\n\n/**\n * Ask the configured project for the fork the signed-in user owns, wherever it’s named. This only\n * runs when {@link fetchForkByName} came up empty, so its worst case is the behavior without it: no\n * fork found, and the contributor asked whether to make one.\n * @returns {Promise<RepositoryPath | undefined>} The fork, or `undefined` if there is none.\n * @see https://docs.gitlab.com/api/project_forks/#list-forks-of-a-project\n */\nexport const fetchForkFromNetwork = async () => {\n  const userName = user.account?.login;\n\n  try {\n    const forks = /** @type {Record<string, any>[]} */ (\n      await fetchAPI(`/projects/${getProjectId()}/forks?owned=true&per_page=${MAX_FORKS}`)\n    );\n\n    // Check the namespace rather than trusting the filter to have applied: committing to a fork in\n    // a group the contributor merely belongs to would put their drafts somewhere unexpected\n    const fork = forks.find(\n      ({ namespace }) => namespace?.kind === 'user' && namespace?.full_path === userName,\n    );\n\n    if (!fork) {\n      return undefined;\n    }\n\n    projectIds.fork = fork.id;\n\n    return parseProjectPath(fork.path_with_namespace);\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Look for an existing fork of the configured project on the signed-in user’s namespace.\n * @returns {Promise<RepositoryPath | undefined>} The fork, or `undefined` if there is none.\n */\nexport const fetchFork = async () => (await fetchForkByName()) ?? fetchForkFromNetwork();\n\n/**\n * Import states that mean the fork is ready to be committed to. `none` is what a project that was\n * never imported reports, which is what an older GitLab says about a finished fork.\n */\nconst FORK_READY_STATUSES = ['none', 'finished'];\n\n/**\n * Wait until a newly requested fork can be committed to. GitLab copies the repository in the\n * background and the request returns before the copy is complete, so committing to it right away\n * could fail.\n * @param {RepositoryPath} fork Fork to wait for.\n * @param {number} [attemptsLeft] Number of attempts remaining, used for the recursive retry.\n * @throws {Error} When the fork hasn’t become available within the allotted time, or the import\n * failed outright.\n * @see https://docs.gitlab.com/api/project_import_export/#import-status\n */\nexport const waitForFork = async (fork, attemptsLeft) => {\n  await pollForFork({\n    repoPath: `${fork.owner}/${fork.repo}`,\n    attemptsLeft,\n    /**\n     * Ask GitLab how far the copy has got.\n     * @returns {Promise<'ready' | 'pending' | 'failed'>} Import status, normalized.\n     */\n    checkFork: async () => {\n      /** @type {string | undefined} */\n      let importStatus;\n\n      try {\n        ({ import_status: importStatus } = /** @type {Record<string, any>} */ (\n          await fetchAPI(`/projects/${getProjectId(fork)}`)\n        ));\n      } catch {\n        // The fork isn’t readable yet, which is what the polling is for\n        return 'pending';\n      }\n\n      if (importStatus === undefined || FORK_READY_STATUSES.includes(importStatus)) {\n        return 'ready';\n      }\n\n      return importStatus === 'failed' ? 'failed' : 'pending';\n    },\n  });\n};\n\n/**\n * Check whether the signed-in user already has a project at the path a fork gets by default, which\n * is what stops a fork from being created there.\n * @returns {Promise<boolean>} `true` if the path is taken.\n * @see https://docs.gitlab.com/api/projects/#get-a-single-project\n */\nconst isForkPathTaken = async () => {\n  const userName = /** @type {string} */ (user.account?.login);\n\n  try {\n    await fetchAPI(`/projects/${getProjectId({ owner: userName, repo: repository.repo })}`);\n\n    return true;\n  } catch {\n    return false;\n  }\n};\n\n/**\n * Fork the configured project onto the signed-in user’s namespace. GitLab doesn’t pick another\n * name when the contributor already has an unrelated project at the default path, the way GitHub\n * does, so the fork is given one made of the configured project’s namespace and name. Later\n * sessions find it by {@link fetchForkFromNetwork}, as {@link fetchForkByName} only looks at the\n * default path.\n * @returns {Promise<RepositoryPath>} The new fork.\n * @throws {Error} When the fork could not be created.\n * @see https://docs.gitlab.com/api/project_forks/#fork-a-project\n */\nexport const createFork = async () => {\n  const { owner, repo } = repository;\n  const endpoint = `/projects/${getProjectId()}/fork`;\n  /** @type {Record<string, any>} */\n  let result;\n\n  /**\n   * Log the given failure and create an error that tells the user the fork couldn’t be made.\n   * @param {Error} ex Failure.\n   * @returns {Error} Error to throw.\n   */\n  const createForkError = (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: `${owner}/${repo}`,\n    });\n  };\n\n  try {\n    result = /** @type {Record<string, any>} */ (await fetchAPI(endpoint, { method: 'POST' }));\n  } catch (/** @type {any} */ ex) {\n    // GitLab refuses a name or path that has already been taken in the namespace with 409 Conflict,\n    // or with 400 Bad Request on some versions. The lookup tells that from any other failure, such\n    // as forking being turned off\n    if (![400, 409].includes(ex.cause?.status) || !(await isForkPathTaken())) {\n      throw createForkError(ex);\n    }\n\n    // A path can’t hold a slash, which a project in a subgroup has in its namespace\n    const name = `${owner.replaceAll('/', '-')}-${repo}`;\n\n    try {\n      result = /** @type {Record<string, any>} */ (\n        await fetchAPI(endpoint, { method: 'POST', body: { name, path: name } })\n      );\n    } catch (/** @type {any} */ retryEx) {\n      throw createForkError(retryEx);\n    }\n  }\n\n  const fork = parseProjectPath(result.path_with_namespace);\n\n  projectIds.fork = result.id;\n\n  await waitForFork(fork);\n\n  return fork;\n};\n\n/**\n * Work out how the signed-in user is going to write to the project, and set up a fork for them if\n * they can’t write to the configured one. This replaces the plain access check performed when Open\n * Authoring is turned off, because a contributor without write access is expected here rather than\n * turned away.\n *\n * Unlike GitHub, GitLab has no API to bring a fork up to date with its parent, so nothing is done\n * about one that has drifted. It doesn’t affect what a contributor submits: a workflow branch is\n * created from the configured project’s branch rather than from the fork’s copy of it, so the merge\n * request only contains the entry being edited either way.\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  const { canWrite } = await fetchRepositoryAccess();\n\n  // A maintainer keeps working on the configured project, as if Open Authoring was off\n  if (canWrite) {\n    return;\n  }\n\n  const { owner, repo } = repository;\n  const [{ allowForking }, existingFork] = await Promise.all([fetchProjectDetails(), fetchFork()]);\n\n  if (existingFork) {\n    forkedRepository.current = existingFork;\n\n    return;\n  }\n\n  await ensureForkPermission({ repoPath: `${owner}/${repo}`, allowForking });\n\n  forkedRepository.current = await createFork();\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  // The IDs belong to the user being signed out, so don’t let a stale fork ID vouch for the next\n  // user’s merge requests\n  projectIds.base = undefined;\n  projectIds.fork = undefined;\n\n  await runOpenAuthoringSetUp(setUpOpenAuthoring);\n};\n","import { encodeBase64 } from '@sveltia/utils/file';\n\nimport { projectIds } from '$lib/services/backends/git/gitlab/fork';\nimport { getProjectId, repository } from '$lib/services/backends/git/gitlab/repository';\nimport { fetchAPI, fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport {\n  assertBranchNotMoved,\n  createCommitMessage,\n  fetchPerPathCommits,\n} 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 { checkDirectCommitAllowed } from '$lib/services/backends/git/shared/fork';\nimport { repositoryHead } from '$lib/services/backends/git/shared/head';\nimport { getOrCreateAsync } from '$lib/services/utils/cache';\nimport { getGitHash } from '$lib/services/utils/file';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { CommitOptions, CommitResults, FileChange, FileCommit } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} FetchLastCommitResponse\n * @property {object} project Project information.\n * @property {object} project.repository Repository information.\n * @property {object} project.repository.tree Tree information.\n * @property {object} project.repository.tree.lastCommit Last commit information.\n * @property {string} project.repository.tree.lastCommit.sha Commit SHA-1 hash.\n * @property {string} project.repository.tree.lastCommit.message Commit message.\n */\n\n/**\n * @typedef {object} CommitResponse\n * @property {string} id Commit SHA-1 hash.\n * @property {string} committed_date Commit date in ISO 8601 format.\n */\n\nconst FETCH_LAST_COMMIT_QUERY = `\n  query($fullPath: ID!, $branch: String!) {\n    project(fullPath: $fullPath) {\n      repository {\n        tree(ref: $branch) {\n          lastCommit {\n            sha\n            message\n          }\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Fetch the last commit on the repository.\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 * @see https://docs.gitlab.com/api/graphql/reference/#tree\n */\nexport const fetchLastCommit = async () => {\n  const { repo, branch } = repository;\n\n  const result = /** @type {FetchLastCommitResponse} */ (\n    await fetchGraphQL(FETCH_LAST_COMMIT_QUERY)\n  );\n\n  if (!result.project) {\n    throw createLocalizedError('Failed to retrieve the last commit hash.', 'repository_not_found', {\n      repo,\n    });\n  }\n\n  const { lastCommit } = result.project.repository.tree ?? {};\n\n  if (!lastCommit) {\n    throw createLocalizedError('Failed to retrieve the last commit hash.', 'branch_not_found', {\n      repo,\n      branch,\n    });\n  }\n\n  const { sha: hash, message } = lastCommit;\n\n  return { hash, message };\n};\n\n/**\n * Save entries or assets remotely. Note that the `commitCreate` GraphQL mutation is broken and\n * images cannot be uploaded properly, so we use the REST API instead.\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 * @see https://docs.gitlab.com/api/commits.html#create-a-commit-with-multiple-files-and-actions\n * @see https://gitlab.com/gitlab-org/gitlab/-/merge_requests/31102\n * @see https://docs.gitlab.com/api/graphql/reference/#mutationcommitcreate\n * @see https://forum.gitlab.com/t/how-to-commit-a-image-via-gitlab-commit-api/26632/4\n */\nexport const commitChanges = async (changes, options) => {\n  checkDirectCommitAllowed(options);\n\n  // A workflow branch lives in the contributor’s fork with Open Authoring, while the configured\n  // branch is only ever committed to by someone who can write to the configured project\n  const fork = options.branch ? forkedRepository.current : undefined;\n  const branch = options.branch ?? repository.branch;\n  // The commit the branch is expected to point at: on the configured branch, the one the loaded\n  // site data reflects, which the caller has just brought up to date; on a workflow branch, the\n  // merge request’s head, which the caller has just compared the branch with. GitLab has no\n  // branch-level guard like GitHub’s `expectedHeadOid`: a `start_sha` is refused on an existing\n  // branch unless `force` is set, which would discard someone else’s push instead. But an action\n  // can take a `last_commit_id`, and GitLab 15.10+ refuses an update, move or deletion when the\n  // file’s last commit on the branch differs from its last commit as of that ID, i.e. when someone\n  // else has changed the file since. So the head goes with every such action, which takes no lookup\n  // per file. A workflow branch is named after the entry, not the editor, so others can push to it\n  // too\n  const expectedHead = (options.branch ? options.headOid : repositoryHead.current) || undefined;\n\n  const actions = await Promise.all(\n    changes.map(async ({ action, path, previousPath, data = '' }) => ({\n      action,\n      content: typeof data === 'string' ? data : await encodeBase64(data),\n      encoding: typeof data === 'string' ? 'text' : 'base64',\n      file_path: path,\n      previous_path: previousPath,\n      ...(expectedHead && action !== 'create' ? { last_commit_id: expectedHead } : {}),\n    })),\n  );\n\n  const endpoint = `/projects/${getProjectId(fork)}/repository/commits`;\n  const body = { branch, commit_message: createCommitMessage(changes, options), actions };\n  const { startBranch } = options;\n  // With Open Authoring the branch is created in the contributor’s fork, but starts from the head\n  // of the configured project 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 merge request. GitLab offers no\n  // way to sync a fork, which makes this the only way to keep the merge request to the entry\n  // edited. The project goes by its numeric ID: a path in the request body is taken as is, so the\n  // encoded one {@link getProjectId} gives for a request path would name no project at all\n  const startProject = fork ? { start_project: projectIds.base } : {};\n  /** @type {CommitResponse} */\n  let response;\n\n  try {\n    // GitLab rejects `start_branch` outright once the branch exists. That’s left to the caller to\n    // sort out, because only the Editorial Workflow service can tell whether the branch is a\n    // leftover to start over from or someone’s work in progress to commit onto\n    response = /** @type {CommitResponse} */ (\n      await fetchAPI(endpoint, {\n        method: 'POST',\n        body: startBranch ? { ...body, start_branch: startBranch, ...startProject } : body,\n      })\n    );\n  } catch (/** @type {any} */ ex) {\n    // GitLab refuses a changed file with a 400 Bad Request, like any other invalid request. A\n    // workflow branch’s head is looked up by the Editorial Workflow service, which knows the branch\n    if (expectedHead && !options.branch && ex.cause?.status === 400) {\n      await assertBranchNotMoved(expectedHead, fetchLastCommit);\n    }\n\n    throw ex;\n  }\n\n  const { id: sha, committed_date: committedDate } = response;\n\n  // Calculate the SHA-1 hash for each file because the GitLab REST API does not return file SHAs\n  const entries = await Promise.all(\n    changes.map(async ({ path, data }) =>\n      data === undefined ? null : [path, { sha: await getGitHash(data) }],\n    ),\n  );\n\n  return {\n    sha,\n    date: new Date(committedDate),\n    files: Object.fromEntries(entries.filter((entry) => !!entry)),\n  };\n};\n\n/**\n * Avatar URLs looked up so far, keyed by email address. The commit history is fetched every time\n * the history of an entry is shown, and mostly lists the same few authors, so each of them is only\n * looked up once.\n * @type {Map<string, Promise<string | undefined>>}\n */\nconst avatarURLCache = new Map();\n\n/**\n * Reset {@link avatarURLCache}. Used in tests.\n */\nexport const _resetAvatarURLCache = () => {\n  avatarURLCache.clear();\n};\n\n/**\n * Fetch the avatar URL for a given email address.\n * @param {string} email Email address.\n * @returns {Promise<string | undefined>} Avatar URL, or `undefined` if not available.\n * @see https://docs.gitlab.com/api/avatar/\n */\nconst fetchAvatarURL = async (email) => {\n  try {\n    // A failure isn’t remembered, so the avatar can show up next time\n    return await getOrCreateAsync(avatarURLCache, email, async () => {\n      const { avatar_url: avatarURL } = /** @type {{ avatar_url: string }} */ (\n        await fetchAPI(`/avatar?email=${encodeURIComponent(email)}&size=48`)\n      );\n\n      return avatarURL || undefined;\n    });\n  } catch {\n    return undefined;\n  }\n};\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.gitlab.com/api/commits/#list-repository-commits\n */\nexport const fetchFileCommits = async (paths) => {\n  const { branch } = repository;\n  const projectId = getProjectId();\n\n  /** @type {FileCommit[]} */\n  const commitList = await fetchPerPathCommits(\n    paths,\n    (path) =>\n      /** @type {Promise<any[]>} */ (\n        fetchAPI(\n          `/projects/${projectId}/repository/commits` +\n            `?ref_name=${encodeURIComponent(branch ?? '')}` +\n            `&path=${encodeURIComponent(path)}&per_page=100`,\n        )\n      ),\n    (commit) => ({\n      sha: commit.id,\n      authorName: commit.author_name,\n      authorEmail: commit.author_email,\n      authorAvatarURL: undefined,\n      date: new Date(commit.committed_date),\n    }),\n  );\n\n  // Resolve avatar URLs for unique author emails via the GitLab Avatar API\n  /** @type {string[]} */\n  const uniqueEmails = /** @type {string[]} */ (\n    [...new Set(commitList.map((c) => c.authorEmail))].filter((e) => !!e)\n  );\n\n  /** @type {Map<string, string | undefined>} */\n  const avatarMap = new Map();\n\n  await runConcurrently(uniqueEmails, async (email) => {\n    avatarMap.set(email, await fetchAvatarURL(email));\n  });\n\n  commitList.forEach((commit) => {\n    commit.authorAvatarURL = avatarMap.get(/** @type {string} */ (commit.authorEmail));\n  });\n\n  return commitList;\n};\n","import {\n  getBranchPath,\n  getProjectId,\n  repository,\n} from '$lib/services/backends/git/gitlab/repository';\nimport { fetchAPI } from '$lib/services/backends/git/shared/api';\nimport { runConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { resolveDeployments } from '$lib/services/backends/git/shared/deployment';\n\n/**\n * @import { DeployState, DeployStatus, DeployTarget } from '$lib/types/private';\n * @import { DeployCandidate } from '$lib/services/backends/git/shared/deployment';\n */\n\n/** Maximum number of items to retrieve per request. This is GitLab’s own cap. */\nconst MAX_ITEMS = 100;\n/**\n * How far back to look for deployments. GitLab’s Deployments API can’t filter by commit or ref, so\n * a recent window is fetched and matched locally. A project that produces more than {@link\n * MAX_ITEMS} deployments within the window may push a Review App out of the first page, in which\n * case the commit statuses still cover it.\n */\nconst DEPLOYMENT_WINDOW = 7 * 24 * 60 * 60 * 1000;\n\n/**\n * Map a commit status to a normalized state. `skipped` is absent, so a job that didn’t run is\n * ignored rather than reported as a failure.\n * @type {Record<string, DeployState>}\n * @see https://docs.gitlab.com/api/commits/#list-the-statuses-of-a-commit\n */\nconst COMMIT_STATUS_MAP = {\n  success: 'ready',\n  pending: 'pending',\n  running: 'pending',\n  created: 'pending',\n  preparing: 'pending',\n  manual: 'pending',\n  scheduled: 'pending',\n  waiting_for_resource: 'pending',\n  failed: 'error',\n  canceled: 'error',\n};\n\n/**\n * Map a deployment status to a normalized state.\n * @type {Record<string, DeployState>}\n * @see https://docs.gitlab.com/api/deployments/\n */\nconst DEPLOYMENT_STATUS_MAP = {\n  success: 'ready',\n  created: 'pending',\n  running: 'pending',\n  blocked: 'pending',\n  failed: 'error',\n  canceled: 'error',\n};\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.gitlab.com/api/branches/#get-single-repository-branch\n */\nexport const fetchBranchHeadSHA = async () => {\n  const { branch } = repository;\n\n  if (!branch) {\n    // The default branch hasn’t been detected yet\n    return undefined;\n  }\n\n  const result = /** @type {Record<string, any>} */ (await fetchAPI(getBranchPath(branch)));\n\n  return result?.commit?.id ?? undefined;\n};\n\n/**\n * Collect deploy candidates from the project’s recent deployments, which is how GitLab’s own Review\n * Apps and environments report a site URL. One request covers every target, because the API can\n * only be narrowed by time, not by commit or ref. Each deployment is matched to a target by commit\n * rather than by branch: a branch with any history has a finished deployment on it, and matching by\n * branch would let that one — `ready`, with a URL — outrank the new commit’s own deployment, still\n * `pending`, so a fresh save would read as built the moment it was pushed and never be checked\n * again.\n * @param {Record<string, DeployCandidate[]>} candidateMap Map to populate, keyed by the commit SHAs\n * to look up.\n */\nconst collectDeploymentCandidates = async (candidateMap) => {\n  const updatedAfter = new Date(Date.now() - DEPLOYMENT_WINDOW).toISOString();\n\n  const deployments = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(\n      `/projects/${getProjectId()}/deployments` +\n        `?order_by=updated_at&sort=desc&per_page=${MAX_ITEMS}` +\n        `&updated_after=${encodeURIComponent(updatedAfter)}`,\n    )\n  );\n\n  // The response is newest first, while {@link pickDeployment} expects the newest last\n  [...(deployments ?? [])].reverse().forEach(({ sha, status, environment }) => {\n    const state = DEPLOYMENT_STATUS_MAP[status];\n    // An older self-hosted GitLab omits `external_url` from the list response\n    const url = environment?.external_url ?? undefined;\n\n    if (!state || !sha) {\n      return;\n    }\n\n    // Anything else within the window is some other commit’s deployment\n    candidateMap[sha]?.push({\n      name: environment?.name ?? '',\n      url,\n      state,\n      source: 'deployment',\n    });\n  });\n};\n\n/**\n * Collect deploy candidates from the commit statuses of the given commit. This is where an external\n * CI service posts a build result when it posts one at all.\n * @param {DeployTarget} target Commit to look up.\n * @param {Record<string, DeployCandidate[]>} candidateMap Map to populate, keyed by commit SHA.\n * @see https://docs.gitlab.com/api/commits/#list-the-statuses-of-a-commit\n */\nconst collectStatusCandidates = async ({ sha }, candidateMap) => {\n  const statuses = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(\n      `/projects/${getProjectId()}/repository/commits/${encodeURIComponent(sha)}` +\n        `/statuses?per_page=${MAX_ITEMS}`,\n    )\n  );\n\n  (statuses ?? []).forEach(({ name, status, target_url: targetURL, description }) => {\n    const state = COMMIT_STATUS_MAP[status];\n\n    if (state) {\n      candidateMap[sha].push({\n        name: name ?? '',\n        url: targetURL ?? undefined,\n        state,\n        description: description ?? undefined,\n        source: 'status',\n      });\n    }\n  });\n};\n\n/**\n * Run a collector, reporting a failure without failing the batch.\n * @param {() => Promise<void>} task Task to run.\n */\nconst 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 * Collect deploy candidates for the given commits from the project’s deployments and from each\n * commit’s statuses.\n * @param {string[]} shas Commit SHAs.\n * @param {Record<string, DeployCandidate[]>} candidateMap Candidates keyed by commit SHA.\n */\nconst collectCandidates = async (shas, candidateMap) => {\n  await Promise.all([\n    collectSafely(() => collectDeploymentCandidates(candidateMap)),\n    runConcurrently(shas, async (sha) =>\n      collectSafely(() =>\n        collectStatusCandidates({ sha, branch: '', kind: 'preview' }, candidateMap),\n      ),\n    ),\n  ]);\n};\n\n/**\n * Fetch the deployment status and URL for the given commits. Each source is requested separately\n * and any failure is swallowed, so a commit whose statuses are gone — after a force push, say —\n * doesn’t take the rest of the batch down with it.\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","/* eslint-disable no-await-in-loop */\n\nimport { getPathInfo } from '@sveltia/utils/file';\n\nimport { fetchLastCommit } from '$lib/services/backends/git/gitlab/commits';\nimport {\n  getWorkflowRepository,\n  initOpenAuthoring,\n  isOpenAuthoringConfigured,\n} from '$lib/services/backends/git/gitlab/fork';\nimport {\n  checkBranchAccess,\n  checkRepositoryAccess,\n  fetchDefaultBranchName,\n  getProjectId,\n  repository,\n} from '$lib/services/backends/git/gitlab/repository';\nimport { fetchAPI, fetchGraphQL } from '$lib/services/backends/git/shared/api';\nimport { mapConcurrently } from '$lib/services/backends/git/shared/concurrency';\nimport { fetchRepositoryFiles } from '$lib/services/backends/git/shared/files';\nimport { startSimulatedProgress } from '$lib/services/backends/git/shared/progress';\nimport { toFileListItems } from '$lib/services/backends/git/shared/tree';\nimport { getRootDir } from '$lib/services/backends/root-dir';\nimport { splitIntoChunks } from '$lib/services/utils/array';\n\n/**\n * @import {\n * Asset,\n * BaseFileListItem,\n * BaseFileListItemProps,\n * RepositoryContentsMap,\n * } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} FileListTree\n * @property {object} blobs Blobs information.\n * @property {{ type: string, path: string, sha: string }[]} blobs.nodes List of file blobs.\n * @property {object} blobs.pageInfo Pagination information.\n * @property {string} blobs.pageInfo.endCursor Cursor for the next page.\n * @property {boolean} blobs.pageInfo.hasNextPage Whether there are more pages to fetch.\n */\n\n/**\n * @typedef {object} FetchFileListResponse\n * @property {object} project Project information.\n * @property {object} project.repository Repository information.\n * @property {FileListTree | null} project.repository.tree Tree information, or `null` if there is\n * none.\n */\n\n/**\n * A blob node as returned by the GraphQL API. Which of these fields is populated depends on the\n * query, as the callers of {@link fetchBlobNodes} select different ones.\n * @typedef {object} BlobItem\n * @property {string} [path] Path of the file.\n * @property {string} [oid] Blob’s object ID, which is a SHA-1 hash.\n * @property {string} [size] Size of the blob in bytes.\n * @property {string} [rawTextBlob] Raw text content of the blob.\n */\n\n/**\n * @typedef {object} FetchBlobsResponse\n * @property {object} project Project information.\n * @property {object} project.repository Repository information.\n * @property {object} project.repository.blobs Blobs information.\n * @property {BlobItem[]} project.repository.blobs.nodes List of file blobs with their sizes and raw\n * text contents.\n */\n\n/**\n * Get the query to fetch a page of the file list.\n * @param {object} args Arguments.\n * @param {boolean} args.scoped Whether to list the files in a directory, given as the `$path`\n * variable, rather than the whole repository.\n * @returns {string} Query.\n */\nconst getFetchFileListQuery = ({ scoped }) => `\n  query($fullPath: ID!, $branch: String!, $cursor: String!${scoped ? ', $path: String!' : ''}) {\n    project(fullPath: $fullPath) {\n      repository {\n        tree(ref: $branch, ${scoped ? 'path: $path, ' : ''}recursive: true) {\n          blobs(after: $cursor) {\n            nodes {\n              type\n              path\n              sha\n            }\n            pageInfo {\n              endCursor\n              hasNextPage\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Fetch the repository’s complete file list, and return it in the canonical format. With the\n * `root_dir` backend option, only the files in that directory are listed, which saves listing the\n * whole of a big monorepo; the paths are still relative to the repository root.\n * @returns {Promise<BaseFileListItemProps[]>} File list.\n * @see https://docs.gitlab.com/api/graphql/reference/index.html#repositorytree\n * @see https://stackoverflow.com/questions/18952935/how-to-get-subfolders-and-files-using-gitlab-api\n */\nexport const fetchFileList = async () => {\n  const rootDir = getRootDir();\n  const query = getFetchFileListQuery({ scoped: !!rootDir });\n  /** @type {{ type: string, path: string, sha: string }[]} */\n  const blobs = [];\n  let cursor = '';\n\n  // Since GitLab has a limit of 100 records per query, use pagination to fetch all the files\n  for (;;) {\n    const result = /** @type {FetchFileListResponse} */ (\n      await fetchGraphQL(query, { cursor, ...(rootDir && { path: rootDir }) })\n    );\n\n    // A directory that doesn’t exist comes back without blobs, while a missing tree is guarded\n    // against as well; either leaves the list empty, which the caller reports\n    const {\n      nodes,\n      pageInfo: { endCursor, hasNextPage },\n    } = result.project.repository.tree?.blobs ?? {\n      nodes: [],\n      pageInfo: { endCursor: '', hasNextPage: false },\n    };\n\n    blobs.push(...nodes);\n    cursor = endCursor;\n\n    if (!hasNextPage) {\n      break;\n    }\n  }\n\n  // The `size` is not available from the GitLab API in bulk, so it’s left as `0`\n  return toFileListItems(blobs);\n};\n\nconst FETCH_SUBTREES_QUERY = `\n  query($fullPath: ID!, $ref: String!, $path: String!, $cursor: String!) {\n    project(fullPath: $fullPath) {\n      repository {\n        tree(ref: $ref, path: $path) {\n          trees(after: $cursor) {\n            nodes {\n              name\n              sha\n            }\n            pageInfo {\n              endCursor\n              hasNextPage\n            }\n          }\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Find the tree SHA of a directory at the given commit, by listing the subdirectories of the\n * directory that holds it, a page at a time.\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.gitlab.com/api/graphql/reference/#tree\n */\nexport const fetchDirSHA = async (ref, dirPath) => {\n  const { dirname = '', basename } = getPathInfo(dirPath);\n  let cursor = '';\n\n  for (;;) {\n    const result = /** @type {any} */ (\n      await fetchGraphQL(FETCH_SUBTREES_QUERY, { ref, path: dirname, cursor })\n    );\n\n    const { nodes = [], pageInfo } = result.project?.repository?.tree?.trees ?? {};\n\n    const sha = /** @type {{ name: string, sha: string }[]} */ (nodes).find(\n      ({ name }) => name === basename,\n    )?.sha;\n\n    if (sha || !pageInfo?.hasNextPage) {\n      return sha;\n    }\n\n    cursor = pageInfo.endCursor;\n  }\n};\n\n/**\n * Number of blob batches requested at the same time on GitLab.com. Each batch is a heavy query, so\n * this is kept well below the general limit on requests in flight.\n */\nexport const BLOB_CONCURRENCY = 4;\n\n/**\n * Number of blob batches requested at the same time on a self-hosted instance, which typically runs\n * on less powerful hardware and is more likely to time out under load.\n */\nexport const SELF_HOSTED_BLOB_CONCURRENCY = 2;\n\nconst FETCH_BLOBS_QUERY = `\n  query($fullPath: ID!, $branch: String!, $paths: [String!]!) {\n    project(fullPath: $fullPath) {\n      repository {\n        blobs(ref: $branch, paths: $paths) {\n          nodes {\n            path\n            rawTextBlob\n          }\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Fetch a single batch of blobs, halving the batch and trying again whenever the request fails.\n * GitLab refuses a request whose blobs add up to more than 20 MB, and the sizes aren’t known in\n * advance, so an oversized batch can only be discovered by attempting it. A single blob of any size\n * is always accepted, which guarantees the split terminates; an error that survives all the way\n * down to one path isn’t about the size, so it’s thrown as is. Because a failing half is awaited\n * before the other one is requested, such an error surfaces after a handful of extra requests\n * rather than a retry of every path.\n * @param {string[]} paths List of file paths to fetch.\n * @param {string} query GraphQL query string.\n * @param {Record<string, any>} [variables] Any variable to be applied to the query, other than the\n * paths.\n * @returns {Promise<BlobItem[]>} Fetched blobs, in the same order as the given paths. A path that\n * isn’t on the branch is left out, so select the `path` to match a blob to its file.\n * @throws {Error} When a request for a single path fails.\n * @see https://docs.gitlab.com/api/graphql/#data-limits\n * @see https://gitlab.com/gitlab-org/gitlab/-/merge_requests/212456\n */\nexport const fetchBlobBatch = async (paths, query, variables = {}) => {\n  /** @type {FetchBlobsResponse} */\n  let result;\n\n  try {\n    result = /** @type {FetchBlobsResponse} */ (await fetchGraphQL(query, { ...variables, paths }));\n  } catch (ex) {\n    // A request for a single blob is always within the size limit, so this error is about something\n    // else, and there’s nothing left to split anyway\n    if (paths.length === 1) {\n      throw ex;\n    }\n\n    const midPoint = Math.ceil(paths.length / 2);\n    const firstHalf = await fetchBlobBatch(paths.slice(0, midPoint), query, variables);\n    const secondHalf = await fetchBlobBatch(paths.slice(midPoint), query, variables);\n\n    return [...firstHalf, ...secondHalf];\n  }\n\n  // Read the response outside the `try` block, so a malformed one is reported as is instead of\n  // being mistaken for an oversized batch and retried\n  return result.project.repository.blobs.nodes;\n};\n\n/**\n * Fetch the blobs for the given file paths. This function retrieves the raw text contents of files\n * in the repository using the GitLab GraphQL API. It handles pagination by fetching a fixed number\n * of paths at a time, ensuring that the complexity score of the query does not exceed the limit.\n * @param {string[]} paths List of file paths to fetch.\n * @param {string} query GraphQL query string.\n * @param {Record<string, any>} [variables] Any variable to be applied to the query, other than the\n * paths.\n * @returns {Promise<BlobItem[]>} Fetched blobs, in the same order as the given paths. A path that\n * isn’t on the branch is left out, so select the `path` to match a blob to its file.\n * @see https://docs.gitlab.com/api/graphql/reference/#repositoryblob\n * @see https://docs.gitlab.com/api/graphql/reference/#tree\n * @see https://forum.gitlab.com/t/graphql-api-read-raw-file/35389\n * @see https://docs.gitlab.com/api/graphql/#limits\n */\nexport const fetchBlobNodes = async (paths, query, variables = {}) => {\n  if (!paths.length) {\n    return [];\n  }\n\n  const { isSelfHosted = false } = repository;\n  const batchSize = isSelfHosted ? 20 : 100;\n  const concurrency = isSelfHosted ? SELF_HOSTED_BLOB_CONCURRENCY : BLOB_CONCURRENCY;\n\n  // Fetch all the text contents with the GraphQL API. Pagination would fail if `paths` becomes too\n  // long, so we just use a fixed number of paths per request. The complexity score of this query is\n  // 15 + (2 * node size) so 100 paths = 215 complexity, giving the following conditions:\n  // 1. The max number of records is 100\n  // 2. The max query complexity is 250 or 300\n  // 3. The total blob size must be under 20 MB (since GitLab 18.4.5)\n  // @see https://github.com/sveltia/sveltia-cms/issues/525\n  // @see https://gitlab.com/gitlab-org/gitlab/-/issues/576497\n  // The batch size is reduced to 20 for self-hosted instances because they typically run on less\n  // powerful hardware, which may lead to timeout issues.\n  // Only the first two conditions can be satisfied by a fixed count; the size of a blob is unknown\n  // until it’s fetched, so {@link fetchBlobBatch} handles the third one by splitting a batch that\n  // turns out to be too large.\n  //\n  // The batches are independent, so a few of them are requested at once rather than one after\n  // another; a large repository needs dozens of them, and each is a full round trip\n  const results = await mapConcurrently(\n    splitIntoChunks(paths, batchSize),\n    (batchPaths) => fetchBlobBatch(batchPaths, query, variables),\n    { concurrency },\n  );\n\n  // Keep the order of the given paths, although callers match a blob to its file by path\n  return results.flat();\n};\n\n/**\n * Fetch the blobs for the given file paths, and map them back to those paths.\n * @param {string[]} paths List of file paths to fetch.\n * @param {string} query GraphQL query string, which has to select the `path` of each blob.\n * @returns {Promise<Record<string, BlobItem>>} Fetched blobs mapped by file path. A path missing\n * from the branch has no blob.\n */\nexport const fetchBlobs = async (paths, query) => {\n  const blobs = await fetchBlobNodes(paths, query);\n\n  // Map the blobs back by their own paths rather than by position: GitLab leaves a path that isn’t\n  // on the branch out of the response, e.g. a file deleted by a push made during the load, which\n  // would otherwise give every later file the content of the one after it\n  return Object.fromEntries(blobs.map((blob) => [/** @type {string} */ (blob.path), blob]));\n};\n\n/**\n * Parse the file contents from the API response. The GitLab API doesn’t give us file sizes or\n * commit information in bulk, so only the text contents are filled in.\n * @param {object} args Arguments.\n * @param {BaseFileListItem[]} args.fetchingFiles Base file list.\n * @param {Record<string, BlobItem>} args.blobs Raw text blobs.\n * @returns {RepositoryContentsMap} Parsed file contents map.\n */\nexport const parseFileContents = ({ fetchingFiles, blobs }) =>\n  Object.fromEntries(\n    fetchingFiles.map(({ path, sha }) => [\n      path,\n      { sha, size: 0, text: blobs[path]?.rawTextBlob ?? undefined, meta: {} },\n    ]),\n  );\n\n/**\n * Fetch the metadata of entry/asset files as well as text file contents.\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  // Fetch blobs for entry/config files only\n  const textPaths = fetchingFiles.filter(({ type }) => type !== 'asset').map(({ path }) => path);\n  /** @type {Awaited<ReturnType<typeof fetchBlobs>>} */\n  let blobs;\n\n  try {\n    blobs = await fetchBlobs(textPaths, FETCH_BLOBS_QUERY);\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, blobs });\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    checkAccess: checkRepositoryAccess,\n    checkBranchAccess,\n    fetchDefaultBranchName,\n    fetchLastCommit,\n    lastCommit,\n    fetchFileList,\n    fetchFileContents,\n  });\n};\n\n/**\n * Fetch an asset as a Blob via the API. We use the `lfs` query parameter to ensure that GitLab\n * returns the file content even if it’s tracked by Git LFS.\n * @param {Asset} asset Asset to retrieve the file content.\n * @returns {Promise<Blob>} Blob data.\n * @see https://docs.gitlab.com/api/repository_files/#get-raw-file-from-repository\n */\nexport const fetchBlob = async (asset) => {\n  const { branch = '' } = repository;\n  const { path, workflow } = asset;\n  // An asset attached to an unpublished entry is committed to a workflow branch only, so it has to\n  // be read from there; on the configured branch the path is missing or holds the published\n  // version. That branch lives in the contributor’s fork with Open Authoring, so it’s read there\n  const ref = workflow?.branch ?? branch;\n  const projectId = getProjectId(workflow ? getWorkflowRepository() : undefined);\n\n  return /** @type {Promise<Blob>} */ (\n    fetchAPI(\n      `/projects/${projectId}/repository/files` +\n        `/${encodeURIComponent(path)}/raw?lfs=true&ref=${encodeURIComponent(ref)}`,\n      { responseType: 'blob' },\n    )\n  );\n};\n","import { sendRequest } from '$lib/services/utils/networking';\n\n/**\n * @import { BackendServiceStatus } from '$lib/types/private';\n */\n\n/**\n * The URL of the GitLab status dashboard.\n */\nexport const STATUS_DASHBOARD_URL = 'https://status.gitlab.com/';\n\n/**\n * The URL to check the GitLab service status.\n */\nconst STATUS_CHECK_URL = 'https://status-api.hostedstatus.com/1.0/status/5b36dc6502d06804c08349f7';\n\n/**\n * Check the GitLab service status.\n * @returns {Promise<BackendServiceStatus>} Current status.\n * @see https://kb.status.io/developers/public-status-api/\n */\nexport const checkStatus = async () => {\n  try {\n    const {\n      result: {\n        status_overall: { status_code: status },\n      },\n    } = /** @type {{ result: { status_overall: { status_code: number } } }} */ (\n      await sendRequest(STATUS_CHECK_URL)\n    );\n\n    if (status === 100) {\n      return 'none';\n    }\n\n    if ([200, 300, 400].includes(status)) {\n      return 'minor';\n    }\n\n    if ([500, 600].includes(status)) {\n      return 'major';\n    }\n  } catch {\n    //\n  }\n\n  return 'unknown';\n};\n","import { fetchBlobNodes } from '$lib/services/backends/git/gitlab/files';\nimport { getWorkflowRepository, projectIds } from '$lib/services/backends/git/gitlab/fork';\nimport {\n  getBranchPath,\n  getProjectId,\n  repository,\n} from '$lib/services/backends/git/gitlab/repository';\nimport { fetchAPI, fetchGraphQL } 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 { PULL_REQUEST_DESCRIPTION } from '$lib/services/backends/git/shared/pull-requests';\nimport { deleteRemoteBranch } from '$lib/services/backends/git/shared/workflow';\nimport { splitIntoChunks } from '$lib/services/utils/array';\nimport {\n  getAllStatusLabels,\n  getStatusFromLabels,\n  getStatusLabel,\n} from '$lib/services/workflow/labels';\nimport { forkedRepository } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * WorkflowFile,\n * WorkflowPullRequest,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Maximum numbers of items to retrieve from the REST API: open merge requests, changed files per\n * merge request, Open Authoring branches in the contributor’s fork, and the contributor’s own merge\n * requests those branches are matched against. 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  mergeRequests: 100,\n  files: 100,\n  branches: 100,\n  authoredMergeRequests: 100,\n};\n\n/**\n * Regular expression matching the draft indicators GitLab accepts at the beginning of a merge\n * request title. GitLab has no dedicated API field to toggle the draft state; the read-only `draft`\n * property is derived from the title instead.\n * @see https://docs.gitlab.com/user/project/merge_requests/drafts/\n */\nconst DRAFT_TITLE_REGEX =\n  /^\\s*(?:\\[draft\\]|\\(draft\\)|draft:|draft\\s|\\[wip\\]|\\(wip\\)|wip:|wip\\s)\\s*/i;\n\n/**\n * Prefix added to a merge request title to mark it as a draft.\n */\nexport const DRAFT_TITLE_PREFIX = 'Draft: ';\n\n/**\n * Remove any draft indicator from the given merge request title.\n * @param {string} title Raw title.\n * @returns {string} Title without a draft prefix.\n */\nexport const stripDraftPrefix = (title) => {\n  let result = title;\n\n  // Repeat, because GitLab tolerates combinations such as `Draft: WIP: Title`\n  while (DRAFT_TITLE_REGEX.test(result)) {\n    result = result.replace(DRAFT_TITLE_REGEX, '');\n  }\n\n  return result;\n};\n\n/**\n * Get whether the signed-in user can merge the given merge request. A single merge request, like\n * the one returned when it’s created, comes with the answer, while a list doesn’t.\n * @param {Record<string, any>} item Merge request returned by the REST API.\n * @returns {boolean | undefined} Result, or `undefined` if the merge request doesn’t tell.\n * @see https://docs.gitlab.com/api/merge_requests/#get-single-mr\n */\nconst getCanMerge = (item) =>\n  typeof item.user?.can_merge === 'boolean' ? item.user.can_merge : undefined;\n\n/**\n * Convert a merge request returned by the REST API to a workflow pull request.\n * @param {Record<string, any>} item Merge request.\n * @param {WorkflowStatus} status Status of the merge request.\n * @returns {WorkflowPullRequest} Merge request.\n */\nexport const toMergeRequest = (item, status) => {\n  const { name, username, id } = item.author ?? {};\n\n  return {\n    number: item.iid,\n    nodeId: String(item.id),\n    title: stripDraftPrefix(item.title),\n    url: item.web_url,\n    branch: item.source_branch,\n    headSHA: item.sha,\n    status,\n    createdDate: new Date(item.created_at),\n    updatedDate: new Date(item.updated_at),\n    author: username ? { name: name ?? username, email: '', id, login: username } : undefined,\n    files: [],\n    canMerge: getCanMerge(item),\n  };\n};\n\n/**\n * Parse a merge request returned by the REST API.\n * @param {Record<string, any>} item Merge request.\n * @returns {WorkflowPullRequest | undefined} Parsed merge request, or `undefined` if the merge\n * request is not managed by the CMS.\n */\nexport const parseMergeRequest = (item) => {\n  // A merge request from a fork has its source branch in the fork, while the branch is read,\n  // merged and deleted on the configured project, where a branch of the same name would be someone\n  // else’s. Skip it, like GitHub’s cross-repository pull requests\n  if (item.source_project_id !== item.target_project_id) {\n    return undefined;\n  }\n\n  // A merge request to a branch other than the configured one isn’t the CMS’s either, whatever\n  // label it carries: one whose target branch was changed on GitLab 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 (item.target_branch !== repository.branch) {\n    return undefined;\n  }\n\n  const status = getStatusFromLabels(item.labels ?? []);\n\n  if (!status) {\n    return undefined;\n  }\n\n  return toMergeRequest(item, status);\n};\n\n/**\n * Convert a diff entry returned by the merge request or comparison endpoints into a\n * {@link WorkflowFile}. The content is filled in later by {@link fetchMergeRequestFileContents}.\n * @param {Record<string, any>} diff Diff entry.\n * @returns {WorkflowFile} Parsed file.\n */\nexport const parseDiff = (diff) => ({\n  path: diff.deleted_file ? diff.old_path : diff.new_path,\n  sha: '',\n  size: 0,\n  deleted: !!diff.deleted_file,\n  previousPath: diff.renamed_file ? diff.old_path : undefined,\n});\n\n/**\n * Fetch the list of files changed in the given merge request.\n * @param {WorkflowPullRequest} mergeRequest Merge request to complete.\n * @see https://docs.gitlab.com/api/merge_requests/#list-merge-request-diffs\n */\nexport const fetchMergeRequestFileList = async (mergeRequest) => {\n  const diffs = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(\n      `/projects/${getProjectId()}/merge_requests/${mergeRequest.number}` +\n        `/diffs?per_page=${MAX_ITEMS.files}`,\n    )\n  );\n\n  mergeRequest.files = diffs.map(parseDiff);\n};\n\nconst FETCH_BLOBS_QUERY = `\n  query($fullPath: ID!, $branch: String!, $paths: [String!]!) {\n    project(fullPath: $fullPath) {\n      repository {\n        blobs(ref: $branch, paths: $paths) {\n          nodes {\n            path\n            oid\n            size\n            rawTextBlob\n          }\n        }\n      }\n    }\n  }\n`;\n\nconst FETCH_MERGE_PERMISSIONS_QUERY = `\n  query($fullPath: ID!, $iids: [String!]) {\n    project(fullPath: $fullPath) {\n      mergeRequests(iids: $iids, first: 100) {\n        nodes {\n          iid\n          userPermissions {\n            canMerge\n          }\n        }\n      }\n    }\n  }\n`;\n\n/**\n * Find out whether the signed-in user can merge each of the given merge requests, and set their\n * `canMerge` property in place. A protected branch may let a Developer push to the workflow\n * branches, but not merge into the configured branch. The merge request list doesn’t tell, so the\n * permissions are asked for all at once. A failed request leaves them unknown, as GitLab still\n * refuses a merge the user isn’t allowed to make.\n * @param {WorkflowPullRequest[]} mergeRequests Merge requests to complete.\n * @see https://docs.gitlab.com/api/graphql/reference/#mergerequestpermissions\n */\nconst fetchMergePermissions = async (mergeRequests) => {\n  /** @type {Map<string, WorkflowPullRequest>} */\n  const iidMap = new Map(mergeRequests.map((mr) => [String(mr.number), mr]));\n  // The query returns up to 100 merge requests at a time\n  const chunks = splitIntoChunks([...iidMap.keys()], MAX_ITEMS.mergeRequests);\n\n  await runConcurrently(chunks, async (chunk) => {\n    try {\n      const result =\n        /** @type {{ project?: { mergeRequests?: { nodes: Record<string, any>[] } } }} */ (\n          await fetchGraphQL(FETCH_MERGE_PERMISSIONS_QUERY, { iids: chunk })\n        );\n\n      result.project?.mergeRequests?.nodes.forEach(({ iid, userPermissions }) => {\n        const mergeRequest = iidMap.get(String(iid));\n\n        if (mergeRequest && typeof userPermissions?.canMerge === 'boolean') {\n          mergeRequest.canMerge = userPermissions.canMerge;\n        }\n      });\n    } catch {\n      // Keep the permissions unknown, as said above\n    }\n  });\n};\n\n/**\n * Fetch the content of the files changed in the given merge request, and populate the\n * {@link WorkflowFile} objects in place. Binary files, such as images, have no `rawTextBlob`, so\n * only their blob metadata is stored.\n * @param {WorkflowPullRequest} mergeRequest Merge request to complete.\n * @see https://docs.gitlab.com/api/graphql/reference/#repositoryblob\n */\nexport const fetchMergeRequestFileContents = async (mergeRequest) => {\n  const files = mergeRequest.files.filter(({ deleted }) => !deleted);\n\n  if (!files.length) {\n    return;\n  }\n\n  // A workflow branch lives in the contributor’s fork with Open Authoring, so that’s where the\n  // blobs have to be read from\n  const { owner, repo } = getWorkflowRepository();\n\n  // The blobs are fetched in batches, which are split further if the total size of a batch exceeds\n  // the API’s limit. An asset committed to a workflow branch is easily large enough to hit it on\n  // its own. @see https://docs.gitlab.com/api/graphql/#data-limits\n  const nodes = await fetchBlobNodes(\n    files.map(({ path }) => path),\n    FETCH_BLOBS_QUERY,\n    // Read at the head commit rather than the branch, so the content shown is that of the commit a\n    // publish is pinned to, even if the branch moves on while the board loads\n    { fullPath: `${owner}/${repo}`, branch: mergeRequest.headSHA ?? mergeRequest.branch },\n  );\n\n  /** @type {Map<string, Record<string, any>>} */\n  const blobMap = new Map(nodes.map((/** @type {any} */ node) => [node.path, node]));\n\n  files.forEach((file) => {\n    const blob = blobMap.get(file.path);\n\n    if (blob) {\n      Object.assign(file, {\n        sha: blob.oid,\n        size: Number(blob.size) || 0,\n        text: blob.rawTextBlob ?? undefined,\n      });\n    } else {\n      // The file may have been removed from the branch in the meantime\n      file.deleted = true;\n    }\n  });\n};\n\n/**\n * Fetch all the open merge requests managed by the CMS, along with the changed files.\n * @returns {Promise<WorkflowPullRequest[]>} Merge requests.\n * @see https://docs.gitlab.com/api/merge_requests/#list-project-merge-requests\n */\nexport const fetchPullRequests = async () => {\n  /** @type {Map<number, WorkflowPullRequest>} */\n  const found = new Map();\n\n  // The status labels are matched by the API rather than by {@link parseMergeRequest}, so the item\n  // cap applies to the CMS’s own merge requests instead of the project’s most recently updated\n  // ones, which could otherwise push the unpublished entries out of the result. Unlike GitHub’s,\n  // GitLab’s label filter matches a merge request carrying all of the given labels, so each label\n  // needs its own request and the results are merged here\n  await runConcurrently(getAllStatusLabels(), async (label) => {\n    const items = /** @type {Record<string, any>[]} */ (\n      await fetchAPI(\n        `/projects/${getProjectId()}/merge_requests` +\n          `?state=opened&order_by=updated_at&per_page=${MAX_ITEMS.mergeRequests}` +\n          `&labels=${encodeURIComponent(label)}`,\n      )\n    );\n\n    items.forEach((item) => {\n      const mergeRequest = parseMergeRequest(item);\n\n      // A merge request can carry status labels with more than one prefix, so it can show up in\n      // several of these requests\n      if (mergeRequest) {\n        found.set(item.iid, mergeRequest);\n      }\n    });\n  });\n\n  const mergeRequests = [...found.values()].sort(\n    (a, b) => b.updatedDate.getTime() - a.updatedDate.getTime(),\n  );\n\n  await Promise.all([\n    fetchMergePermissions(mergeRequests),\n    runConcurrently(mergeRequests, async (mergeRequest) => {\n      await fetchMergeRequestFileList(mergeRequest);\n      await fetchMergeRequestFileContents(mergeRequest);\n    }),\n  ]);\n\n  return mergeRequests;\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 project it lives in, which is the\n * contributor’s fork with Open Authoring.\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 merge request leaves behind.\n * @see https://docs.gitlab.com/api/branches/#get-single-repository-branch\n */\nexport const fetchBranchHead = async (branch) => {\n  const result = /** @type {{ commit?: { id?: string } } | undefined} */ (\n    await fetchAPIOrUndefined(getBranchPath(branch, getWorkflowRepository()))\n  );\n\n  return result?.commit?.id;\n};\n\n/**\n * Delete the given branch. Failures are ignored, as the branch may already have been deleted when\n * the merge request was merged.\n * @param {string} branch Branch name.\n * @see https://docs.gitlab.com/api/branches/#delete-repository-branch\n */\nexport const deleteBranch = async (branch) => {\n  await deleteRemoteBranch({\n    branch,\n    // A workflow branch lives in the contributor’s fork with Open Authoring\n    path: getBranchPath(branch, getWorkflowRepository()),\n    goneStatuses: [404],\n  });\n};\n\n/**\n * Create a new merge request for the given workflow branch. The merge request is created as a\n * draft, 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 Merge request title.\n * @param {WorkflowStatus} args.status Status to open the merge request with.\n * @returns {Promise<WorkflowPullRequest>} Created merge request.\n * @see https://docs.gitlab.com/api/merge_requests/#create-merge-request\n */\nexport const createPullRequest = async ({ branch, title, status }) => {\n  const isDraft = status === 'draft';\n  const fork = forkedRepository.current;\n\n  // A merge request is created on the project the branch lives in, which is the contributor’s fork\n  // with Open Authoring, and targets the configured project by ID\n  const result = /** @type {Record<string, any>} */ (\n    await fetchAPI(`/projects/${getProjectId(fork)}/merge_requests`, {\n      method: 'POST',\n      body: {\n        title: isDraft ? `${DRAFT_TITLE_PREFIX}${title}` : title,\n        source_branch: branch,\n        target_branch: repository.branch,\n        description: PULL_REQUEST_DESCRIPTION,\n        remove_source_branch: true,\n        ...(fork\n          ? {\n              target_project_id: projectIds.base,\n              // Let a maintainer amend the contribution on the branch it came from, which is what\n              // GitHub does by default for a pull request from a fork\n              allow_collaboration: true,\n            }\n          : // Labelling a merge request requires write access to the configured project, which an\n            // Open Authoring contributor doesn’t have. Their status is read from the merge request\n            // itself instead\n            { labels: getStatusLabel(status) }),\n      },\n    })\n  );\n\n  // Keep the given title rather than stripping the draft prefix from the returned one, which would\n  // also strip a title that happens to start with a draft indicator such as `WIP:`\n  return { ...toMergeRequest(result, status), title, branch };\n};\n\n/**\n * Fetch the open merge requests from the given branch of the configured project, whichever branch\n * they go to. A merge request from a fork can have a source branch of the same name, but it isn’t\n * from this branch, so it’s left out.\n * @param {string} branch Branch name.\n * @returns {Promise<Record<string, any>[]>} Merge requests returned by the REST API.\n * @see https://docs.gitlab.com/api/merge_requests/#list-project-merge-requests\n */\nexport const fetchOpenMergeRequests = async (branch) => {\n  const items = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(\n      `/projects/${getProjectId()}/merge_requests` +\n        `?state=opened&source_branch=${encodeURIComponent(branch)}` +\n        `&per_page=${MAX_ITEMS.mergeRequests}`,\n    )\n  );\n\n  return items.filter(\n    ({ source_project_id: sourceId, target_project_id: targetId }) => sourceId === targetId,\n  );\n};\n\n/**\n * Fetch the merge request as it stands.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @returns {Promise<Record<string, any>>} Merge request returned by the REST API.\n * @see https://docs.gitlab.com/api/merge_requests/#get-single-mr\n */\nexport const fetchMergeRequest = async (pullRequest) =>\n  /** @type {Record<string, any>} */ (\n    await fetchAPI(`/projects/${getProjectId()}/merge_requests/${pullRequest.number}`)\n  );\n","import { getWorkflowRepository, projectIds } from '$lib/services/backends/git/gitlab/fork';\nimport {\n  createPullRequest,\n  deleteBranch,\n  DRAFT_TITLE_PREFIX,\n  fetchBranchHead,\n  fetchMergeRequest,\n  fetchMergeRequestFileContents,\n  MAX_ITEMS,\n  parseDiff,\n  stripDraftPrefix,\n  toMergeRequest,\n} from '$lib/services/backends/git/gitlab/merge-requests';\nimport { getProjectId, repository } from '$lib/services/backends/git/gitlab/repository';\nimport { fetchAPI } 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 { pruneForkBranches, updateForkStatusWith } from '$lib/services/backends/git/shared/fork';\nimport { user } from '$lib/services/user/account.svelte';\nimport { getBranchListPrefix } from '$lib/services/workflow/branch';\n\n/**\n * @import { ForkRequestState, WorkflowPullRequest, WorkflowStatus } from '$lib/types/private';\n */\n\n/**\n * Fetch the Editorial Workflow branches in the contributor’s fork. With Open Authoring the branches\n * are the source of truth: a draft has no merge request yet, so listing merge requests alone would\n * miss it.\n * @returns {Promise<Record<string, any>[]>} Branches, as returned by the API.\n * @see https://docs.gitlab.com/api/branches/#list-repository-branches\n */\nexport const fetchForkBranchList = async () => {\n  const prefix = getBranchListPrefix();\n\n  const branches = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(\n      `/projects/${getProjectId(getWorkflowRepository())}/repository/branches` +\n        `?search=${encodeURIComponent(`^${prefix}`)}&per_page=${MAX_ITEMS.branches}`,\n    )\n  );\n\n  // The list isn’t paginated, so going over the cap drops an arbitrary set of branches from the\n  // board. Rare enough to leave unpaged, too confusing to leave unsaid\n  if (branches.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  return branches;\n};\n\n/**\n * Check whether the given merge request goes from the fork the CMS is working in to the configured\n * branch, which is the only kind GitLab refuses to open a second of from the same branch.\n * @param {Record<string, any>} item Merge request returned by the REST API.\n * @returns {boolean} Result.\n */\nconst isFromForkToBranch = (item) =>\n  item.source_project_id === projectIds.fork && item.target_branch === repository.branch;\n\n/**\n * Check whether the given merge request is one the CMS manages for the contributor: opened by them,\n * from the fork the CMS is working in, to the configured branch. Someone else’s merge request from\n * the contributor’s branch would put their title on the entry, and the contributor could neither\n * convert, reopen nor close it.\n * @param {Record<string, any>} item Merge request returned by the REST API.\n * @returns {boolean} Result.\n */\nconst isForkMergeRequest = (item) =>\n  isFromForkToBranch(item) && user.account?.id !== undefined && item.author?.id === user.account.id;\n\n/**\n * Fetch the merge request each of the given fork branches has on the configured project. A branch\n * in the fork doesn’t report the merge requests opened from it, and a merge request opened from a\n * fork lives on the project it targets, so they’re looked up there. What makes a merge request the\n * contributor’s is its source project, which has to be the fork the CMS is working in: a branch of\n * the same name elsewhere says nothing about where the merge request came from. The author filter\n * spends the single page of results on the user’s own merge requests, and is checked again on each\n * one rather than trusted to have applied.\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 merge\n * request opened from it, where there is one.\n * @see https://docs.gitlab.com/api/merge_requests/#list-project-merge-requests\n */\nexport const fetchForkBranchMergeRequests = 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 branchSet = new Set(branches);\n\n  const items = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(\n      `/projects/${getProjectId()}/merge_requests?state=all&order_by=created_at&sort=desc` +\n        `&author_id=${user.account?.id}&per_page=${MAX_ITEMS.authoredMergeRequests}`,\n    )\n  );\n\n  items.forEach((item) => {\n    // The merge request has to come from the fork the CMS is working in, not from the configured\n    // project and not from some other project of the contributor’s that happens to have a branch of\n    // the same name. The source project is checked rather than inferred from the branch name, the\n    // way GitHub’s flow checks the head repository’s owner\n    // @see https://github.com/sveltia/sveltia-cms/security/advisories/GHSA-p8qh-54q9-2qjx\n    //\n    // It also has to go to the configured branch. One the contributor aimed elsewhere in the\n    // project is their own business, and acting on it — relabelling or closing it as the entry\n    // moves — would be meddling with a review the CMS knows nothing about. And it has to be the\n    // contributor’s own, like on GitHub\n    if (!isForkMergeRequest(item)) {\n      return;\n    }\n\n    // The list is newest first, so the first match for a branch is the one that counts\n    if (branchSet.has(item.source_branch) && !map.has(item.source_branch)) {\n      map.set(item.source_branch, item);\n    }\n  });\n\n  return map;\n};\n\n/**\n * Parse a branch returned by {@link fetchForkBranchList}.\n * @param {Record<string, any>} branchInfo Branch.\n * @param {Record<string, any>} [mergeRequest] Merge request opened from the branch, from\n * {@link fetchForkBranchMergeRequests}.\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 = (branchInfo, mergeRequest) => {\n  const { name: branch, commit } = branchInfo;\n\n  const {\n    id: headSHA,\n    message,\n    committed_date: committedDate,\n    author_name: authorName,\n    author_email: authorEmail,\n  } = commit ?? {};\n\n  // A merged merge 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 merge request forward would instead try to reopen it when the entry moves to review\n  const current = mergeRequest?.state === 'merged' ? undefined : mergeRequest;\n  const isOpen = current?.state === 'opened';\n  // A closed merge 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.draft;\n  const { name, username, id } = current?.author ?? {};\n\n  // A merge request names its author, while a branch on its own only carries the identity Git\n  // recorded with the head commit\n  const author = username\n    ? { name: name ?? username, email: '', id, login: username }\n    : authorName && { name: authorName, email: authorEmail ?? '' };\n\n  return {\n    number: current?.iid,\n    nodeId: current ? String(current.id) : undefined,\n    // Without a merge request there’s no title to show, so the head commit’s message stands in.\n    // It’s the message the merge request would be opened with anyway\n    title: current ? stripDraftPrefix(current.title) : (message ?? ''),\n    url: current?.web_url,\n    branch,\n    // The branch head, rather than the merge request’s: a save compares it with the branch to find\n    // out whether anything has been committed since, and a closed merge request’s head is stale\n    headSHA,\n    status: inReview ? 'pending_review' : 'draft',\n    createdDate: new Date(current?.created_at ?? committedDate),\n    updatedDate: new Date(current?.updated_at ?? committedDate),\n    author: author || undefined,\n    files: [],\n    // Only a maintainer merges, and a contributor is never one\n    canMerge: false,\n  };\n};\n\n/**\n * Fetch the files a fork branch changes, and populate the `WorkflowFile` objects in place. A draft\n * has no merge request to list files from, so the branch is compared with the configured branch\n * instead. The comparison also reports the path a renamed file came from, and is used even where a\n * merge request exists: a closed one’s diff is no longer a reliable account of a branch that has\n * moved on since.\n * @param {WorkflowPullRequest} pullRequest Branch to complete.\n * @see https://docs.gitlab.com/api/repositories/#compare-branches-tags-or-commits\n */\nexport const fetchForkBranchFileList = async (pullRequest) => {\n  const { branch: baseBranch = '' } = repository;\n\n  // The comparison runs on the project that holds the branch being compared — the fork — and names\n  // the configured project as the one the base branch belongs to\n  const { diffs = [] } = /** @type {{ diffs?: Record<string, any>[] }} */ (\n    await fetchAPI(\n      `/projects/${getProjectId(getWorkflowRepository())}/repository/compare` +\n        `?from=${encodeURIComponent(baseBranch)}&to=${encodeURIComponent(pullRequest.branch)}` +\n        `&from_project_id=${projectIds.base}`,\n    )\n  );\n\n  pullRequest.files = diffs.map(parseDiff);\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 merge requests and changed files.\n */\nexport const fetchForkPullRequests = async () => {\n  const branchList = await fetchForkBranchList();\n  const mergeRequests = await fetchForkBranchMergeRequests(branchList.map(({ name }) => name));\n\n  const pending = await pruneForkBranches(\n    branchList,\n    (branchInfo) => {\n      const mergeRequest = mergeRequests.get(branchInfo.name);\n\n      return mergeRequest?.state === 'merged' && mergeRequest.sha === branchInfo.commit?.id\n        ? { leftover: branchInfo.name }\n        : { pending: parseForkBranch(branchInfo, mergeRequest) };\n    },\n    deleteBranch,\n  );\n\n  await runConcurrently(pending, fetchForkBranchFileList);\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 merge request looks like\n  const entries = pending.filter(({ files }) => files.length);\n\n  await runConcurrently(entries, fetchMergeRequestFileContents);\n\n  return entries;\n};\n\n/**\n * Work out the changes that move a merge request to the given stage. A contributor can’t label a\n * merge request on a project they don’t have access to, so the stage is recorded in the merge\n * request itself: an entry in review has one waiting for a maintainer, while a draft has one GitLab\n * still considers a draft, or none at all.\n * @param {object} args Arguments.\n * @param {WorkflowStatus} args.status New status.\n * @param {string} args.title Entry title, without a draft prefix.\n * @param {string} [args.state] State the merge request is in, e.g. `opened`.\n * @param {boolean} [args.draft] Whether GitLab considers the merge request a draft.\n * @returns {Record<string, any>} Request body, empty when the merge request already says as much.\n */\nconst getStatusChange = ({ status, title, state, draft }) => {\n  if (status === 'draft') {\n    // Marking the merge request as a draft keeps it — and the discussion on it — in place while\n    // taking it out of the maintainers’ review queue\n    return state === 'opened' && !draft ? { title: `${DRAFT_TITLE_PREFIX}${title}` } : {};\n  }\n\n  return {\n    ...(state === 'closed' ? { state_event: 'reopen' } : {}),\n    ...(draft ? { title } : {}),\n  };\n};\n\n/**\n * Apply the given changes to a merge request on the configured project, which is where a merge\n * request opened from the fork lives.\n * @param {number} number Merge request `iid`.\n * @param {Record<string, any>} body Changes, from {@link getStatusChange}. Nothing is sent when\n * there are none.\n * @see https://docs.gitlab.com/api/merge_requests/#edit-merge-request\n */\nconst applyStatusChange = async (number, body) => {\n  if (Object.keys(body).length) {\n    await fetchAPI(`/projects/${getProjectId()}/merge_requests/${number}`, { method: 'PUT', body });\n  }\n};\n\n/**\n * HTTP status GitLab answers a merge request it won’t create because the source branch already has\n * one open.\n * @see https://docs.gitlab.com/api/merge_requests/#create-merge-request\n */\nconst MERGE_REQUEST_EXISTS_STATUS = 409;\n\n/**\n * Fetch the open merge request from the given branch in the contributor’s fork to the configured\n * branch, if any. This is only asked about a branch the CMS found no merge request for, so one\n * found here either sits beyond the page {@link fetchForkBranchMergeRequests} reads — a contributor\n * with a long history in the project can have more merge requests than fit in it — or isn’t the\n * contributor’s own.\n * @param {string} branch Branch name.\n * @returns {Promise<Record<string, any> | undefined>} Merge request returned by the REST API, or\n * `undefined` if none is open from the branch.\n * @see https://docs.gitlab.com/api/merge_requests/#list-project-merge-requests\n */\nconst fetchOpenForkMergeRequest = async (branch) => {\n  const items = /** @type {Record<string, any>[]} */ (\n    await fetchAPI(\n      `/projects/${getProjectId()}/merge_requests` +\n        `?state=opened&source_branch=${encodeURIComponent(branch)}` +\n        `&per_page=${MAX_ITEMS.mergeRequests}`,\n    )\n  );\n\n  // A merge request from some other project of the contributor’s that happens to have a branch of\n  // the same name, or one to another branch, isn’t the one GitLab refused to open another of\n  // @see https://github.com/sveltia/sveltia-cms/security/advisories/GHSA-p8qh-54q9-2qjx\n  return items.find(isFromForkToBranch);\n};\n\n/**\n * Open the merge request that hands an Open Authoring draft over for review. GitLab refuses a\n * second merge request from a branch that already has one open to the same branch, which is what\n * happens when the entry’s own merge request sat beyond the page the load read and the entry was\n * taken for a draft. That merge request is the entry’s, so it’s taken over and moved to the stage\n * asked for, rather than reported as a conflict the contributor can do nothing about.\n * @param {object} args Arguments.\n * @param {string} args.branch Workflow branch name.\n * @param {string} args.title Merge request title.\n * @param {WorkflowStatus} args.status Status to open the merge request with.\n * @returns {Promise<WorkflowPullRequest>} New or adopted merge request.\n * @throws {Error} When the merge request could not be created, including when the one standing in\n * the way is someone else’s.\n */\nexport const createForkMergeRequest = async ({ branch, title, status }) => {\n  try {\n    return await createPullRequest({ branch, title, status });\n  } catch (/** @type {any} */ ex) {\n    if (ex.cause?.status !== MERGE_REQUEST_EXISTS_STATUS) {\n      throw ex;\n    }\n\n    const item = await fetchOpenForkMergeRequest(branch);\n\n    // Nothing the CMS can make sense of stands in the way, so let GitLab’s own refusal stand\n    // rather than claiming the entry is in review\n    if (!item) {\n      throw ex;\n    }\n\n    // Someone else opened it from the contributor’s branch, which anyone the fork lets push can\n    // do. Taking it over would put their title on the entry and hand their request to the\n    // maintainers in the contributor’s name, so the contributor is told what’s in the way instead\n    if (!isForkMergeRequest(item)) {\n      throw createLocalizedError(\n        'The workflow branch is in use by another merge request.',\n        'workflow.branch_in_use',\n        { number: `!${item.iid}` },\n      );\n    }\n\n    await applyStatusChange(\n      item.iid,\n      getStatusChange({ status, title, state: item.state, draft: item.draft }),\n    );\n\n    // Keep the entry’s title rather than the one the merge request was opened with, which may have\n    // been edited on GitLab\n    return { ...toMergeRequest(item, status), title, branch };\n  }\n};\n\n/**\n * Read the current state of the merge request an Open Authoring entry has, for\n * {@link updateForkStatusWith}.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @returns {Promise<ForkRequestState>} State.\n */\nconst fetchForkRequestState = async (pullRequest) => {\n  const item = await fetchMergeRequest(pullRequest);\n\n  return {\n    merged: item.state === 'merged',\n    isEntryRequest: isForkMergeRequest(item),\n    /**\n     * Read the head commit the merge request was merged at.\n     * @returns {Promise<string>} Commit SHA.\n     */\n    getMergedSHA: async () => item.sha,\n    state: item.state,\n    draft: item.draft,\n  };\n};\n\n/**\n * Bring a merge request in line with the given status, for {@link updateForkStatusWith}. Unlike on\n * the other services, the whole transition is made with a single request.\n * @param {object} args Arguments.\n * @param {WorkflowPullRequest} args.pullRequest Merge request.\n * @param {WorkflowStatus} args.status New status.\n * @param {string} [args.state] Merge request state, e.g. `opened`.\n * @param {boolean} [args.draft] Whether GitLab considers the merge request a draft.\n */\nconst applyForkStatus = async ({ pullRequest: { number, title }, status, state, draft }) => {\n  await applyStatusChange(\n    /** @type {number} */ (number),\n    getStatusChange({ status, title, state, draft }),\n  );\n};\n\n/**\n * Move an Open Authoring entry between the drafting and review stages, which is recorded in its\n * merge request: see {@link getStatusChange}.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @param {WorkflowStatus} status New status.\n * @returns {Promise<WorkflowPullRequest>} Updated merge request, or a new one if the known one is\n * no 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: 'number',\n    createRequest: createForkMergeRequest,\n    fetchRequest: fetchForkRequestState,\n    applyStatus: applyForkStatus,\n    fetchBranchHead,\n    deleteBranch,\n  });\n","import { sleep } from '@sveltia/utils/misc';\n\nimport { commitChanges } from '$lib/services/backends/git/gitlab/commits';\nimport { fetchBlobNodes } from '$lib/services/backends/git/gitlab/files';\nimport { getWorkflowRepository } from '$lib/services/backends/git/gitlab/fork';\nimport {\n  createPullRequest,\n  deleteBranch,\n  DRAFT_TITLE_PREFIX,\n  fetchBranchHead,\n  fetchPullRequests as fetchLabelledPullRequests,\n  fetchMergeRequest,\n  fetchOpenMergeRequests,\n} from '$lib/services/backends/git/gitlab/merge-requests';\nimport { getProjectId, repository } from '$lib/services/backends/git/gitlab/repository';\nimport {\n  fetchForkPullRequests,\n  updateForkStatus,\n} from '$lib/services/backends/git/gitlab/workflow-fork';\nimport { fetchAPI } from '$lib/services/backends/git/shared/api';\nimport { assertBranchNotMoved } from '$lib/services/backends/git/shared/commits';\nimport { checkPublishAllowed } from '$lib/services/backends/git/shared/fork';\nimport {\n  assertBranchAtHead,\n  commitToNewWorkflowBranch,\n  isSquashMergeEnabled,\n  saveWorkflowBranch,\n} from '$lib/services/backends/git/shared/workflow';\nimport { getAllStatusLabels, getStatusLabel } from '$lib/services/workflow/labels';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * CommitOptions,\n * CommitResults,\n * FileChange,\n * WorkflowChangedFile,\n * WorkflowMergeState,\n * WorkflowPullRequest,\n * WorkflowSaveOptions,\n * WorkflowStatus,\n * } from '$lib/types/private';\n */\n\n/**\n * Merge statuses GitLab reports while its mergeability check is queued or running. The check runs\n * in the background once a merge request is created or pushed to, so one of these is what a merge\n * request opened or updated a moment ago answers with; the real status follows once the check is\n * done. Approval rules are re-synced in the background as well, on a project that has them.\n * @see https://docs.gitlab.com/api/merge_requests/#merge-status\n */\nconst TRANSIENT_MERGE_STATUSES = ['preparing', 'unchecked', 'checking', 'approvals_syncing'];\n/**\n * How many times, and how often, the merge status is read while it’s transient. The check\n * usually takes a second or two.\n */\nconst MERGE_STATUS_POLL = { attempts: 10, interval: 1000 };\n/**\n * Merge statuses under which a merge request set to auto-merge is still expected to merge on its\n * own: the pipeline hasn’t finished, the mergeability check is being redone once it has, or the\n * merge itself is queued. Anything else — `ci_must_pass` once the pipeline has failed, say — means\n * GitLab is done waiting, even though the auto-merge stays armed in case a job is retried by hand.\n * @see https://docs.gitlab.com/user/project/merge_requests/auto_merge/\n */\nconst AUTO_MERGE_WAIT_STATUSES = [...TRANSIENT_MERGE_STATUSES, 'ci_still_running', 'mergeable'];\n/**\n * How often, and for how long at most, a merge request set to auto-merge is read while GitLab\n * waits for its pipeline. A pipeline takes minutes, so the reads are spaced out. The cap is a\n * safety net for a merge that never lands, e.g. one GitLab has queued but not carried out.\n */\nconst AUTO_MERGE_POLL = { interval: 10000, maxDuration: 60 * 60 * 1000 };\n\n/**\n * Fetch all the unpublished entries the signed-in user has in progress.\n * @returns {Promise<WorkflowPullRequest[]>} Merge requests.\n */\nexport const fetchPullRequests = async () =>\n  openAuthoring.current ? fetchForkPullRequests() : fetchLabelledPullRequests();\n\n/**\n * Commit the given changes on a workflow branch that no merge request is known for, creating the\n * branch from the configured one; see {@link commitToNewWorkflowBranch} for a branch that already\n * exists.\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 merge request is open from it.\n */\nconst commitToNewBranch = async (changes, options) => {\n  const { branch = '' } = options;\n  const startBranch = repository.branch;\n\n  return commitToNewWorkflowBranch({\n    branch,\n    // GitLab rejects `start_branch` outright once the branch exists\n    branchExistsStatus: 400,\n    /**\n     * Commit the changes on a branch created from the start branch.\n     * @returns {Promise<CommitResults>} Commit results.\n     */\n    commitFromStart: () => commitChanges(changes, { ...options, startBranch }),\n    /**\n     * Commit the changes onto the existing branch.\n     * @returns {Promise<CommitResults>} Commit results.\n     */\n    commitOnBranch: () => commitChanges(changes, options),\n    /**\n     * Look up a merge request open from the branch.\n     * @returns {Promise<string | undefined>} Its reference, or `undefined` if there is none.\n     */\n    findOpenPullRequest: async () => {\n      const [openMergeRequest] = await fetchOpenMergeRequests(branch);\n\n      return openMergeRequest ? `!${openMergeRequest.iid}` : undefined;\n    },\n    inUseMessage: 'The workflow branch is in use by another merge request.',\n    deleteBranch,\n  });\n};\n\n/**\n * Commit the given changes onto the branch of an existing merge request. An entry’s branch is named\n * after the entry, not the editor, so someone else can push to it too, and GitLab can’t be told\n * which commit a commit has to go on top of: it lands on whatever the branch points at. So the\n * branch has to point at the commit the entry was loaded or saved at, which the conflict check has\n * just compared it with, or a commit pushed since would go out with the save, vouched for by the\n * head recorded afterwards. Without a head on record there’s nothing to compare, which is refused\n * just the same. The head also goes with the commit as the last commit of each file it changes, so\n * a push that lands in the last moment and touches the same files makes GitLab refuse the save.\n * @param {FileChange[]} changes Changes to be committed.\n * @param {CommitOptions} options Commit options, with the workflow branch.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @returns {Promise<CommitResults>} Commit results.\n * @throws {Error} When the branch is gone, or points at another commit than the one on record.\n */\nconst commitToExistingBranch = async (changes, options, pullRequest) => {\n  const { branch = '' } = options;\n\n  const headSHA = await assertBranchAtHead({\n    branch,\n    headSHA: pullRequest.headSHA,\n    fetchBranchHead,\n    getWorkflowRepository,\n  });\n\n  try {\n    return await commitChanges(changes, { ...options, headOid: headSHA });\n  } catch (/** @type {any} */ ex) {\n    // GitLab refuses a file changed since with a 400 Bad Request, like any other invalid request\n    if (ex.cause?.status === 400) {\n      await assertBranchNotMoved(headSHA, async () => ({\n        hash: /** @type {string} */ (await fetchBranchHead(branch)),\n      }));\n    }\n\n    throw ex;\n  }\n};\n\n/**\n * Update the merge request’s status label and draft state. A merge request in the `draft` status is\n * kept as a GitLab draft, so it cannot be merged accidentally. GitLab stores the draft state in the\n * title, so the title is rewritten along with the labels in a single request.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @param {WorkflowStatus} status New status.\n * @returns {Promise<WorkflowPullRequest>} Updated merge request.\n * @see https://docs.gitlab.com/api/merge_requests/#edit-merge-request\n */\nexport const updateStatus = async (pullRequest, status) => {\n  if (openAuthoring.current) {\n    return updateForkStatus(pullRequest, status);\n  }\n\n  const newLabel = getStatusLabel(status);\n  const isDraft = status === 'draft';\n  const title = isDraft ? `${DRAFT_TITLE_PREFIX}${pullRequest.title}` : pullRequest.title;\n\n  await fetchAPI(`/projects/${getProjectId()}/merge_requests/${pullRequest.number}`, {\n    method: 'PUT',\n    body: {\n      title,\n      // Use `add_labels`/`remove_labels` instead of `labels`, so any label added outside the CMS is\n      // preserved. The new label must not be in the removal list, or GitLab would drop it.\n      add_labels: newLabel,\n      remove_labels: getAllStatusLabels()\n        .filter((label) => label !== newLabel)\n        .join(','),\n    },\n  });\n\n  return { ...pullRequest, status, updatedDate: new Date() };\n};\n\n/**\n * Commit the given changes on the workflow branch, creating the branch and the merge request if\n * they don’t exist yet.\n * @param {WorkflowSaveOptions} args Arguments.\n * @returns {Promise<{ commit: CommitResults, pullRequest: WorkflowPullRequest }>} Commit results\n * and the new or updated merge request.\n */\nexport const savePullRequest = async (args) =>\n  saveWorkflowBranch(args, { commitToNewBranch, commitToExistingBranch, createPullRequest });\n\n/**\n * Fetch the merge request’s detailed merge status, which names the single check that stands in the\n * way of an immediate merge, e.g. `ci_still_running`. A transient status is polled until it settles\n * or the attempts run out, in which case the transient status is returned as is.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @param {number} [attemptsLeft] Remaining reads, including this one.\n * @returns {Promise<string | undefined>} Detailed merge status.\n * @see https://docs.gitlab.com/api/merge_requests/#merge-status\n */\nconst fetchMergeStatus = async (pullRequest, attemptsLeft = MERGE_STATUS_POLL.attempts) => {\n  const { detailed_merge_status: status } = await fetchMergeRequest(pullRequest);\n\n  if (!TRANSIENT_MERGE_STATUSES.includes(status) || attemptsLeft <= 1) {\n    return status;\n  }\n\n  await sleep(MERGE_STATUS_POLL.interval);\n\n  return fetchMergeStatus(pullRequest, attemptsLeft - 1);\n};\n\n/**\n * Cancel the auto-merge on the given merge request. Failures are ignored: this is called once the\n * publish is being reported as failed, and a merge request that has just been merged or closed\n * has no auto-merge left to cancel.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @see https://docs.gitlab.com/api/merge_requests/#cancel-merge-when-pipeline-succeeds\n */\nconst cancelAutoMerge = async (pullRequest) => {\n  try {\n    await fetchAPI(\n      `/projects/${getProjectId()}/merge_requests/${pullRequest.number}` +\n        '/cancel_merge_when_pipeline_succeeds',\n      { method: 'POST' },\n    );\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.warn(`Failed to cancel the auto-merge on merge request !${pullRequest.number}.`, ex);\n  }\n};\n\n/**\n * Wait for GitLab to merge a merge request that has been set to auto-merge. The merge request is\n * read every so often until it’s merged, in which case this resolves, or until it’s clear that the\n * merge won’t happen on its own: the pipeline has failed, a new commit has cancelled the\n * auto-merge, the merge request has been closed, or the wait has run out. Those are reported as\n * errors, so the entry stays on the Editorial Workflow board rather than being taken for\n * published. GitLab keeps the auto-merge armed after a failed pipeline, in case a job is retried by\n * hand, but a merge made that way would happen behind the CMS’s back once it has reported a\n * failure, so the auto-merge is cancelled along with the report: publishing again is what merges\n * the entry from then on.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @param {number} [deadline] Time to give up at, as a Unix timestamp in milliseconds.\n * @returns {Promise<void>}\n * @throws {Error} When the merge request won’t be merged, or wasn’t within the time allowed.\n * @see https://github.com/sveltia/sveltia-cms/issues/992\n */\nconst waitForAutoMerge = async (\n  pullRequest,\n  deadline = Date.now() + AUTO_MERGE_POLL.maxDuration,\n) => {\n  if (Date.now() >= deadline) {\n    await cancelAutoMerge(pullRequest);\n\n    throw new Error(`Timed out waiting for merge request !${pullRequest.number} to be merged`);\n  }\n\n  await sleep(AUTO_MERGE_POLL.interval);\n\n  const mergeRequest = await fetchMergeRequest(pullRequest).catch((ex) => {\n    const status = ex.cause?.status;\n\n    // A network error or a server error says nothing about the merge, which GitLab carries out on\n    // its own, so keep waiting rather than reporting a failure that hasn’t happened. A client\n    // error won’t go away by itself — the session has ended, or the merge request is gone — so\n    // there’s no point in asking again, except when the limit on requests has been hit\n    if (typeof status === 'number' && status >= 400 && status < 500 && status !== 429) {\n      throw ex;\n    }\n\n    // eslint-disable-next-line no-console\n    console.warn(`Failed to read merge request !${pullRequest.number}, still waiting.`, ex);\n\n    return undefined;\n  });\n\n  if (mergeRequest) {\n    const {\n      state,\n      merge_when_pipeline_succeeds: autoMerge,\n      detailed_merge_status: status,\n    } = mergeRequest;\n\n    if (state === 'merged') {\n      return;\n    }\n\n    // `locked` is the merge in progress\n    const waiting =\n      state === 'locked' ||\n      (state === 'opened' && !!autoMerge && AUTO_MERGE_WAIT_STATUSES.includes(status));\n\n    if (!waiting) {\n      if (state === 'opened' && autoMerge) {\n        await cancelAutoMerge(pullRequest);\n      }\n\n      throw new Error(\n        `Merge request !${pullRequest.number} was not merged: ${state}, ${status}, ` +\n          `auto-merge ${autoMerge ? 'on' : 'off'}`,\n      );\n    }\n  }\n\n  await waitForAutoMerge(pullRequest, deadline);\n};\n\n/**\n * Number of files past which GitLab cuts a comparison short by default, without saying so.\n * @see https://docs.gitlab.com/administration/diff_limits/\n */\nconst MAX_COMPARE_FILES = 1000;\n\n/**\n * Get how the given diff changes its file.\n * @param {Record<string, any>} diff Diff returned by the REST API.\n * @returns {WorkflowChangedFile['status']} Status.\n */\nconst getDiffStatus = (diff) => {\n  if (diff.new_file) {\n    return 'added';\n  }\n\n  if (diff.deleted_file) {\n    return 'removed';\n  }\n\n  return diff.renamed_file ? 'renamed' : 'modified';\n};\n\n/**\n * Read the merge request afresh right before it’s merged. The files are listed by comparing the\n * configured branch with the very commit the merge request points at, rather than read off the\n * merge request, so they describe exactly what a merge pinned to that commit would bring in, even\n * if the branch moves on meanwhile. The comparison can stop short of the whole list on a large\n * change, which the merge request’s own count of changes tells.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @returns {Promise<WorkflowMergeState>} State.\n * @see https://docs.gitlab.com/api/merge_requests/#get-single-mr\n * @see https://docs.gitlab.com/api/repositories/#compare-branches-tags-or-commits\n */\nexport const fetchMergeState = async (pullRequest) => {\n  const {\n    sha: headSHA,\n    target_branch: targetBranch,\n    source_project_id: sourceId,\n    target_project_id: targetId,\n    changes_count: changesCount,\n  } = await fetchMergeRequest(pullRequest);\n\n  const onConfiguredBranches = targetBranch === repository.branch && sourceId === targetId;\n\n  if (!headSHA || !onConfiguredBranches) {\n    return { headSHA, onConfiguredBranches: false, files: [], complete: false };\n  }\n\n  const { diffs = [] } = /** @type {{ diffs?: Record<string, any>[] }} */ (\n    await fetchAPI(\n      `/projects/${getProjectId()}/repository/compare` +\n        `?from=${encodeURIComponent(/** @type {string} */ (targetBranch))}` +\n        `&to=${encodeURIComponent(headSHA)}&straight=false`,\n    )\n  );\n\n  // `changes_count` is a string, which reads like `1000+` past GitLab’s limit, and is missing\n  // while the merge request’s diff is still being worked out. The comparison is then all there is\n  // to go by, and one that reaches GitLab’s default limit on files may have been cut short\n  const count = changesCount === null || changesCount === undefined ? undefined : `${changesCount}`;\n\n  const complete =\n    count === undefined\n      ? diffs.length < MAX_COMPARE_FILES\n      : !count.endsWith('+') && diffs.length >= Number(count);\n\n  return {\n    headSHA,\n    onConfiguredBranches,\n    files: diffs.map((diff) => ({\n      path: diff.new_path,\n      status: getDiffStatus(diff),\n      previousPath: diff.renamed_file ? diff.old_path : undefined,\n      mode: diff.deleted_file ? undefined : diff.b_mode,\n    })),\n    complete,\n  };\n};\n\n/**\n * Query to fetch the Git object IDs of the blobs at the given paths on a branch or commit.\n */\nconst FETCH_BLOB_IDS_QUERY = `\n  query($fullPath: ID!, $branch: String!, $paths: [String!]!) {\n    project(fullPath: $fullPath) {\n      repository {\n        blobs(ref: $branch, paths: $paths) {\n          nodes {\n            path\n            oid\n          }\n        }\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.gitlab.com/api/graphql/reference/#repositoryblob\n */\nexport const fetchUnchangedPaths = async ({ headSHA, paths }) => {\n  const [base, head] = await Promise.all(\n    [/** @type {string} */ (repository.branch), headSHA].map(async (branch) => {\n      const nodes = await fetchBlobNodes(paths, FETCH_BLOB_IDS_QUERY, { branch });\n\n      return new Map(nodes.map((/** @type {any} */ { path, oid }) => [path, oid]));\n    }),\n  );\n\n  return paths.filter((path) => base.get(path) === head.get(path));\n};\n\n/**\n * Merge the merge request and delete the workflow branch. A project or group can require the merge\n * request’s pipeline to succeed before it can be merged; the group-level setting is not exposed by\n * the project API. In that case, GitLab refuses an immediate merge while the pipeline is running,\n * which is likely right after the merge request is opened — always so for a deletion, which can be\n * published as soon as it’s created — so the merge request is set to auto-merge instead, and GitLab\n * merges it once the pipeline has passed. Scheduling the merge is not the same as making it: the\n * pipeline can still fail, so this resolves only once the merge has landed.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @see https://docs.gitlab.com/api/merge_requests/#merge-a-merge-request\n * @see https://github.com/sveltia/sveltia-cms/issues/989\n */\nexport const publish = async (pullRequest) => {\n  checkPublishAllowed();\n\n  const squash = isSquashMergeEnabled();\n  const path = `/projects/${getProjectId()}/merge_requests/${pullRequest.number}/merge`;\n\n  const body = {\n    squash,\n    should_remove_source_branch: true,\n    // A group or instance can require the source branch’s current HEAD SHA on this call; without\n    // it, the merge fails with `SHA must be provided when merging` even though the branch is up\n    // to date.\n    // @see https://github.com/decaporg/decap-cms/issues/7963\n    // @see https://docs.gitlab.com/user/group/manage/#require-a-commit-sha-on-the-merge-requests-api\n    ...(pullRequest.headSHA ? { sha: pullRequest.headSHA } : {}),\n    ...(squash\n      ? { squash_commit_message: pullRequest.title }\n      : { merge_commit_message: pullRequest.title }),\n  };\n\n  try {\n    await fetchAPI(path, { method: 'PUT', body });\n  } catch (/** @type {any} */ ex) {\n    // GitLab answers 405 Method Not Allowed whenever the merge request can’t be merged right away,\n    // whatever the reason, so the detailed status tells a running pipeline from a real blocker,\n    // such as a conflict. Auto-merge would take a blocked merge request as well, but it would sit\n    // there unmerged while the CMS reports the entry as published, so anything else stays an\n    // error\n    if (ex.cause?.status !== 405 || (await fetchMergeStatus(pullRequest)) !== 'ci_still_running') {\n      throw ex;\n    }\n\n    // `merge_when_pipeline_succeeds` is the pre-17.11 name of `auto_merge`, which a self-managed\n    // instance may still be on. GitLab reads either, so both are sent\n    await fetchAPI(path, {\n      method: 'PUT',\n      body: { ...body, auto_merge: true, merge_when_pipeline_succeeds: true },\n    });\n\n    // The merge request stays open until the pipeline passes, and GitLab removes the branch along\n    // with the merge, as requested above. Deleting it here would close the merge request instead\n    await waitForAutoMerge(pullRequest);\n\n    return;\n  }\n\n  await deleteBranch(pullRequest.branch);\n};\n\n/**\n * Close the merge request without merging it, and delete the workflow branch.\n * @param {WorkflowPullRequest} pullRequest Merge request.\n * @see https://docs.gitlab.com/api/merge_requests/#edit-merge-request\n */\nexport const discard = async (pullRequest) => {\n  // An Open Authoring draft has no merge request yet, so deleting the branch is all there is to do\n  if (pullRequest.number !== undefined) {\n    await fetchAPI(`/projects/${getProjectId()}/merge_requests/${pullRequest.number}`, {\n      method: 'PUT',\n      body: { state_event: 'close' },\n    });\n  }\n\n  await deleteBranch(pullRequest.branch);\n};\n\n/**\n * GitLab’s Editorial Workflow implementation.\n * @type {import('$lib/types/private').WorkflowBackendService}\n */\nexport default {\n  fetchPullRequests,\n  savePullRequest,\n  updateStatus,\n  fetchBranchHead,\n  fetchMergeState,\n  fetchUnchangedPaths,\n  publish,\n  discard,\n};\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { getTokenPageURL, signIn, signOut } from '$lib/services/backends/git/gitlab/auth';\nimport {\n  commitChanges,\n  fetchFileCommits,\n  fetchLastCommit,\n} from '$lib/services/backends/git/gitlab/commits';\nimport {\n  BACKEND_LABEL,\n  BACKEND_NAME,\n  DEFAULT_API_ROOT,\n  DEFAULT_AUTH_PATH,\n  DEFAULT_AUTH_ROOT,\n  DEFAULT_PKCE_AUTH_PATH,\n  DEFAULT_PKCE_AUTH_ROOT,\n} from '$lib/services/backends/git/gitlab/constants';\nimport { fetchBranchHeadSHA, fetchDeployments } from '$lib/services/backends/git/gitlab/deployment';\nimport { fetchBlob, fetchDirSHA, fetchFiles } from '$lib/services/backends/git/gitlab/files';\nimport {\n  getBaseURLs,\n  parseProjectPath,\n  repository,\n} from '$lib/services/backends/git/gitlab/repository';\nimport { checkStatus, STATUS_DASHBOARD_URL } from '$lib/services/backends/git/gitlab/status';\nimport workflow from '$lib/services/backends/git/gitlab/workflow';\nimport { graphqlVars } from '$lib/services/backends/git/shared/api';\nimport { initGitBackend } from '$lib/services/backends/git/shared/init';\nimport { cmsConfig } from '$lib/services/config';\n\n/**\n * @import { BackendService, RepositoryInfo } from '$lib/types/private';\n */\n\n/**\n * Initialize the GitLab backend.\n * @returns {RepositoryInfo | undefined} Repository info, or nothing when the configured backend is\n * not GitLab.\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    auth_type: authType = '',\n    // Like Decap CMS, sign in through Netlify unless the client-side PKCE flow is used\n    base_url: authRoot = authType === 'pkce' ? DEFAULT_PKCE_AUTH_ROOT : DEFAULT_AUTH_ROOT,\n    auth_endpoint: authPath = authType === 'pkce' ? DEFAULT_PKCE_AUTH_PATH : DEFAULT_AUTH_PATH,\n    app_id: clientId = '',\n    // https://HOSTNAME/api/v1 or https://HOSTNAME/PATH/api/v1\n    api_root: restApiRoot = DEFAULT_API_ROOT,\n    // https://HOSTNAME/api/graphql or https://HOSTNAME/PATH/api/graphql\n    graphql_api_root: graphqlApiRoot = restApiRoot.replace(/\\/api\\/.+$/, '/api/graphql'),\n    include_credentials: includeCredentials = false,\n  } = backend;\n\n  const { owner, repo } = parseProjectPath(/** @type {string} */ (projectPath));\n  const repoPath = `${owner}/${repo}`;\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    authPath,\n    tokenPath: '/token',\n    api: {\n      clientId,\n      authScope: 'api',\n      authScheme: 'Bearer',\n      restBaseURL: stripSlashes(restApiRoot),\n      graphqlBaseURL: stripSlashes(graphqlApiRoot),\n      includeCredentials,\n    },\n  });\n\n  Object.assign(graphqlVars, {\n    fullPath: repoPath,\n    branch,\n  });\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  fetchBranchHeadSHA,\n  fetchDeployments,\n  workflow,\n};\n","import gitea from '$lib/services/backends/git/gitea';\nimport github from '$lib/services/backends/git/github';\nimport gitlab from '$lib/services/backends/git/gitlab';\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. This lives apart from the full list of backend services in\n * the parent module so that the local backend, which wraps one of these, can look its remote up\n * without a circular import. Each service is wrapped so the paths the CMS deals with are relative\n * to the `root_dir` backend option, if configured.\n * @type {Record<string, BackendService>}\n */\nexport const gitBackendServices = {\n  github: scopeBackendService(github),\n  gitlab: scopeBackendService(gitlab),\n  gitea: scopeBackendService(gitea),\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","import { getScopedRootDirHandle, readFile } 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 { getRepositoryDatabase } from '$lib/services/utils/database';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * Asset,\n * BackendService,\n * CommitResults,\n * FileChange,\n * InternalCmsConfig,\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 * @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 (ex.name === 'TypeMismatchError') {\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  } 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  await rootDirHandleDB?.delete(ROOT_DIR_HANDLE_KEY);\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.\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: backendName,\n  label,\n  repository,\n  init,\n  signIn,\n  signOut,\n  fetchFiles,\n  fetchBlob,\n  commitChanges,\n};\n","import {\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';\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\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.\n * @returns {Promise<User>} User info. Since we don’t have any details for the local user, just\n * return the backend name.\n * @see https://web.dev/articles/origin-private-file-system\n * @todo Preload entry files on the demo site.\n */\nconst signIn = async () => {\n  try {\n    // The configured root directory is created if needed, like the backend’s own directory\n    rootDirHandle = await getScopedRootDirHandle(\n      await getDirectoryHandle(await navigator.storage.getDirectory(), 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 local from '$lib/services/backends/fs/local';\nimport test from '$lib/services/backends/fs/test';\nimport { gitBackendServices } from '$lib/services/backends/git/services';\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 all the supported backend services.\n * @type {Record<string, BackendService>}\n * @see https://decapcms.org/docs/backends-overview/\n * @see https://sveltiacms.app/en/docs/backends\n */\nexport const allBackendServices = {\n  ...gitBackendServices,\n  local,\n  'test-repo': test,\n};\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#features-not-to-be-implemented\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(allBackendServices).filter((name) => name !== 'local')\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 ? allBackendServices[backendName.current] : undefined,\n);\n\n/**\n * Select the backend service with the given name, initializing it if it’s not the current one.\n * @param {string | undefined} name Backend name, or `undefined` to deselect the current backend.\n * @returns {BackendService | undefined} Selected backend service, if any.\n */\nexport const selectBackend = (name) => {\n  const service = name ? allBackendServices[name] : undefined;\n\n  if (service && service !== backend.current) {\n    service.init();\n  }\n\n  backendName.current = name;\n\n  return service;\n};\n","const replacements = [\n\t// German umlauts\n\t['ß', 'ss'],\n\t['ẞ', 'Ss'],\n\t['ä', 'ae'],\n\t['Ä', 'Ae'],\n\t['ö', 'oe'],\n\t['Ö', 'Oe'],\n\t['ü', 'ue'],\n\t['Ü', 'Ue'],\n\n\t// Latin\n\t['À', 'A'],\n\t['Á', 'A'],\n\t['Â', 'A'],\n\t['Ã', 'A'],\n\t['Ä', 'Ae'],\n\t['Å', 'A'],\n\t['Æ', 'AE'],\n\t['Ç', 'C'],\n\t['È', 'E'],\n\t['É', 'E'],\n\t['Ê', 'E'],\n\t['Ë', 'E'],\n\t['Ə', 'A'], // Azerbaijani schwa\n\t['Ì', 'I'],\n\t['Í', 'I'],\n\t['Î', 'I'],\n\t['Ï', 'I'],\n\t['Ð', 'D'],\n\t['Ñ', 'N'],\n\t['Ò', 'O'],\n\t['Ó', 'O'],\n\t['Ô', 'O'],\n\t['Õ', 'O'],\n\t['Ö', 'Oe'],\n\t['Ō', 'O'],\n\t['Ő', 'O'],\n\t['Ø', 'O'],\n\t['Œ', 'OE'], // French ligature\n\t['Ù', 'U'],\n\t['Ú', 'U'],\n\t['Û', 'U'],\n\t['Ü', 'Ue'],\n\t['Ű', 'U'],\n\t['Ý', 'Y'],\n\t['Þ', 'TH'],\n\t['ß', 'ss'],\n\t['à', 'a'],\n\t['á', 'a'],\n\t['â', 'a'],\n\t['ã', 'a'],\n\t['ä', 'ae'],\n\t['å', 'a'],\n\t['æ', 'ae'],\n\t['ç', 'c'],\n\t['è', 'e'],\n\t['é', 'e'],\n\t['ê', 'e'],\n\t['ë', 'e'],\n\t['ə', 'a'], // Azerbaijani schwa\n\t['ì', 'i'],\n\t['í', 'i'],\n\t['î', 'i'],\n\t['ï', 'i'],\n\t['ð', 'd'],\n\t['ñ', 'n'],\n\t['ò', 'o'],\n\t['ó', 'o'],\n\t['ô', 'o'],\n\t['õ', 'o'],\n\t['ö', 'oe'],\n\t['ō', 'o'],\n\t['ő', 'o'],\n\t['ø', 'o'],\n\t['œ', 'oe'], // French ligature\n\t['ù', 'u'],\n\t['ú', 'u'],\n\t['û', 'u'],\n\t['ü', 'ue'],\n\t['ű', 'u'],\n\t['ý', 'y'],\n\t['þ', 'th'],\n\t['ÿ', 'y'],\n\n\t// Vietnamese\n\t['à', 'a'],\n\t['À', 'A'],\n\t['á', 'a'],\n\t['Á', 'A'],\n\t['â', 'a'],\n\t['Â', 'A'],\n\t['ã', 'a'],\n\t['Ã', 'A'],\n\t['è', 'e'],\n\t['È', 'E'],\n\t['é', 'e'],\n\t['É', 'E'],\n\t['ê', 'e'],\n\t['Ê', 'E'],\n\t['ì', 'i'],\n\t['Ì', 'I'],\n\t['í', 'i'],\n\t['Í', 'I'],\n\t['ò', 'o'],\n\t['Ò', 'O'],\n\t['ó', 'o'],\n\t['Ó', 'O'],\n\t['ô', 'o'],\n\t['Ô', 'O'],\n\t['õ', 'o'],\n\t['Õ', 'O'],\n\t['ù', 'u'],\n\t['Ù', 'U'],\n\t['ú', 'u'],\n\t['Ú', 'U'],\n\t['ý', 'y'],\n\t['Ý', 'Y'],\n\t['ă', 'a'],\n\t['Ă', 'A'],\n\t['Đ', 'D'],\n\t['đ', 'd'],\n\t['ĩ', 'i'],\n\t['Ĩ', 'I'],\n\t['ũ', 'u'],\n\t['Ũ', 'U'],\n\t['ơ', 'o'],\n\t['Ơ', 'O'],\n\t['ư', 'u'],\n\t['Ư', 'U'],\n\t['ạ', 'a'],\n\t['Ạ', 'A'],\n\t['ả', 'a'],\n\t['Ả', 'A'],\n\t['ấ', 'a'],\n\t['Ấ', 'A'],\n\t['ầ', 'a'],\n\t['Ầ', 'A'],\n\t['ẩ', 'a'],\n\t['Ẩ', 'A'],\n\t['ẫ', 'a'],\n\t['Ẫ', 'A'],\n\t['ậ', 'a'],\n\t['Ậ', 'A'],\n\t['ắ', 'a'],\n\t['Ắ', 'A'],\n\t['ằ', 'a'],\n\t['Ằ', 'A'],\n\t['ẳ', 'a'],\n\t['Ẳ', 'A'],\n\t['ẵ', 'a'],\n\t['Ẵ', 'A'],\n\t['ặ', 'a'],\n\t['Ặ', 'A'],\n\t['ẹ', 'e'],\n\t['Ẹ', 'E'],\n\t['ẻ', 'e'],\n\t['Ẻ', 'E'],\n\t['ẽ', 'e'],\n\t['Ẽ', 'E'],\n\t['ế', 'e'],\n\t['Ế', 'E'],\n\t['ề', 'e'],\n\t['Ề', 'E'],\n\t['ể', 'e'],\n\t['Ể', 'E'],\n\t['ễ', 'e'],\n\t['Ễ', 'E'],\n\t['ệ', 'e'],\n\t['Ệ', 'E'],\n\t['ỉ', 'i'],\n\t['Ỉ', 'I'],\n\t['ị', 'i'],\n\t['Ị', 'I'],\n\t['ọ', 'o'],\n\t['Ọ', 'O'],\n\t['ỏ', 'o'],\n\t['Ỏ', 'O'],\n\t['ố', 'o'],\n\t['Ố', 'O'],\n\t['ồ', 'o'],\n\t['Ồ', 'O'],\n\t['ổ', 'o'],\n\t['Ổ', 'O'],\n\t['ỗ', 'o'],\n\t['Ỗ', 'O'],\n\t['ộ', 'o'],\n\t['Ộ', 'O'],\n\t['ớ', 'o'],\n\t['Ớ', 'O'],\n\t['ờ', 'o'],\n\t['Ờ', 'O'],\n\t['ở', 'o'],\n\t['Ở', 'O'],\n\t['ỡ', 'o'],\n\t['Ỡ', 'O'],\n\t['ợ', 'o'],\n\t['Ợ', 'O'],\n\t['ụ', 'u'],\n\t['Ụ', 'U'],\n\t['ủ', 'u'],\n\t['Ủ', 'U'],\n\t['ứ', 'u'],\n\t['Ứ', 'U'],\n\t['ừ', 'u'],\n\t['Ừ', 'U'],\n\t['ử', 'u'],\n\t['Ử', 'U'],\n\t['ữ', 'u'],\n\t['Ữ', 'U'],\n\t['ự', 'u'],\n\t['Ự', 'U'],\n\t['ỳ', 'y'],\n\t['Ỳ', 'Y'],\n\t['ỵ', 'y'],\n\t['Ỵ', 'Y'],\n\t['ỷ', 'y'],\n\t['Ỷ', 'Y'],\n\t['ỹ', 'y'],\n\t['Ỹ', 'Y'],\n\n\t// Arabic\n\t['ء', 'e'],\n\t['آ', 'a'],\n\t['أ', 'a'],\n\t['ؤ', 'w'],\n\t['إ', 'a'],\n\t['ئ', 'y'],\n\t['ا', 'a'],\n\t['ب', 'b'],\n\t['ة', 't'],\n\t['ت', 't'],\n\t['ث', 'th'],\n\t['ج', 'j'],\n\t['ح', 'h'],\n\t['خ', 'kh'],\n\t['د', 'd'],\n\t['ذ', 'dh'],\n\t['ر', 'r'],\n\t['ز', 'z'],\n\t['س', 's'],\n\t['ش', 'sh'],\n\t['ص', 's'],\n\t['ض', 'd'],\n\t['ط', 't'],\n\t['ظ', 'z'],\n\t['ع', 'e'],\n\t['غ', 'gh'],\n\t['ـ', '_'],\n\t['ف', 'f'],\n\t['ق', 'q'],\n\t['ك', 'k'],\n\t['ل', 'l'],\n\t['م', 'm'],\n\t['ن', 'n'],\n\t['ه', 'h'],\n\t['و', 'w'],\n\t['ى', 'a'],\n\t['ي', 'y'],\n\t['َ‎', 'a'],\n\t['ُ', 'u'],\n\t['ِ‎', 'i'],\n\t['٠', '0'],\n\t['١', '1'],\n\t['٢', '2'],\n\t['٣', '3'],\n\t['٤', '4'],\n\t['٥', '5'],\n\t['٦', '6'],\n\t['٧', '7'],\n\t['٨', '8'],\n\t['٩', '9'],\n\n\t// Persian / Farsi\n\t['چ', 'ch'],\n\t['ک', 'k'],\n\t['گ', 'g'],\n\t['پ', 'p'],\n\t['ژ', 'zh'],\n\t['ی', 'y'],\n\t['۰', '0'],\n\t['۱', '1'],\n\t['۲', '2'],\n\t['۳', '3'],\n\t['۴', '4'],\n\t['۵', '5'],\n\t['۶', '6'],\n\t['۷', '7'],\n\t['۸', '8'],\n\t['۹', '9'],\n\n\t// Pashto\n\t['ټ', 'p'],\n\t['ځ', 'z'],\n\t['څ', 'c'],\n\t['ډ', 'd'],\n\t['ﺫ', 'd'],\n\t['ﺭ', 'r'],\n\t['ړ', 'r'],\n\t['ﺯ', 'z'],\n\t['ږ', 'g'],\n\t['ښ', 'x'],\n\t['ګ', 'g'],\n\t['ڼ', 'n'],\n\t['ۀ', 'e'],\n\t['ې', 'e'],\n\t['ۍ', 'ai'],\n\n\t// Urdu\n\t['ٹ', 't'],\n\t['ڈ', 'd'],\n\t['ڑ', 'r'],\n\t['ں', 'n'],\n\t['ہ', 'h'],\n\t['ھ', 'h'],\n\t['ے', 'e'],\n\n\t// Russian\n\t['А', 'A'],\n\t['а', 'a'],\n\t['Б', 'B'],\n\t['б', 'b'],\n\t['В', 'V'],\n\t['в', 'v'],\n\t['Г', 'G'],\n\t['г', 'g'],\n\t['Д', 'D'],\n\t['д', 'd'],\n\t['ъе', 'ye'],\n\t['Ъе', 'Ye'],\n\t['ъЕ', 'yE'],\n\t['ЪЕ', 'YE'],\n\t['Е', 'E'],\n\t['е', 'e'],\n\t['Ё', 'Yo'],\n\t['ё', 'yo'],\n\t['Ж', 'Zh'],\n\t['ж', 'zh'],\n\t['З', 'Z'],\n\t['з', 'z'],\n\t['И', 'I'],\n\t['и', 'i'],\n\t['ый', 'iy'],\n\t['Ый', 'Iy'],\n\t['ЫЙ', 'IY'],\n\t['ыЙ', 'iY'],\n\t['Й', 'Y'],\n\t['й', 'y'],\n\t['К', 'K'],\n\t['к', 'k'],\n\t['Л', 'L'],\n\t['л', 'l'],\n\t['М', 'M'],\n\t['м', 'm'],\n\t['Н', 'N'],\n\t['н', 'n'],\n\t['О', 'O'],\n\t['о', 'o'],\n\t['П', 'P'],\n\t['п', 'p'],\n\t['Р', 'R'],\n\t['р', 'r'],\n\t['С', 'S'],\n\t['с', 's'],\n\t['Т', 'T'],\n\t['т', 't'],\n\t['У', 'U'],\n\t['у', 'u'],\n\t['Ф', 'F'],\n\t['ф', 'f'],\n\t['Х', 'Kh'],\n\t['х', 'kh'],\n\t['Ц', 'Ts'],\n\t['ц', 'ts'],\n\t['Ч', 'Ch'],\n\t['ч', 'ch'],\n\t['Ш', 'Sh'],\n\t['ш', 'sh'],\n\t['Щ', 'Sch'],\n\t['щ', 'sch'],\n\t['Ъ', ''],\n\t['ъ', ''],\n\t['Ы', 'Y'],\n\t['ы', 'y'],\n\t['Ь', ''],\n\t['ь', ''],\n\t['Э', 'E'],\n\t['э', 'e'],\n\t['Ю', 'Yu'],\n\t['ю', 'yu'],\n\t['Я', 'Ya'],\n\t['я', 'ya'],\n\n\t// Romanian\n\t['ă', 'a'],\n\t['Ă', 'A'],\n\t['ș', 's'],\n\t['Ș', 'S'],\n\t['ț', 't'],\n\t['Ț', 'T'],\n\t['ţ', 't'],\n\t['Ţ', 'T'],\n\n\t// Turkish\n\t['ş', 's'],\n\t['Ş', 'S'],\n\t['ç', 'c'],\n\t['Ç', 'C'],\n\t['ğ', 'g'],\n\t['Ğ', 'G'],\n\t['ı', 'i'],\n\t['İ', 'I'],\n\n\t// Armenian\n\t['ա', 'a'],\n\t['Ա', 'A'],\n\t['բ', 'b'],\n\t['Բ', 'B'],\n\t['գ', 'g'],\n\t['Գ', 'G'],\n\t['դ', 'd'],\n\t['Դ', 'D'],\n\t['ե', 'ye'],\n\t['Ե', 'Ye'],\n\t['զ', 'z'],\n\t['Զ', 'Z'],\n\t['է', 'e'],\n\t['Է', 'E'],\n\t['ը', 'y'],\n\t['Ը', 'Y'],\n\t['թ', 't'],\n\t['Թ', 'T'],\n\t['ժ', 'zh'],\n\t['Ժ', 'Zh'],\n\t['ի', 'i'],\n\t['Ի', 'I'],\n\t['լ', 'l'],\n\t['Լ', 'L'],\n\t['խ', 'kh'],\n\t['Խ', 'Kh'],\n\t['ծ', 'ts'],\n\t['Ծ', 'Ts'],\n\t['կ', 'k'],\n\t['Կ', 'K'],\n\t['հ', 'h'],\n\t['Հ', 'H'],\n\t['ձ', 'dz'],\n\t['Ձ', 'Dz'],\n\t['ղ', 'gh'],\n\t['Ղ', 'Gh'],\n\t['ճ', 'tch'],\n\t['Ճ', 'Tch'],\n\t['մ', 'm'],\n\t['Մ', 'M'],\n\t['յ', 'y'],\n\t['Յ', 'Y'],\n\t['ն', 'n'],\n\t['Ն', 'N'],\n\t['շ', 'sh'],\n\t['Շ', 'Sh'],\n\t// NOTE: Longer Armenian sequences must come before shorter ones\n\t['ու', 'u'],\n\t['ՈՒ', 'U'],\n\t['Ու', 'U'],\n\t['ո', 'vo'],\n\t['Ո', 'Vo'],\n\t['չ', 'ch'],\n\t['Չ', 'Ch'],\n\t['պ', 'p'],\n\t['Պ', 'P'],\n\t['ջ', 'j'],\n\t['Ջ', 'J'],\n\t['ռ', 'r'],\n\t['Ռ', 'R'],\n\t['ս', 's'],\n\t['Ս', 'S'],\n\t['վ', 'v'],\n\t['Վ', 'V'],\n\t['տ', 't'],\n\t['Տ', 'T'],\n\t['ր', 'r'],\n\t['Ր', 'R'],\n\t['ց', 'c'],\n\t['Ց', 'C'],\n\t['փ', 'p'],\n\t['Փ', 'P'],\n\t['ք', 'q'],\n\t['Ք', 'Q'],\n\t['օ', 'o'],\n\t['Օ', 'O'],\n\t['ֆ', 'f'],\n\t['Ֆ', 'F'],\n\t['և', 'yev'],\n\n\t// Georgian\n\t['ა', 'a'],\n\t['ბ', 'b'],\n\t['გ', 'g'],\n\t['დ', 'd'],\n\t['ე', 'e'],\n\t['ვ', 'v'],\n\t['ზ', 'z'],\n\t['თ', 't'],\n\t['ი', 'i'],\n\t['კ', 'k'],\n\t['ლ', 'l'],\n\t['მ', 'm'],\n\t['ნ', 'n'],\n\t['ო', 'o'],\n\t['პ', 'p'],\n\t['ჟ', 'zh'],\n\t['რ', 'r'],\n\t['ს', 's'],\n\t['ტ', 't'],\n\t['უ', 'u'],\n\t['ფ', 'ph'],\n\t['ქ', 'q'],\n\t['ღ', 'gh'],\n\t['ყ', 'k'],\n\t['შ', 'sh'],\n\t['ჩ', 'ch'],\n\t['ც', 'ts'],\n\t['ძ', 'dz'],\n\t['წ', 'ts'],\n\t['ჭ', 'tch'],\n\t['ხ', 'kh'],\n\t['ჯ', 'j'],\n\t['ჰ', 'h'],\n\n\t// Czech\n\t['č', 'c'],\n\t['ď', 'd'],\n\t['ě', 'e'],\n\t['ň', 'n'],\n\t['ř', 'r'],\n\t['š', 's'],\n\t['ť', 't'],\n\t['ů', 'u'],\n\t['ž', 'z'],\n\t['Č', 'C'],\n\t['Ď', 'D'],\n\t['Ě', 'E'],\n\t['Ň', 'N'],\n\t['Ř', 'R'],\n\t['Š', 'S'],\n\t['Ť', 'T'],\n\t['Ů', 'U'],\n\t['Ž', 'Z'],\n\n\t// Dhivehi\n\t['ހ', 'h'],\n\t['ށ', 'sh'],\n\t['ނ', 'n'],\n\t['ރ', 'r'],\n\t['ބ', 'b'],\n\t['ޅ', 'lh'],\n\t['ކ', 'k'],\n\t['އ', 'a'],\n\t['ވ', 'v'],\n\t['މ', 'm'],\n\t['ފ', 'f'],\n\t['ދ', 'dh'],\n\t['ތ', 'th'],\n\t['ލ', 'l'],\n\t['ގ', 'g'],\n\t['ޏ', 'gn'],\n\t['ސ', 's'],\n\t['ޑ', 'd'],\n\t['ޒ', 'z'],\n\t['ޓ', 't'],\n\t['ޔ', 'y'],\n\t['ޕ', 'p'],\n\t['ޖ', 'j'],\n\t['ޗ', 'ch'],\n\t['ޘ', 'tt'],\n\t['ޙ', 'hh'],\n\t['ޚ', 'kh'],\n\t['ޛ', 'th'],\n\t['ޜ', 'z'],\n\t['ޝ', 'sh'],\n\t['ޞ', 's'],\n\t['ޟ', 'd'],\n\t['ޠ', 't'],\n\t['ޡ', 'z'],\n\t['ޢ', 'a'],\n\t['ޣ', 'gh'],\n\t['ޤ', 'q'],\n\t['ޥ', 'w'],\n\t['ަ', 'a'],\n\t['ާ', 'aa'],\n\t['ި', 'i'],\n\t['ީ', 'ee'],\n\t['ު', 'u'],\n\t['ޫ', 'oo'],\n\t['ެ', 'e'],\n\t['ޭ', 'ey'],\n\t['ޮ', 'o'],\n\t['ޯ', 'oa'],\n\t['ް', ''],\n\n\t// Greek\n\t['α', 'a'],\n\t['β', 'v'],\n\t['γ', 'g'],\n\t['δ', 'd'],\n\t['ε', 'e'],\n\t['ζ', 'z'],\n\t['η', 'i'],\n\t['θ', 'th'],\n\t['ι', 'i'],\n\t['κ', 'k'],\n\t['λ', 'l'],\n\t['μ', 'm'],\n\t['ν', 'n'],\n\t['ξ', 'ks'],\n\t['ο', 'o'],\n\t['π', 'p'],\n\t['ρ', 'r'],\n\t['σ', 's'],\n\t['τ', 't'],\n\t['υ', 'y'],\n\t['φ', 'f'],\n\t['χ', 'x'],\n\t['ψ', 'ps'],\n\t['ω', 'o'],\n\t['ά', 'a'],\n\t['έ', 'e'],\n\t['ί', 'i'],\n\t['ό', 'o'],\n\t['ύ', 'y'],\n\t['ή', 'i'],\n\t['ώ', 'o'],\n\t['ς', 's'],\n\t['ϊ', 'i'],\n\t['ΰ', 'y'],\n\t['ϋ', 'y'],\n\t['ΐ', 'i'],\n\t['Α', 'A'],\n\t['Β', 'B'],\n\t['Γ', 'G'],\n\t['Δ', 'D'],\n\t['Ε', 'E'],\n\t['Ζ', 'Z'],\n\t['Η', 'I'],\n\t['Θ', 'TH'],\n\t['Ι', 'I'],\n\t['Κ', 'K'],\n\t['Λ', 'L'],\n\t['Μ', 'M'],\n\t['Ν', 'N'],\n\t['Ξ', 'KS'],\n\t['Ο', 'O'],\n\t['Π', 'P'],\n\t['Ρ', 'R'],\n\t['Σ', 'S'],\n\t['Τ', 'T'],\n\t['Υ', 'Y'],\n\t['Φ', 'F'],\n\t['Χ', 'X'],\n\t['Ψ', 'PS'],\n\t['Ω', 'O'],\n\t['Ά', 'A'],\n\t['Έ', 'E'],\n\t['Ί', 'I'],\n\t['Ό', 'O'],\n\t['Ύ', 'Y'],\n\t['Ή', 'I'],\n\t['Ώ', 'O'],\n\t['Ϊ', 'I'],\n\t['Ϋ', 'Y'],\n\n\t// Disabled as it conflicts with German and Latin.\n\t// Hungarian\n\t// ['ä', 'a'],\n\t// ['Ä', 'A'],\n\t// ['ö', 'o'],\n\t// ['Ö', 'O'],\n\t// ['ü', 'u'],\n\t// ['Ü', 'U'],\n\t// ['ű', 'u'],\n\t// ['Ű', 'U'],\n\n\t// Latvian\n\t['ā', 'a'],\n\t['ē', 'e'],\n\t['ģ', 'g'],\n\t['ī', 'i'],\n\t['ķ', 'k'],\n\t['ļ', 'l'],\n\t['ņ', 'n'],\n\t['ū', 'u'],\n\t['Ā', 'A'],\n\t['Ē', 'E'],\n\t['Ģ', 'G'],\n\t['Ī', 'I'],\n\t['Ķ', 'K'],\n\t['Ļ', 'L'],\n\t['Ņ', 'N'],\n\t['Ū', 'U'],\n\t['č', 'c'],\n\t['š', 's'],\n\t['ž', 'z'],\n\t['Č', 'C'],\n\t['Š', 'S'],\n\t['Ž', 'Z'],\n\n\t// Lithuanian\n\t['ą', 'a'],\n\t['č', 'c'],\n\t['ę', 'e'],\n\t['ė', 'e'],\n\t['į', 'i'],\n\t['š', 's'],\n\t['ų', 'u'],\n\t['ū', 'u'],\n\t['ž', 'z'],\n\t['Ą', 'A'],\n\t['Č', 'C'],\n\t['Ę', 'E'],\n\t['Ė', 'E'],\n\t['Į', 'I'],\n\t['Š', 'S'],\n\t['Ų', 'U'],\n\t['Ū', 'U'],\n\n\t// Macedonian\n\t['Ќ', 'Kj'],\n\t['ќ', 'kj'],\n\t['Љ', 'Lj'],\n\t['љ', 'lj'],\n\t['Њ', 'Nj'],\n\t['њ', 'nj'],\n\t['Тс', 'Ts'],\n\t['тс', 'ts'],\n\n\t// Polish\n\t['ą', 'a'],\n\t['ć', 'c'],\n\t['ę', 'e'],\n\t['ł', 'l'],\n\t['ń', 'n'],\n\t['ś', 's'],\n\t['ź', 'z'],\n\t['ż', 'z'],\n\t['Ą', 'A'],\n\t['Ć', 'C'],\n\t['Ę', 'E'],\n\t['Ł', 'L'],\n\t['Ń', 'N'],\n\t['Ś', 'S'],\n\t['Ź', 'Z'],\n\t['Ż', 'Z'],\n\n\t// Disabled as it conflicts with Vietnamese.\n\t// Serbian\n\t// ['љ', 'lj'],\n\t// ['њ', 'nj'],\n\t// ['Љ', 'Lj'],\n\t// ['Њ', 'Nj'],\n\t// ['đ', 'dj'],\n\t// ['Đ', 'Dj'],\n\t// ['ђ', 'dj'],\n\t// ['ј', 'j'],\n\t// ['ћ', 'c'],\n\t// ['џ', 'dz'],\n\t// ['Ђ', 'Dj'],\n\t// ['Ј', 'j'],\n\t// ['Ћ', 'C'],\n\t// ['Џ', 'Dz'],\n\n\t// Disabled as it conflicts with German and Latin.\n\t// Slovak\n\t// ['ä', 'a'],\n\t// ['Ä', 'A'],\n\t// ['ľ', 'l'],\n\t// ['ĺ', 'l'],\n\t// ['ŕ', 'r'],\n\t// ['Ľ', 'L'],\n\t// ['Ĺ', 'L'],\n\t// ['Ŕ', 'R'],\n\n\t// Disabled as it conflicts with German and Latin.\n\t// Swedish\n\t// ['å', 'o'],\n\t// ['Å', 'o'],\n\t// ['ä', 'a'],\n\t// ['Ä', 'A'],\n\t// ['ë', 'e'],\n\t// ['Ë', 'E'],\n\t// ['ö', 'o'],\n\t// ['Ö', 'O'],\n\n\t// Ukrainian\n\t['Є', 'Ye'],\n\t['І', 'I'],\n\t['Ї', 'Yi'],\n\t['Ґ', 'G'],\n\t['є', 'ye'],\n\t['і', 'i'],\n\t['ї', 'yi'],\n\t['ґ', 'g'],\n\n\t// Dutch\n\t['Ĳ', 'IJ'],\n\t['ĳ', 'ij'],\n\n\t// Danish\n\t// ['Æ', 'Ae'],\n\t// ['Ø', 'Oe'],\n\t// ['Å', 'Aa'],\n\t// ['æ', 'ae'],\n\t// ['ø', 'oe'],\n\t// ['å', 'aa']\n\n\t// Currencies\n\t['¢', 'c'],\n\t['¥', 'Y'],\n\t['߿', 'b'],\n\t['৳', 't'],\n\t['૱', 'Bo'],\n\t['฿', 'B'],\n\t['₠', 'CE'],\n\t['₡', 'C'],\n\t['₢', 'Cr'],\n\t['₣', 'F'],\n\t['₥', 'm'],\n\t['₦', 'N'],\n\t['₧', 'Pt'],\n\t['₨', 'Rs'],\n\t['₩', 'W'],\n\t['₫', 's'],\n\t['€', 'E'],\n\t['₭', 'K'],\n\t['₮', 'T'],\n\t['₯', 'Dp'],\n\t['₰', 'S'],\n\t['₱', 'P'],\n\t['₲', 'G'],\n\t['₳', 'A'],\n\t['₴', 'S'],\n\t['₵', 'C'],\n\t['₶', 'tt'],\n\t['₷', 'S'],\n\t['₸', 'T'],\n\t['₹', 'R'],\n\t['₺', 'L'],\n\t['₽', 'P'],\n\t['₿', 'B'],\n\t['﹩', '$'],\n\t['￠', 'c'],\n\t['￥', 'Y'],\n\t['￦', 'W'],\n\n\t// Latin\n\t['𝐀', 'A'],\n\t['𝐁', 'B'],\n\t['𝐂', 'C'],\n\t['𝐃', 'D'],\n\t['𝐄', 'E'],\n\t['𝐅', 'F'],\n\t['𝐆', 'G'],\n\t['𝐇', 'H'],\n\t['𝐈', 'I'],\n\t['𝐉', 'J'],\n\t['𝐊', 'K'],\n\t['𝐋', 'L'],\n\t['𝐌', 'M'],\n\t['𝐍', 'N'],\n\t['𝐎', 'O'],\n\t['𝐏', 'P'],\n\t['𝐐', 'Q'],\n\t['𝐑', 'R'],\n\t['𝐒', 'S'],\n\t['𝐓', 'T'],\n\t['𝐔', 'U'],\n\t['𝐕', 'V'],\n\t['𝐖', 'W'],\n\t['𝐗', 'X'],\n\t['𝐘', 'Y'],\n\t['𝐙', 'Z'],\n\t['𝐚', 'a'],\n\t['𝐛', 'b'],\n\t['𝐜', 'c'],\n\t['𝐝', 'd'],\n\t['𝐞', 'e'],\n\t['𝐟', 'f'],\n\t['𝐠', 'g'],\n\t['𝐡', 'h'],\n\t['𝐢', 'i'],\n\t['𝐣', 'j'],\n\t['𝐤', 'k'],\n\t['𝐥', 'l'],\n\t['𝐦', 'm'],\n\t['𝐧', 'n'],\n\t['𝐨', 'o'],\n\t['𝐩', 'p'],\n\t['𝐪', 'q'],\n\t['𝐫', 'r'],\n\t['𝐬', 's'],\n\t['𝐭', 't'],\n\t['𝐮', 'u'],\n\t['𝐯', 'v'],\n\t['𝐰', 'w'],\n\t['𝐱', 'x'],\n\t['𝐲', 'y'],\n\t['𝐳', 'z'],\n\t['𝐴', 'A'],\n\t['𝐵', 'B'],\n\t['𝐶', 'C'],\n\t['𝐷', 'D'],\n\t['𝐸', 'E'],\n\t['𝐹', 'F'],\n\t['𝐺', 'G'],\n\t['𝐻', 'H'],\n\t['𝐼', 'I'],\n\t['𝐽', 'J'],\n\t['𝐾', 'K'],\n\t['𝐿', 'L'],\n\t['𝑀', 'M'],\n\t['𝑁', 'N'],\n\t['𝑂', 'O'],\n\t['𝑃', 'P'],\n\t['𝑄', 'Q'],\n\t['𝑅', 'R'],\n\t['𝑆', 'S'],\n\t['𝑇', 'T'],\n\t['𝑈', 'U'],\n\t['𝑉', 'V'],\n\t['𝑊', 'W'],\n\t['𝑋', 'X'],\n\t['𝑌', 'Y'],\n\t['𝑍', 'Z'],\n\t['𝑎', 'a'],\n\t['𝑏', 'b'],\n\t['𝑐', 'c'],\n\t['𝑑', 'd'],\n\t['𝑒', 'e'],\n\t['𝑓', 'f'],\n\t['𝑔', 'g'],\n\t['𝑖', 'i'],\n\t['𝑗', 'j'],\n\t['𝑘', 'k'],\n\t['𝑙', 'l'],\n\t['𝑚', 'm'],\n\t['𝑛', 'n'],\n\t['𝑜', 'o'],\n\t['𝑝', 'p'],\n\t['𝑞', 'q'],\n\t['𝑟', 'r'],\n\t['𝑠', 's'],\n\t['𝑡', 't'],\n\t['𝑢', 'u'],\n\t['𝑣', 'v'],\n\t['𝑤', 'w'],\n\t['𝑥', 'x'],\n\t['𝑦', 'y'],\n\t['𝑧', 'z'],\n\t['𝑨', 'A'],\n\t['𝑩', 'B'],\n\t['𝑪', 'C'],\n\t['𝑫', 'D'],\n\t['𝑬', 'E'],\n\t['𝑭', 'F'],\n\t['𝑮', 'G'],\n\t['𝑯', 'H'],\n\t['𝑰', 'I'],\n\t['𝑱', 'J'],\n\t['𝑲', 'K'],\n\t['𝑳', 'L'],\n\t['𝑴', 'M'],\n\t['𝑵', 'N'],\n\t['𝑶', 'O'],\n\t['𝑷', 'P'],\n\t['𝑸', 'Q'],\n\t['𝑹', 'R'],\n\t['𝑺', 'S'],\n\t['𝑻', 'T'],\n\t['𝑼', 'U'],\n\t['𝑽', 'V'],\n\t['𝑾', 'W'],\n\t['𝑿', 'X'],\n\t['𝒀', 'Y'],\n\t['𝒁', 'Z'],\n\t['𝒂', 'a'],\n\t['𝒃', 'b'],\n\t['𝒄', 'c'],\n\t['𝒅', 'd'],\n\t['𝒆', 'e'],\n\t['𝒇', 'f'],\n\t['𝒈', 'g'],\n\t['𝒉', 'h'],\n\t['𝒊', 'i'],\n\t['𝒋', 'j'],\n\t['𝒌', 'k'],\n\t['𝒍', 'l'],\n\t['𝒎', 'm'],\n\t['𝒏', 'n'],\n\t['𝒐', 'o'],\n\t['𝒑', 'p'],\n\t['𝒒', 'q'],\n\t['𝒓', 'r'],\n\t['𝒔', 's'],\n\t['𝒕', 't'],\n\t['𝒖', 'u'],\n\t['𝒗', 'v'],\n\t['𝒘', 'w'],\n\t['𝒙', 'x'],\n\t['𝒚', 'y'],\n\t['𝒛', 'z'],\n\t['𝒜', 'A'],\n\t['𝒞', 'C'],\n\t['𝒟', 'D'],\n\t['𝒢', 'g'],\n\t['𝒥', 'J'],\n\t['𝒦', 'K'],\n\t['𝒩', 'N'],\n\t['𝒪', 'O'],\n\t['𝒫', 'P'],\n\t['𝒬', 'Q'],\n\t['𝒮', 'S'],\n\t['𝒯', 'T'],\n\t['𝒰', 'U'],\n\t['𝒱', 'V'],\n\t['𝒲', 'W'],\n\t['𝒳', 'X'],\n\t['𝒴', 'Y'],\n\t['𝒵', 'Z'],\n\t['𝒶', 'a'],\n\t['𝒷', 'b'],\n\t['𝒸', 'c'],\n\t['𝒹', 'd'],\n\t['𝒻', 'f'],\n\t['𝒽', 'h'],\n\t['𝒾', 'i'],\n\t['𝒿', 'j'],\n\t['𝓀', 'k'],\n\t['𝓁', 'l'],\n\t['𝓂', 'm'],\n\t['𝓃', 'n'],\n\t['𝓅', 'p'],\n\t['𝓆', 'q'],\n\t['𝓇', 'r'],\n\t['𝓈', 's'],\n\t['𝓉', 't'],\n\t['𝓊', 'u'],\n\t['𝓋', 'v'],\n\t['𝓌', 'w'],\n\t['𝓍', 'x'],\n\t['𝓎', 'y'],\n\t['𝓏', 'z'],\n\t['𝓐', 'A'],\n\t['𝓑', 'B'],\n\t['𝓒', 'C'],\n\t['𝓓', 'D'],\n\t['𝓔', 'E'],\n\t['𝓕', 'F'],\n\t['𝓖', 'G'],\n\t['𝓗', 'H'],\n\t['𝓘', 'I'],\n\t['𝓙', 'J'],\n\t['𝓚', 'K'],\n\t['𝓛', 'L'],\n\t['𝓜', 'M'],\n\t['𝓝', 'N'],\n\t['𝓞', 'O'],\n\t['𝓟', 'P'],\n\t['𝓠', 'Q'],\n\t['𝓡', 'R'],\n\t['𝓢', 'S'],\n\t['𝓣', 'T'],\n\t['𝓤', 'U'],\n\t['𝓥', 'V'],\n\t['𝓦', 'W'],\n\t['𝓧', 'X'],\n\t['𝓨', 'Y'],\n\t['𝓩', 'Z'],\n\t['𝓪', 'a'],\n\t['𝓫', 'b'],\n\t['𝓬', 'c'],\n\t['𝓭', 'd'],\n\t['𝓮', 'e'],\n\t['𝓯', 'f'],\n\t['𝓰', 'g'],\n\t['𝓱', 'h'],\n\t['𝓲', 'i'],\n\t['𝓳', 'j'],\n\t['𝓴', 'k'],\n\t['𝓵', 'l'],\n\t['𝓶', 'm'],\n\t['𝓷', 'n'],\n\t['𝓸', 'o'],\n\t['𝓹', 'p'],\n\t['𝓺', 'q'],\n\t['𝓻', 'r'],\n\t['𝓼', 's'],\n\t['𝓽', 't'],\n\t['𝓾', 'u'],\n\t['𝓿', 'v'],\n\t['𝔀', 'w'],\n\t['𝔁', 'x'],\n\t['𝔂', 'y'],\n\t['𝔃', 'z'],\n\t['𝔄', 'A'],\n\t['𝔅', 'B'],\n\t['𝔇', 'D'],\n\t['𝔈', 'E'],\n\t['𝔉', 'F'],\n\t['𝔊', 'G'],\n\t['𝔍', 'J'],\n\t['𝔎', 'K'],\n\t['𝔏', 'L'],\n\t['𝔐', 'M'],\n\t['𝔑', 'N'],\n\t['𝔒', 'O'],\n\t['𝔓', 'P'],\n\t['𝔔', 'Q'],\n\t['𝔖', 'S'],\n\t['𝔗', 'T'],\n\t['𝔘', 'U'],\n\t['𝔙', 'V'],\n\t['𝔚', 'W'],\n\t['𝔛', 'X'],\n\t['𝔜', 'Y'],\n\t['𝔞', 'a'],\n\t['𝔟', 'b'],\n\t['𝔠', 'c'],\n\t['𝔡', 'd'],\n\t['𝔢', 'e'],\n\t['𝔣', 'f'],\n\t['𝔤', 'g'],\n\t['𝔥', 'h'],\n\t['𝔦', 'i'],\n\t['𝔧', 'j'],\n\t['𝔨', 'k'],\n\t['𝔩', 'l'],\n\t['𝔪', 'm'],\n\t['𝔫', 'n'],\n\t['𝔬', 'o'],\n\t['𝔭', 'p'],\n\t['𝔮', 'q'],\n\t['𝔯', 'r'],\n\t['𝔰', 's'],\n\t['𝔱', 't'],\n\t['𝔲', 'u'],\n\t['𝔳', 'v'],\n\t['𝔴', 'w'],\n\t['𝔵', 'x'],\n\t['𝔶', 'y'],\n\t['𝔷', 'z'],\n\t['𝔸', 'A'],\n\t['𝔹', 'B'],\n\t['𝔻', 'D'],\n\t['𝔼', 'E'],\n\t['𝔽', 'F'],\n\t['𝔾', 'G'],\n\t['𝕀', 'I'],\n\t['𝕁', 'J'],\n\t['𝕂', 'K'],\n\t['𝕃', 'L'],\n\t['𝕄', 'M'],\n\t['𝕆', 'O'],\n\t['𝕊', 'S'],\n\t['𝕋', 'T'],\n\t['𝕌', 'U'],\n\t['𝕍', 'V'],\n\t['𝕎', 'W'],\n\t['𝕏', 'X'],\n\t['𝕐', 'Y'],\n\t['𝕒', 'a'],\n\t['𝕓', 'b'],\n\t['𝕔', 'c'],\n\t['𝕕', 'd'],\n\t['𝕖', 'e'],\n\t['𝕗', 'f'],\n\t['𝕘', 'g'],\n\t['𝕙', 'h'],\n\t['𝕚', 'i'],\n\t['𝕛', 'j'],\n\t['𝕜', 'k'],\n\t['𝕝', 'l'],\n\t['𝕞', 'm'],\n\t['𝕟', 'n'],\n\t['𝕠', 'o'],\n\t['𝕡', 'p'],\n\t['𝕢', 'q'],\n\t['𝕣', 'r'],\n\t['𝕤', 's'],\n\t['𝕥', 't'],\n\t['𝕦', 'u'],\n\t['𝕧', 'v'],\n\t['𝕨', 'w'],\n\t['𝕩', 'x'],\n\t['𝕪', 'y'],\n\t['𝕫', 'z'],\n\t['𝕬', 'A'],\n\t['𝕭', 'B'],\n\t['𝕮', 'C'],\n\t['𝕯', 'D'],\n\t['𝕰', 'E'],\n\t['𝕱', 'F'],\n\t['𝕲', 'G'],\n\t['𝕳', 'H'],\n\t['𝕴', 'I'],\n\t['𝕵', 'J'],\n\t['𝕶', 'K'],\n\t['𝕷', 'L'],\n\t['𝕸', 'M'],\n\t['𝕹', 'N'],\n\t['𝕺', 'O'],\n\t['𝕻', 'P'],\n\t['𝕼', 'Q'],\n\t['𝕽', 'R'],\n\t['𝕾', 'S'],\n\t['𝕿', 'T'],\n\t['𝖀', 'U'],\n\t['𝖁', 'V'],\n\t['𝖂', 'W'],\n\t['𝖃', 'X'],\n\t['𝖄', 'Y'],\n\t['𝖅', 'Z'],\n\t['𝖆', 'a'],\n\t['𝖇', 'b'],\n\t['𝖈', 'c'],\n\t['𝖉', 'd'],\n\t['𝖊', 'e'],\n\t['𝖋', 'f'],\n\t['𝖌', 'g'],\n\t['𝖍', 'h'],\n\t['𝖎', 'i'],\n\t['𝖏', 'j'],\n\t['𝖐', 'k'],\n\t['𝖑', 'l'],\n\t['𝖒', 'm'],\n\t['𝖓', 'n'],\n\t['𝖔', 'o'],\n\t['𝖕', 'p'],\n\t['𝖖', 'q'],\n\t['𝖗', 'r'],\n\t['𝖘', 's'],\n\t['𝖙', 't'],\n\t['𝖚', 'u'],\n\t['𝖛', 'v'],\n\t['𝖜', 'w'],\n\t['𝖝', 'x'],\n\t['𝖞', 'y'],\n\t['𝖟', 'z'],\n\t['𝖠', 'A'],\n\t['𝖡', 'B'],\n\t['𝖢', 'C'],\n\t['𝖣', 'D'],\n\t['𝖤', 'E'],\n\t['𝖥', 'F'],\n\t['𝖦', 'G'],\n\t['𝖧', 'H'],\n\t['𝖨', 'I'],\n\t['𝖩', 'J'],\n\t['𝖪', 'K'],\n\t['𝖫', 'L'],\n\t['𝖬', 'M'],\n\t['𝖭', 'N'],\n\t['𝖮', 'O'],\n\t['𝖯', 'P'],\n\t['𝖰', 'Q'],\n\t['𝖱', 'R'],\n\t['𝖲', 'S'],\n\t['𝖳', 'T'],\n\t['𝖴', 'U'],\n\t['𝖵', 'V'],\n\t['𝖶', 'W'],\n\t['𝖷', 'X'],\n\t['𝖸', 'Y'],\n\t['𝖹', 'Z'],\n\t['𝖺', 'a'],\n\t['𝖻', 'b'],\n\t['𝖼', 'c'],\n\t['𝖽', 'd'],\n\t['𝖾', 'e'],\n\t['𝖿', 'f'],\n\t['𝗀', 'g'],\n\t['𝗁', 'h'],\n\t['𝗂', 'i'],\n\t['𝗃', 'j'],\n\t['𝗄', 'k'],\n\t['𝗅', 'l'],\n\t['𝗆', 'm'],\n\t['𝗇', 'n'],\n\t['𝗈', 'o'],\n\t['𝗉', 'p'],\n\t['𝗊', 'q'],\n\t['𝗋', 'r'],\n\t['𝗌', 's'],\n\t['𝗍', 't'],\n\t['𝗎', 'u'],\n\t['𝗏', 'v'],\n\t['𝗐', 'w'],\n\t['𝗑', 'x'],\n\t['𝗒', 'y'],\n\t['𝗓', 'z'],\n\t['𝗔', 'A'],\n\t['𝗕', 'B'],\n\t['𝗖', 'C'],\n\t['𝗗', 'D'],\n\t['𝗘', 'E'],\n\t['𝗙', 'F'],\n\t['𝗚', 'G'],\n\t['𝗛', 'H'],\n\t['𝗜', 'I'],\n\t['𝗝', 'J'],\n\t['𝗞', 'K'],\n\t['𝗟', 'L'],\n\t['𝗠', 'M'],\n\t['𝗡', 'N'],\n\t['𝗢', 'O'],\n\t['𝗣', 'P'],\n\t['𝗤', 'Q'],\n\t['𝗥', 'R'],\n\t['𝗦', 'S'],\n\t['𝗧', 'T'],\n\t['𝗨', 'U'],\n\t['𝗩', 'V'],\n\t['𝗪', 'W'],\n\t['𝗫', 'X'],\n\t['𝗬', 'Y'],\n\t['𝗭', 'Z'],\n\t['𝗮', 'a'],\n\t['𝗯', 'b'],\n\t['𝗰', 'c'],\n\t['𝗱', 'd'],\n\t['𝗲', 'e'],\n\t['𝗳', 'f'],\n\t['𝗴', 'g'],\n\t['𝗵', 'h'],\n\t['𝗶', 'i'],\n\t['𝗷', 'j'],\n\t['𝗸', 'k'],\n\t['𝗹', 'l'],\n\t['𝗺', 'm'],\n\t['𝗻', 'n'],\n\t['𝗼', 'o'],\n\t['𝗽', 'p'],\n\t['𝗾', 'q'],\n\t['𝗿', 'r'],\n\t['𝘀', 's'],\n\t['𝘁', 't'],\n\t['𝘂', 'u'],\n\t['𝘃', 'v'],\n\t['𝘄', 'w'],\n\t['𝘅', 'x'],\n\t['𝘆', 'y'],\n\t['𝘇', 'z'],\n\t['𝘈', 'A'],\n\t['𝘉', 'B'],\n\t['𝘊', 'C'],\n\t['𝘋', 'D'],\n\t['𝘌', 'E'],\n\t['𝘍', 'F'],\n\t['𝘎', 'G'],\n\t['𝘏', 'H'],\n\t['𝘐', 'I'],\n\t['𝘑', 'J'],\n\t['𝘒', 'K'],\n\t['𝘓', 'L'],\n\t['𝘔', 'M'],\n\t['𝘕', 'N'],\n\t['𝘖', 'O'],\n\t['𝘗', 'P'],\n\t['𝘘', 'Q'],\n\t['𝘙', 'R'],\n\t['𝘚', 'S'],\n\t['𝘛', 'T'],\n\t['𝘜', 'U'],\n\t['𝘝', 'V'],\n\t['𝘞', 'W'],\n\t['𝘟', 'X'],\n\t['𝘠', 'Y'],\n\t['𝘡', 'Z'],\n\t['𝘢', 'a'],\n\t['𝘣', 'b'],\n\t['𝘤', 'c'],\n\t['𝘥', 'd'],\n\t['𝘦', 'e'],\n\t['𝘧', 'f'],\n\t['𝘨', 'g'],\n\t['𝘩', 'h'],\n\t['𝘪', 'i'],\n\t['𝘫', 'j'],\n\t['𝘬', 'k'],\n\t['𝘭', 'l'],\n\t['𝘮', 'm'],\n\t['𝘯', 'n'],\n\t['𝘰', 'o'],\n\t['𝘱', 'p'],\n\t['𝘲', 'q'],\n\t['𝘳', 'r'],\n\t['𝘴', 's'],\n\t['𝘵', 't'],\n\t['𝘶', 'u'],\n\t['𝘷', 'v'],\n\t['𝘸', 'w'],\n\t['𝘹', 'x'],\n\t['𝘺', 'y'],\n\t['𝘻', 'z'],\n\t['𝘼', 'A'],\n\t['𝘽', 'B'],\n\t['𝘾', 'C'],\n\t['𝘿', 'D'],\n\t['𝙀', 'E'],\n\t['𝙁', 'F'],\n\t['𝙂', 'G'],\n\t['𝙃', 'H'],\n\t['𝙄', 'I'],\n\t['𝙅', 'J'],\n\t['𝙆', 'K'],\n\t['𝙇', 'L'],\n\t['𝙈', 'M'],\n\t['𝙉', 'N'],\n\t['𝙊', 'O'],\n\t['𝙋', 'P'],\n\t['𝙌', 'Q'],\n\t['𝙍', 'R'],\n\t['𝙎', 'S'],\n\t['𝙏', 'T'],\n\t['𝙐', 'U'],\n\t['𝙑', 'V'],\n\t['𝙒', 'W'],\n\t['𝙓', 'X'],\n\t['𝙔', 'Y'],\n\t['𝙕', 'Z'],\n\t['𝙖', 'a'],\n\t['𝙗', 'b'],\n\t['𝙘', 'c'],\n\t['𝙙', 'd'],\n\t['𝙚', 'e'],\n\t['𝙛', 'f'],\n\t['𝙜', 'g'],\n\t['𝙝', 'h'],\n\t['𝙞', 'i'],\n\t['𝙟', 'j'],\n\t['𝙠', 'k'],\n\t['𝙡', 'l'],\n\t['𝙢', 'm'],\n\t['𝙣', 'n'],\n\t['𝙤', 'o'],\n\t['𝙥', 'p'],\n\t['𝙦', 'q'],\n\t['𝙧', 'r'],\n\t['𝙨', 's'],\n\t['𝙩', 't'],\n\t['𝙪', 'u'],\n\t['𝙫', 'v'],\n\t['𝙬', 'w'],\n\t['𝙭', 'x'],\n\t['𝙮', 'y'],\n\t['𝙯', 'z'],\n\t['𝙰', 'A'],\n\t['𝙱', 'B'],\n\t['𝙲', 'C'],\n\t['𝙳', 'D'],\n\t['𝙴', 'E'],\n\t['𝙵', 'F'],\n\t['𝙶', 'G'],\n\t['𝙷', 'H'],\n\t['𝙸', 'I'],\n\t['𝙹', 'J'],\n\t['𝙺', 'K'],\n\t['𝙻', 'L'],\n\t['𝙼', 'M'],\n\t['𝙽', 'N'],\n\t['𝙾', 'O'],\n\t['𝙿', 'P'],\n\t['𝚀', 'Q'],\n\t['𝚁', 'R'],\n\t['𝚂', 'S'],\n\t['𝚃', 'T'],\n\t['𝚄', 'U'],\n\t['𝚅', 'V'],\n\t['𝚆', 'W'],\n\t['𝚇', 'X'],\n\t['𝚈', 'Y'],\n\t['𝚉', 'Z'],\n\t['𝚊', 'a'],\n\t['𝚋', 'b'],\n\t['𝚌', 'c'],\n\t['𝚍', 'd'],\n\t['𝚎', 'e'],\n\t['𝚏', 'f'],\n\t['𝚐', 'g'],\n\t['𝚑', 'h'],\n\t['𝚒', 'i'],\n\t['𝚓', 'j'],\n\t['𝚔', 'k'],\n\t['𝚕', 'l'],\n\t['𝚖', 'm'],\n\t['𝚗', 'n'],\n\t['𝚘', 'o'],\n\t['𝚙', 'p'],\n\t['𝚚', 'q'],\n\t['𝚛', 'r'],\n\t['𝚜', 's'],\n\t['𝚝', 't'],\n\t['𝚞', 'u'],\n\t['𝚟', 'v'],\n\t['𝚠', 'w'],\n\t['𝚡', 'x'],\n\t['𝚢', 'y'],\n\t['𝚣', 'z'],\n\n\t// Dotless letters\n\t['𝚤', 'l'],\n\t['𝚥', 'j'],\n\n\t// Greek\n\t['𝛢', 'A'],\n\t['𝛣', 'B'],\n\t['𝛤', 'G'],\n\t['𝛥', 'D'],\n\t['𝛦', 'E'],\n\t['𝛧', 'Z'],\n\t['𝛨', 'I'],\n\t['𝛩', 'TH'],\n\t['𝛪', 'I'],\n\t['𝛫', 'K'],\n\t['𝛬', 'L'],\n\t['𝛭', 'M'],\n\t['𝛮', 'N'],\n\t['𝛯', 'KS'],\n\t['𝛰', 'O'],\n\t['𝛱', 'P'],\n\t['𝛲', 'R'],\n\t['𝛳', 'TH'],\n\t['𝛴', 'S'],\n\t['𝛵', 'T'],\n\t['𝛶', 'Y'],\n\t['𝛷', 'F'],\n\t['𝛸', 'x'],\n\t['𝛹', 'PS'],\n\t['𝛺', 'O'],\n\t['𝛻', 'D'],\n\t['𝛼', 'a'],\n\t['𝛽', 'b'],\n\t['𝛾', 'g'],\n\t['𝛿', 'd'],\n\t['𝜀', 'e'],\n\t['𝜁', 'z'],\n\t['𝜂', 'i'],\n\t['𝜃', 'th'],\n\t['𝜄', 'i'],\n\t['𝜅', 'k'],\n\t['𝜆', 'l'],\n\t['𝜇', 'm'],\n\t['𝜈', 'n'],\n\t['𝜉', 'ks'],\n\t['𝜊', 'o'],\n\t['𝜋', 'p'],\n\t['𝜌', 'r'],\n\t['𝜍', 's'],\n\t['𝜎', 's'],\n\t['𝜏', 't'],\n\t['𝜐', 'y'],\n\t['𝜑', 'f'],\n\t['𝜒', 'x'],\n\t['𝜓', 'ps'],\n\t['𝜔', 'o'],\n\t['𝜕', 'd'],\n\t['𝜖', 'E'],\n\t['𝜗', 'TH'],\n\t['𝜘', 'K'],\n\t['𝜙', 'f'],\n\t['𝜚', 'r'],\n\t['𝜛', 'p'],\n\t['𝜜', 'A'],\n\t['𝜝', 'V'],\n\t['𝜞', 'G'],\n\t['𝜟', 'D'],\n\t['𝜠', 'E'],\n\t['𝜡', 'Z'],\n\t['𝜢', 'I'],\n\t['𝜣', 'TH'],\n\t['𝜤', 'I'],\n\t['𝜥', 'K'],\n\t['𝜦', 'L'],\n\t['𝜧', 'M'],\n\t['𝜨', 'N'],\n\t['𝜩', 'KS'],\n\t['𝜪', 'O'],\n\t['𝜫', 'P'],\n\t['𝜬', 'S'],\n\t['𝜭', 'TH'],\n\t['𝜮', 'S'],\n\t['𝜯', 'T'],\n\t['𝜰', 'Y'],\n\t['𝜱', 'F'],\n\t['𝜲', 'X'],\n\t['𝜳', 'PS'],\n\t['𝜴', 'O'],\n\t['𝜵', 'D'],\n\t['𝜶', 'a'],\n\t['𝜷', 'v'],\n\t['𝜸', 'g'],\n\t['𝜹', 'd'],\n\t['𝜺', 'e'],\n\t['𝜻', 'z'],\n\t['𝜼', 'i'],\n\t['𝜽', 'th'],\n\t['𝜾', 'i'],\n\t['𝜿', 'k'],\n\t['𝝀', 'l'],\n\t['𝝁', 'm'],\n\t['𝝂', 'n'],\n\t['𝝃', 'ks'],\n\t['𝝄', 'o'],\n\t['𝝅', 'p'],\n\t['𝝆', 'r'],\n\t['𝝇', 's'],\n\t['𝝈', 's'],\n\t['𝝉', 't'],\n\t['𝝊', 'y'],\n\t['𝝋', 'f'],\n\t['𝝌', 'x'],\n\t['𝝍', 'ps'],\n\t['𝝎', 'o'],\n\t['𝝏', 'a'],\n\t['𝝐', 'e'],\n\t['𝝑', 'i'],\n\t['𝝒', 'k'],\n\t['𝝓', 'f'],\n\t['𝝔', 'r'],\n\t['𝝕', 'p'],\n\t['𝝖', 'A'],\n\t['𝝗', 'B'],\n\t['𝝘', 'G'],\n\t['𝝙', 'D'],\n\t['𝝚', 'E'],\n\t['𝝛', 'Z'],\n\t['𝝜', 'I'],\n\t['𝝝', 'TH'],\n\t['𝝞', 'I'],\n\t['𝝟', 'K'],\n\t['𝝠', 'L'],\n\t['𝝡', 'M'],\n\t['𝝢', 'N'],\n\t['𝝣', 'KS'],\n\t['𝝤', 'O'],\n\t['𝝥', 'P'],\n\t['𝝦', 'R'],\n\t['𝝧', 'TH'],\n\t['𝝨', 'S'],\n\t['𝝩', 'T'],\n\t['𝝪', 'Y'],\n\t['𝝫', 'F'],\n\t['𝝬', 'X'],\n\t['𝝭', 'PS'],\n\t['𝝮', 'O'],\n\t['𝝯', 'D'],\n\t['𝝰', 'a'],\n\t['𝝱', 'v'],\n\t['𝝲', 'g'],\n\t['𝝳', 'd'],\n\t['𝝴', 'e'],\n\t['𝝵', 'z'],\n\t['𝝶', 'i'],\n\t['𝝷', 'th'],\n\t['𝝸', 'i'],\n\t['𝝹', 'k'],\n\t['𝝺', 'l'],\n\t['𝝻', 'm'],\n\t['𝝼', 'n'],\n\t['𝝽', 'ks'],\n\t['𝝾', 'o'],\n\t['𝝿', 'p'],\n\t['𝞀', 'r'],\n\t['𝞁', 's'],\n\t['𝞂', 's'],\n\t['𝞃', 't'],\n\t['𝞄', 'y'],\n\t['𝞅', 'f'],\n\t['𝞆', 'x'],\n\t['𝞇', 'ps'],\n\t['𝞈', 'o'],\n\t['𝞉', 'a'],\n\t['𝞊', 'e'],\n\t['𝞋', 'i'],\n\t['𝞌', 'k'],\n\t['𝞍', 'f'],\n\t['𝞎', 'r'],\n\t['𝞏', 'p'],\n\t['𝞐', 'A'],\n\t['𝞑', 'V'],\n\t['𝞒', 'G'],\n\t['𝞓', 'D'],\n\t['𝞔', 'E'],\n\t['𝞕', 'Z'],\n\t['𝞖', 'I'],\n\t['𝞗', 'TH'],\n\t['𝞘', 'I'],\n\t['𝞙', 'K'],\n\t['𝞚', 'L'],\n\t['𝞛', 'M'],\n\t['𝞜', 'N'],\n\t['𝞝', 'KS'],\n\t['𝞞', 'O'],\n\t['𝞟', 'P'],\n\t['𝞠', 'S'],\n\t['𝞡', 'TH'],\n\t['𝞢', 'S'],\n\t['𝞣', 'T'],\n\t['𝞤', 'Y'],\n\t['𝞥', 'F'],\n\t['𝞦', 'X'],\n\t['𝞧', 'PS'],\n\t['𝞨', 'O'],\n\t['𝞩', 'D'],\n\t['𝞪', 'av'],\n\t['𝞫', 'g'],\n\t['𝞬', 'd'],\n\t['𝞭', 'e'],\n\t['𝞮', 'z'],\n\t['𝞯', 'i'],\n\t['𝞰', 'i'],\n\t['𝞱', 'th'],\n\t['𝞲', 'i'],\n\t['𝞳', 'k'],\n\t['𝞴', 'l'],\n\t['𝞵', 'm'],\n\t['𝞶', 'n'],\n\t['𝞷', 'ks'],\n\t['𝞸', 'o'],\n\t['𝞹', 'p'],\n\t['𝞺', 'r'],\n\t['𝞻', 's'],\n\t['𝞼', 's'],\n\t['𝞽', 't'],\n\t['𝞾', 'y'],\n\t['𝞿', 'f'],\n\t['𝟀', 'x'],\n\t['𝟁', 'ps'],\n\t['𝟂', 'o'],\n\t['𝟃', 'a'],\n\t['𝟄', 'e'],\n\t['𝟅', 'i'],\n\t['𝟆', 'k'],\n\t['𝟇', 'f'],\n\t['𝟈', 'r'],\n\t['𝟉', 'p'],\n\t['𝟊', 'F'],\n\t['𝟋', 'f'],\n\t['⒜', '(a)'],\n\t['⒝', '(b)'],\n\t['⒞', '(c)'],\n\t['⒟', '(d)'],\n\t['⒠', '(e)'],\n\t['⒡', '(f)'],\n\t['⒢', '(g)'],\n\t['⒣', '(h)'],\n\t['⒤', '(i)'],\n\t['⒥', '(j)'],\n\t['⒦', '(k)'],\n\t['⒧', '(l)'],\n\t['⒨', '(m)'],\n\t['⒩', '(n)'],\n\t['⒪', '(o)'],\n\t['⒫', '(p)'],\n\t['⒬', '(q)'],\n\t['⒭', '(r)'],\n\t['⒮', '(s)'],\n\t['⒯', '(t)'],\n\t['⒰', '(u)'],\n\t['⒱', '(v)'],\n\t['⒲', '(w)'],\n\t['⒳', '(x)'],\n\t['⒴', '(y)'],\n\t['⒵', '(z)'],\n\t['Ⓐ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t['𝟎', '0'],\n\t['𝟏', '1'],\n\t['𝟐', '2'],\n\t['𝟑', '3'],\n\t['𝟒', '4'],\n\t['𝟓', '5'],\n\t['𝟔', '6'],\n\t['𝟕', '7'],\n\t['𝟖', '8'],\n\t['𝟗', '9'],\n\t['𝟘', '0'],\n\t['𝟙', '1'],\n\t['𝟚', '2'],\n\t['𝟛', '3'],\n\t['𝟜', '4'],\n\t['𝟝', '5'],\n\t['𝟞', '6'],\n\t['𝟟', '7'],\n\t['𝟠', '8'],\n\t['𝟡', '9'],\n\t['𝟢', '0'],\n\t['𝟣', '1'],\n\t['𝟤', '2'],\n\t['𝟥', '3'],\n\t['𝟦', '4'],\n\t['𝟧', '5'],\n\t['𝟨', '6'],\n\t['𝟩', '7'],\n\t['𝟪', '8'],\n\t['𝟫', '9'],\n\t['𝟬', '0'],\n\t['𝟭', '1'],\n\t['𝟮', '2'],\n\t['𝟯', '3'],\n\t['𝟰', '4'],\n\t['𝟱', '5'],\n\t['𝟲', '6'],\n\t['𝟳', '7'],\n\t['𝟴', '8'],\n\t['𝟵', '9'],\n\t['𝟶', '0'],\n\t['𝟷', '1'],\n\t['𝟸', '2'],\n\t['𝟹', '3'],\n\t['𝟺', '4'],\n\t['𝟻', '5'],\n\t['𝟼', '6'],\n\t['𝟽', '7'],\n\t['𝟾', '8'],\n\t['𝟿', '9'],\n\t['①', '1'],\n\t['②', '2'],\n\t['③', '3'],\n\t['④', '4'],\n\t['⑤', '5'],\n\t['⑥', '6'],\n\t['⑦', '7'],\n\t['⑧', '8'],\n\t['⑨', '9'],\n\t['⑩', '10'],\n\t['⑪', '11'],\n\t['⑫', '12'],\n\t['⑬', '13'],\n\t['⑭', '14'],\n\t['⑮', '15'],\n\t['⑯', '16'],\n\t['⑰', '17'],\n\t['⑱', '18'],\n\t['⑲', '19'],\n\t['⑳', '20'],\n\t['⑴', '1'],\n\t['⑵', '2'],\n\t['⑶', '3'],\n\t['⑷', '4'],\n\t['⑸', '5'],\n\t['⑹', '6'],\n\t['⑺', '7'],\n\t['⑻', '8'],\n\t['⑼', '9'],\n\t['⑽', '10'],\n\t['⑾', '11'],\n\t['⑿', '12'],\n\t['⒀', '13'],\n\t['⒁', '14'],\n\t['⒂', '15'],\n\t['⒃', '16'],\n\t['⒄', '17'],\n\t['⒅', '18'],\n\t['⒆', '19'],\n\t['⒇', '20'],\n\t['⒈', '1.'],\n\t['⒉', '2.'],\n\t['⒊', '3.'],\n\t['⒋', '4.'],\n\t['⒌', '5.'],\n\t['⒍', '6.'],\n\t['⒎', '7.'],\n\t['⒏', '8.'],\n\t['⒐', '9.'],\n\t['⒑', '10.'],\n\t['⒒', '11.'],\n\t['⒓', '12.'],\n\t['⒔', '13.'],\n\t['⒕', '14.'],\n\t['⒖', '15.'],\n\t['⒗', '16.'],\n\t['⒘', '17.'],\n\t['⒙', '18.'],\n\t['⒚', '19.'],\n\t['⒛', '20.'],\n\t['⓪', '0'],\n\t['⓫', '11'],\n\t['⓬', '12'],\n\t['⓭', '13'],\n\t['⓮', '14'],\n\t['⓯', '15'],\n\t['⓰', '16'],\n\t['⓱', '17'],\n\t['⓲', '18'],\n\t['⓳', '19'],\n\t['⓴', '20'],\n\t['⓵', '1'],\n\t['⓶', '2'],\n\t['⓷', '3'],\n\t['⓸', '4'],\n\t['⓹', '5'],\n\t['⓺', '6'],\n\t['⓻', '7'],\n\t['⓼', '8'],\n\t['⓽', '9'],\n\t['⓾', '10'],\n\t['⓿', '0'],\n\n\t// Punctuation\n\t['🙰', '&'],\n\t['🙱', '&'],\n\t['🙲', '&'],\n\t['🙳', '&'],\n\t['🙴', '&'],\n\t['🙵', '&'],\n\t['🙶', '\"'],\n\t['🙷', '\"'],\n\t['🙸', '\"'],\n\t['‽', '?!'],\n\t['🙹', '?!'],\n\t['🙺', '?!'],\n\t['🙻', '?!'],\n\t['🙼', '/'],\n\t['🙽', '\\\\'],\n\n\t// Alchemy\n\t['🜇', 'AR'],\n\t['🜈', 'V'],\n\t['🜉', 'V'],\n\t['🜆', 'VR'],\n\t['🜅', 'VF'],\n\t['🜩', '2'],\n\t['🜪', '5'],\n\t['🝡', 'f'],\n\t['🝢', 'W'],\n\t['🝣', 'U'],\n\t['🝧', 'V'],\n\t['🝨', 'T'],\n\t['🝪', 'V'],\n\t['🝫', 'MB'],\n\t['🝬', 'VB'],\n\t['🝲', '3B'],\n\t['🝳', '3B'],\n\n\t// Emojis\n\t['💯', '100'],\n\t['🔙', 'BACK'],\n\t['🔚', 'END'],\n\t['🔛', 'ON!'],\n\t['🔜', 'SOON'],\n\t['🔝', 'TOP'],\n\t['🔞', '18'],\n\t['🔤', 'abc'],\n\t['🔠', 'ABCD'],\n\t['🔡', 'abcd'],\n\t['🔢', '1234'],\n\t['🔣', 'T&@%'],\n\t['#️⃣', '#'],\n\t['*️⃣', '*'],\n\t['0️⃣', '0'],\n\t['1️⃣', '1'],\n\t['2️⃣', '2'],\n\t['3️⃣', '3'],\n\t['4️⃣', '4'],\n\t['5️⃣', '5'],\n\t['6️⃣', '6'],\n\t['7️⃣', '7'],\n\t['8️⃣', '8'],\n\t['9️⃣', '9'],\n\t['🔟', '10'],\n\t['🅰️', 'A'],\n\t['🅱️', 'B'],\n\t['🆎', 'AB'],\n\t['🆑', 'CL'],\n\t['🅾️', 'O'],\n\t['🅿', 'P'],\n\t['🆘', 'SOS'],\n\t['🅲', 'C'],\n\t['🅳', 'D'],\n\t['🅴', 'E'],\n\t['🅵', 'F'],\n\t['🅶', 'G'],\n\t['🅷', 'H'],\n\t['🅸', 'I'],\n\t['🅹', 'J'],\n\t['🅺', 'K'],\n\t['🅻', 'L'],\n\t['🅼', 'M'],\n\t['🅽', 'N'],\n\t['🆀', 'Q'],\n\t['🆁', 'R'],\n\t['🆂', 'S'],\n\t['🆃', 'T'],\n\t['🆄', 'U'],\n\t['🆅', 'V'],\n\t['🆆', 'W'],\n\t['🆇', 'X'],\n\t['🆈', 'Y'],\n\t['🆉', 'Z'],\n\n\t// Dashes not covered by Dash_Punctuation category\n\t['−', '-'], // U+2212 Minus Sign (Mathematical Operators category)\n\t['⁓', '-'], // U+2053 Swung Dash (Other_Punctuation category)\n];\n\nconst builtinReplacements = new Map(replacements);\n\nexport default builtinReplacements;\n","/**\nLanguage-specific replacement rules.\n\nKeys are BCP-47 language tags (or their prefixes).\n\nValues are arrays of [from, to] replacement pairs.\n\nThese replacements take precedence over the default replacements when a matching locale is specified.\n*/\n\n// Shared Danish/Norwegian replacements\nconst danishNorwegianReplacements = [\n\t['æ', 'ae'],\n\t['Æ', 'Ae'],\n\t['ø', 'oe'],\n\t['Ø', 'Oe'],\n\t['å', 'aa'],\n\t['Å', 'Aa'],\n];\n\nconst localeReplacements = {\n\t// Swedish\n\tsv: [\n\t\t['ä', 'a'],\n\t\t['Ä', 'A'],\n\t\t['ö', 'o'],\n\t\t['Ö', 'O'],\n\t\t['å', 'a'],\n\t\t['Å', 'A'],\n\t],\n\n\t// Danish\n\tda: danishNorwegianReplacements,\n\n\t// Norwegian Bokmål\n\tnb: danishNorwegianReplacements,\n\n\t// German\n\tde: [\n\t\t['ä', 'ae'],\n\t\t['Ä', 'Ae'],\n\t\t['ö', 'oe'],\n\t\t['Ö', 'Oe'],\n\t\t['ü', 'ue'],\n\t\t['Ü', 'Ue'],\n\t\t['ß', 'ss'],\n\t\t['ẞ', 'Ss'],\n\t],\n\n\t// Turkish\n\ttr: [\n\t\t['â', 'a'],\n\t\t['Â', 'A'],\n\t\t['ö', 'o'],\n\t\t['Ö', 'O'],\n\t\t['ü', 'u'],\n\t\t['Ü', 'U'],\n\t],\n\n\t// Hungarian\n\thu: [\n\t\t['ű', 'u'],\n\t\t['Ű', 'U'],\n\t\t['ö', 'o'],\n\t\t['Ö', 'O'],\n\t\t['ü', 'u'],\n\t\t['Ü', 'U'],\n\t\t['á', 'a'],\n\t\t['Á', 'A'],\n\t\t['é', 'e'],\n\t\t['É', 'E'],\n\t\t['í', 'i'],\n\t\t['Í', 'I'],\n\t\t['ó', 'o'],\n\t\t['Ó', 'O'],\n\t\t['ú', 'u'],\n\t\t['Ú', 'U'],\n\t],\n\n\t// Serbian\n\tsr: [\n\t\t['ђ', 'dj'],\n\t\t['Ђ', 'Dj'],\n\t\t['џ', 'dz'],\n\t\t['Џ', 'Dz'],\n\t\t['љ', 'lj'],\n\t\t['Љ', 'Lj'],\n\t\t['њ', 'nj'],\n\t\t['Њ', 'Nj'],\n\t\t['ћ', 'c'],\n\t\t['Ћ', 'C'],\n\t\t['ч', 'ch'],\n\t\t['Ч', 'Ch'],\n\t\t['ш', 'sh'],\n\t\t['Ш', 'Sh'],\n\t\t['ж', 'zh'],\n\t\t['Ж', 'Zh'],\n\t],\n};\n\n// Convert all locale replacements to Maps at module load time\nfor (const locale of Object.keys(localeReplacements)) {\n\tlocaleReplacements[locale] = new Map(localeReplacements[locale]);\n}\n\nexport default localeReplacements;\n","import builtinReplacements from './replacements.js';\nimport localeReplacements from './locale-replacements.js';\n\n// TODO: Use Regex.escape when targeting Node.js 24.\nconst escapeRegex = string => string.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n\nconst buildReplacementPattern = replacements => {\n\t// Sort by key length descending so longer patterns match first (e.g., 'ու' before 'ո')\n\tconst sortedKeys = [...replacements.keys()].sort((a, b) => b.length - a.length);\n\treturn new RegExp(sortedKeys.map(key => escapeRegex(key)).join('|'), 'gu');\n};\n\n// Pre-compile the default pattern for performance\nconst defaultPattern = buildReplacementPattern(builtinReplacements);\n\n// Pre-compile locale patterns\nconst localeCache = new Map();\n\nfor (const [locale, localeMap] of Object.entries(localeReplacements)) {\n\tconst replacements = new Map(builtinReplacements);\n\tfor (const [key, value] of localeMap) {\n\t\treplacements.set(key, value);\n\t}\n\n\tlocaleCache.set(locale, {\n\t\treplacements,\n\t\tpattern: buildReplacementPattern(replacements),\n\t});\n}\n\nconst normalizeLocale = locale => {\n\tif (!locale) {\n\t\treturn;\n\t}\n\n\tconst normalizedLocale = locale.toLowerCase()\n\t\t// Norwegian (no) is an alias for Norwegian Bokmål (nb)\n\t\t.replace(/^no(-|$)/, 'nb$1');\n\n\tif (Object.hasOwn(localeReplacements, normalizedLocale)) {\n\t\treturn normalizedLocale;\n\t}\n\n\tconst prefix = normalizedLocale.split('-')[0];\n\tif (Object.hasOwn(localeReplacements, prefix)) {\n\t\treturn prefix;\n\t}\n};\n\nexport default function transliterate(string, options) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a string, got \\`${typeof string}\\``);\n\t}\n\n\toptions = {\n\t\tcustomReplacements: [],\n\t\t...options,\n\t};\n\n\tconst normalizedLocale = normalizeLocale(options.locale);\n\tconst customReplacements = [...options.customReplacements];\n\n\tlet replacements = builtinReplacements;\n\tlet pattern = defaultPattern;\n\n\tif (normalizedLocale) {\n\t\t({replacements, pattern} = localeCache.get(normalizedLocale));\n\t}\n\n\tstring = string.normalize();\n\n\t// Apply customReplacements separately (avoids expensive regex compilation)\n\tif (customReplacements.length > 0) {\n\t\t// Sort by key length descending so longer patterns match first\n\t\tcustomReplacements.sort((a, b) => b[0].length - a[0].length);\n\t\tfor (const [key, value] of customReplacements) {\n\t\t\tstring = string.replaceAll(key, value);\n\t\t}\n\t}\n\n\tstring = string.replace(pattern, match => replacements.get(match) ?? match);\n\tstring = string.normalize('NFD').replaceAll(/\\p{Diacritic}/gu, '').normalize();\n\n\t// Normalize all dash types to hyphen-minus\n\tstring = string.replaceAll(/\\p{Dash_Punctuation}/gu, '-');\n\n\treturn string;\n}\n","/**\n * Characters that can’t be used in a slug with the default `unicode` encoding: space, control,\n * delimiter, reserved and unwise characters.\n * @see https://stackoverflow.com/q/1547899\n */\nexport const UNSAFE_UNICODE_SLUG_CHARS_REGEX = /[\\p{Z}\\p{C}!\"#$%&'()*+,/:;<=>?@[\\\\\\]^`{|}]/u;\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 transliterate from '@sindresorhus/transliterate';\nimport { 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 { cmsConfig } from '$lib/services/config';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { InternalCmsConfig } from '$lib/types/private';\n */\n\n/**\n * Locales that are supported in the `locale` option of the transliteration library.\n * @see https://github.com/sindresorhus/transliterate/tree/main#locale\n */\nconst TRANSLITERATION_LOCALES = ['da', 'de', 'hu', 'nb', 'sr', 'sv', 'tr'];\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, 'gu'),\n  ascii: new RegExp(UNSAFE_ASCII_SLUG_CHARS_REGEX, 'g'),\n};\n\n/**\n * @type {Map<string, { consecutivePattern: RegExp, trimPattern: RegExp }>}\n */\nconst slugReplacementRegexCache = new Map();\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] BCP 47 language tag passed to the transliterate library when\n * `clean_accents` is enabled.\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      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    // @see https://www.npmjs.com/package/@sindresorhus/transliterate\n    slug = transliterate(slug.normalize('NFD'), {\n      locale: locale && TRANSLITERATION_LOCALES.includes(locale) ? locale : undefined,\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  /** @type {RegExp | undefined} */\n  let trimPattern;\n\n  // Consolidate consecutive replacement characters into a single one and trim them from ends\n  if (sanitizeReplacement) {\n    const escapedReplacement = escapeRegExp(sanitizeReplacement);\n\n    const cachedSlugRegexes = 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    }));\n\n    slug = slug.replace(cachedSlugRegexes.consecutivePattern, sanitizeReplacement);\n\n    // Trim replacement characters from the beginning and end\n    if (trimReplacement) {\n      ({ trimPattern } = cachedSlugRegexes);\n      slug = slug.replace(trimPattern, '');\n    }\n  }\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 replacement character the cut may leave at the end\n    if (trimPattern) {\n      slug = slug.replace(trimPattern, '');\n    }\n  }\n\n  if (lowercase) {\n    slug = slug.toLocaleLowerCase();\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, either while creating one with the parent\n * folder picker or while renaming one with the slug editor.\n * @param {object} args Arguments.\n * @param {string[]} args.takenNames Names of the folders already sharing the parent folder.\n * @param {string} args.name Name to check, as typed.\n * @returns {'empty' | 'invalid' | 'duplicate' | undefined} What stops the name from being used, or\n * `undefined` if it can be used.\n */\nexport const validateNewFolderName = ({ takenNames, name }) => {\n  const trimmedName = name.trim();\n\n  if (!trimmedName) {\n    return 'empty';\n  }\n\n  const folderName = getNewFolderName(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 slugification can leave nothing to name the folder with. The dot is\n  // looked for in the slugified name, which can start with one even when what was typed didn’t\n  if (!folderName || trimmedName.includes('/') || folderName.startsWith('.')) {\n    return 'invalid';\n  }\n\n  return takenNames.includes(folderName) ? 'duplicate' : undefined;\n};\n","import { isObject } from '@sveltia/utils/object';\n\nimport { cmsConfig } from '$lib/services/config/state';\n\n/**\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 * @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) => {\n  const options = config?.media_libraries?.[libraryName];\n\n  if (options !== undefined && options !== null) {\n    return options;\n  }\n\n  const { media_library: legacyOptions } = config ?? {};\n  const legacyName = legacyOptions?.name ?? cmsConfig.current?.media_library?.name;\n\n  return legacyOptions && legacyName === 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","import { cmsConfig } from '$lib/services/config';\nimport { mergeLibraryOptions } 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  const siteLibName = _cmsConfig?.media_library?.name ?? 'default';\n\n  /**\n   * Find the library’s options in the field configuration.\n   * @returns {Record<string, any> | false | undefined} Options, `false` if the library is\n   * explicitly disabled, or `undefined` if the field doesn’t configure the library.\n   */\n  const getFieldOptions = () => {\n    const opts = fieldConfig?.media_libraries?.[libraryName];\n\n    // `media_libraries` (including explicit `false` to disable)\n    if (opts !== undefined && opts !== null) {\n      return opts;\n    }\n\n    // `media_library` (legacy), which applies to the site-level library if it has no name\n    const fieldLib = fieldConfig?.media_library;\n\n    return fieldLib &&\n      siteLibName === libraryName &&\n      (fieldLib.name === libraryName || fieldLib.name === undefined)\n      ? fieldLib\n      : undefined;\n  };\n\n  /**\n   * Find the library’s options in the site configuration.\n   * @returns {Record<string, any> | false | undefined} Options, `false` if the library is\n   * explicitly disabled, or `undefined` if the site doesn’t configure the library.\n   */\n  const getSiteOptions = () => {\n    const opts = _cmsConfig?.media_libraries?.[libraryName];\n\n    // `media_libraries` (including explicit `false` to disable)\n    if (opts !== undefined && opts !== null) {\n      return opts;\n    }\n\n    // `media_library` (legacy)\n    return _cmsConfig?.media_library && siteLibName === libraryName\n      ? _cmsConfig.media_library\n      : undefined;\n  };\n\n  const siteOptions = getSiteOptions();\n  const fieldOptions = getFieldOptions();\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 at the end of a file name. JPEG files can also have\n * a `.jpe` or `.jfif` extension, and HEIC files a `.heif` extension, so those aliases are included.\n */\nexport const RASTER_IMAGE_EXTENSION_REGEX = /\\b(?: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'];\nexport const VECTOR_IMAGE_EXTENSION_REGEX = /\\b(?: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","/**\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 { 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 * 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.\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, 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, for the development server, which serves the app as source modules\n * rather than a built bundle: there’s no built chunk next to the script there, so the entry is\n * imported through Vite instead. Empty in a production build, where this is removed along with the\n * 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    ? {\n        // eslint-disable-next-line jsdoc/require-jsdoc\n        'react-dom': () => import('$lib/chunks/react-dom.js'),\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.\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 { 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 * 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.\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 * @returns {Promise<Blob>} Image blob.\n * @see https://github.com/jamsinclair/jSquash\n */\nexport const exportCanvasAsBlob = async (canvas, { format = 'webp', quality = 85 } = {}) => {\n  const type = `image/${format}`;\n\n  if (\n    !(await checkIfEncodingIsSupported(format)) &&\n    /** @type {string[]} */ (RASTER_IMAGE_CONVERSION_FORMATS).includes(format)\n  ) {\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';\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 * The pending decode jobs. Jobs are run one at a time: a decode blocks the worker anyway, and\n * running them serially means at most one photo’s pixels are held at once.\n * @type {Promise<any>}\n */\nlet queue = Promise.resolve();\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  const job = queue.then(async () => decodeBuffer(await blob.arrayBuffer()));\n\n  queue = job.catch(() => undefined);\n\n  return job;\n};\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 { 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.\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};\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 (\n  blob,\n  { format = 'png', quality = 85, width = undefined, height = undefined, fit = 'scale-down' } = {},\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  width ??= naturalWidth;\n  height ??= naturalHeight;\n\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 });\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 { 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 { sniffRasterImageFormat } from '$lib/services/utils/media/image/sniff';\nimport { optimizeSVG, transformImage } from '$lib/services/utils/media/image/transform';\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 * 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  if (!transformation) {\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 { gitConfigFiles } from '$lib/services/backends/git/shared/config';\nimport { slugify } from '$lib/services/common/slug';\nimport { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\nimport { createPath, getDirName, sanitizeFileName } 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 * @returns {string[]} Names.\n */\nexport const getTakenNames = ({ subfolders, fileNames, exclude = undefined }) => [\n  ...subfolders.map(({ name }) => name).filter((name) => name !== exclude),\n  ...fileNames,\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 * 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) => resolveAssetFolderPath(dirPath)?.folder.internalPath;\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  // 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 listSubfolders({ dirPath, paths: [...assets, ...configFiles].map(({ path }) => 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.\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\n  return slugificationEnabled ? slugify(folderName, { fallback: false }) : 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  const trimmedName = name.trim();\n\n  if (!trimmedName) {\n    return 'empty';\n  }\n\n  const folderName = formatSubfolderName(trimmedName);\n\n  // A name has to stay a single folder, a leading dot would hide the folder from most file\n  // listings, and sanitization can leave nothing to name the folder with\n  if (!folderName || trimmedName.includes('/') || folderName.startsWith('.')) {\n    return 'invalid';\n  }\n\n  // The files in a folder the CMS itself is usually served from are read-only\n  if (isCmsFolderName(folderName)) {\n    return 'reserved';\n  }\n\n  const normalizedName = folderName.normalize().toLowerCase();\n\n  return takenNames.some((taken) => taken.normalize().toLowerCase() === normalizedName)\n    ? 'duplicate'\n    : undefined;\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 * 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') {\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 ?? { pattern: input };\n\n    if (pattern) {\n      try {\n        return new RegExp(pattern, flags?.replace(STATEFUL_FLAGS_REGEX, ''));\n      } catch {\n        // Ignore invalid regex\n      }\n    }\n  }\n\n  return undefined;\n};\n","import { _ } from '@sveltia/i18n';\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 * } & 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 * Sort an array of items using a key function and apply ascending/descending order.\n * @template T\n * @param {T[]} items Items to sort in place.\n * @param {(item: T) => string | number} getKey Returns the sort key for an item. Called once per\n * 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\n  keyedItems.sort(({ key: aKey }, { key: bKey }) =>\n    isStringType\n      ? compare(/** @type {string} */ (aKey), /** @type {string} */ (bKey))\n      : /** @type {number} */ (aKey) - /** @type {number} */ (bKey),\n  );\n\n  if (order === 'descending') {\n    keyedItems.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  keyedItems.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 a group is collapsed in the given view.\n * @param {ViewWithGroups} view View settings.\n * @param {string} name Group name.\n * @returns {boolean} Whether the group’s items are hidden.\n */\nexport const isGroupCollapsed = (view, name) => {\n  const key = getGroupingKey(view.group);\n\n  return key !== undefined && !!view.collapsedGroups?.[key]?.includes(name);\n};\n\n/**\n * Get the view settings with the collapsed groups of the current grouping condition replaced.\n * @template {ViewWithGroups} T\n * @param {T} view View settings.\n * @param {string[]} names Names of the collapsed groups. The condition is dropped from the saved\n * state when there is none, and so is the whole `collapsedGroups` property once it’s empty.\n * @returns {T} New view settings.\n */\nconst setCollapsedGroups = (view, names) => {\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 { [key]: _current, ...others } = view.collapsedGroups ?? {};\n  const collapsedGroups = names.length ? { ...others, [key]: names } : others;\n  const { collapsedGroups: _previous, ...rest } = view;\n\n  return /** @type {T} */ (\n    Object.keys(collapsedGroups).length ? { ...rest, collapsedGroups } : rest\n  );\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 * @returns {T} New view settings.\n */\nexport const setGroupCollapsed = (view, name, collapsed) => {\n  const key = getGroupingKey(view.group);\n  const current = key === undefined ? [] : (view.collapsedGroups?.[key] ?? []);\n  const names = current.filter((_name) => _name !== name);\n\n  if (collapsed) {\n    names.push(name);\n  }\n\n  return setCollapsedGroups(view, names);\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 * @returns {T} New view settings.\n */\nexport const setAllGroupsCollapsed = (view, names, collapsed) =>\n  setCollapsedGroups(view, collapsed ? [...names] : []);\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  const initial = { ...defaults, ...(await settingsDB?.get(storageKey)) };\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  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 { 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","/** @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","import { FIELD_TAG_PREFIX_REGEX } from '$lib/services/common/template/constants';\n\n/**\n * @import { InternalCollection } 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, which are only\n * there with the `multiple_files` i18n structure.\n * @param {InternalCollection} collection Collection. Its i18n configuration can be missing from a\n * partial collection object, which is then treated as not localized.\n * @returns {string[]} Locale codes.\n */\nexport const getFileNameLocaleSuffixes = ({ _i18n }) =>\n  _i18n?.structureMap?.i18nMultiFile ? _i18n.allLocales : [];\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 { INNER_TAG_REGEX } from '$lib/services/common/template/constants';\n\n/**\n * @import { StringTransformation } from '$lib/types/private';\n */\n\n/**\n * Resolve a single nested template value in transformation arguments.\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  if (!value.includes('{{')) {\n    return value;\n  }\n\n  const { innerTag } = value.match(INNER_TAG_REGEX)?.groups ?? {};\n\n  if (innerTag === undefined) {\n    return value;\n  }\n\n  /* v8 ignore next */\n  return String(resolveTag(innerTag) ?? '');\n};\n\n/**\n * Process nested template tags in transformation arguments (e.g., `default('{{fields.title}}')`).\n * This handles nested templates in `default`, `ternary`, and other 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    return hasChanges ? { ...tf, args: newArgs } : tf;\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 { 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 { slugify } from '$lib/services/common/slug';\nimport { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\nimport { getOrCreateBounded } from '$lib/services/utils/cache';\n\n/**\n * @import { StringTransformation } from '$lib/types/private';\n * @import { DateTimeField, Field } 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\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 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  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.\n * @param {string} string The string to be split.\n * @returns {string[]} Trimmed segments.\n */\nconst splitTransformations = (string) => {\n  /** @type {string[]} */\n  const segments = [];\n  let segment = '';\n  let quoted = false;\n\n  [...string].forEach((char, index) => {\n    if (char === \"'\") {\n      if (!quoted && /[(,]\\s*$/.test(string.slice(0, index))) {\n        quoted = true;\n      } else if (quoted && /^\\s*[,)]/.test(string.slice(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 } = parseTransformation(tf);\n\n              return Object.freeze({ method, args: Object.freeze(args) });\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.\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 * @returns {string} The formatted date string if valid, otherwise an empty string.\n */\nexport const applyDateTransformation = (value, { format, timeZone }, fieldConfig) => {\n  const sValue = String(value);\n  const { dateOnly, utc } = parseDateTimeConfig(fieldConfig);\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 = (useUTC ? dayjs.utc : dayjs)(sValue);\n\n  if (date.isValid()) {\n    return date.format(format);\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 * 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.\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 } = transformation;\n\n  switch (method) {\n    case 'upper':\n      return applyUpperCaseTransformation(value);\n    case 'lower':\n      return applyLowerCaseTransformation(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      );\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    default:\n      return String(value);\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","!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}}}));","/**\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 * 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  date.toLocaleString(locale ?? undefined, DATE_TIME_FORMAT_OPTIONS);\n","import dayjs from 'dayjs';\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';\n\n/**\n * @import { DateTimeField } from '$lib/types/public';\n */\n\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 * 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 * @returns {dayjs.Dayjs} Parsed dayjs instance.\n */\nexport const parseWithFormatFallback = ({ value, format, parseAsUTC }) => {\n  const parse = getParser(parseAsUTC);\n  const parsed = parse(value, format);\n\n  return parsed.isValid() ? parsed : parse(value);\n};\n\n/**\n * Get a `Date` object given the current value.\n * @param {string | undefined} currentValue Value in the entry draft datastore.\n * @param {DateTimeField} fieldConfig Field configuration.\n * @returns {Date | undefined} Date or `undefined` if invalid.\n */\nexport const getDate = (currentValue, fieldConfig) => {\n  const { format, timeOnly, utc, outputUTC } = parseDateTimeConfig(fieldConfig);\n  // Parse the stored value as UTC when: `input_timezone` is 'utc', OR `output_utc` is `true`. With\n  // a custom format, the stored string carries no timezone info, so we must specify UTC explicitly\n  // — otherwise the browser’s local offset is applied and the epoch is wrong.\n  const parseAsUTC = utc || outputUTC;\n\n  if (!currentValue) {\n    return undefined;\n  }\n\n  /** @type {Date | undefined} */\n  let date;\n\n  // If a format is specified, use Day.js to parse\n  if (format) {\n    const parsed = parseWithFormatFallback({ value: currentValue, format, parseAsUTC });\n\n    if (parsed.isValid()) {\n      return parsed.toDate();\n    }\n\n    // eslint-disable-next-line no-console\n    console.error('Invalid Date', currentValue);\n\n    return undefined;\n  }\n\n  if (timeOnly) {\n    // Use the current date\n    date = new Date(`${new Date().toJSON().split('T')[0]}T${currentValue}`);\n  } else {\n    date = new Date(currentValue);\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 dayjs from 'dayjs';\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 { getDate, isValidDate, parseWithFormatFallback } from './parse.js';\n\n/**\n * @import { InternalLocaleCode } from '$lib/types/private';\n * @import { DateTimeField } from '$lib/types/public';\n */\n\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 * 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 parsed = parseWithFormatFallback({ value: currentValue, format, parseAsUTC: utc });\n\n    if (parsed.isValid()) {\n      return parsed.format(format);\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);\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    return getDisplayFormatter({\n      locale: canonicalLocale,\n      parts: 'date',\n      timeZone:\n        displayTimeZone ||\n        (utc || DATE_REGEX.test(currentValue) || TIME_SUFFIX_REGEX.test(currentValue)\n          ? 'UTC'\n          : undefined),\n    }).format(date);\n  }\n\n  return getDisplayFormatter({\n    locale: canonicalLocale,\n    parts: 'datetime',\n    timeZone: displayTimeZone,\n  }).format(date);\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","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 { getAssociatedCollections } from '$lib/services/contents/entry/collections';\nimport { getPropertyValue } from '$lib/services/contents/entry/values';\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  const value = getPropertyValue({\n    entry,\n    locale: collection._i18n.defaultLocale,\n    collectionName: collection.name,\n    key: field,\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    return items.some((item) => pattern.test(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.\n * @param {Entry} entry Entry.\n * @returns {InternalCollection[]} Collections.\n */\nexport const getListedCollections = (entry) =>\n  getAssociatedCollections(entry).filter((collection) =>\n    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 * }}\n */\nconst entriesByCollectionCache = {\n  entrySource: undefined,\n  folderSource: undefined,\n  buckets: undefined,\n  map: 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};\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  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  }\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 * 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 * 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';\n\n/**\n * @import { Entry, InternalEntryCollection } from '$lib/types/private';\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  // An entry collection storing all the entries in one file keeps them in the order of the array\n  if (isArrayFileCollection(collection)) {\n    return entries.toSorted((a, b) => (a.arrayIndex ?? 0) - (b.arrayIndex ?? 0));\n  }\n\n  const orderKey = getOrderFieldKey(collection);\n\n  if (!orderKey) {\n    return [...entries];\n  }\n\n  const { defaultLocale } = collection._i18n;\n\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) => {\n    const raw = entry.locales[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 { entry, v, has: Number.isFinite(v) };\n  });\n\n  keyed.sort((a, b) => {\n    if (a.has && b.has) return a.v - b.v;\n    if (a.has) return -1;\n    if (b.has) 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 replacement value for a field name based on standard field types.\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 * @returns {string} The replacement value.\n */\nexport const getFieldReplacement = (fieldName, context, fallbackContext) => {\n  const { slug, locale, getDisplayValue } = context;\n  const { content, locales, defaultLocale, identifierField } = 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  return (\n    getDisplayValue(keyPath) ||\n    getDisplayValue(keyPath, defaultLocale) ||\n    getEntrySummaryFromContent(content, { identifierField }) ||\n    getEntrySummaryFromContent(locales[defaultLocale]?.content || {}, {\n      identifierField,\n    }) ||\n    slug\n  );\n};\n\n/**\n * Replace all template tags in the given strings with actual values.\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\n  fieldNames.forEach((fieldName) => {\n    const replacement = getFieldReplacement(fieldName, context, fallbackContext);\n\n    label = label.replaceAll(`{{${fieldName}}}`, () => replacement);\n    value = value.replaceAll(`{{${fieldName}}}`, () => replacement);\n    searchValue = searchValue?.replaceAll(`{{${fieldName}}}`, () => replacement) ?? '';\n  });\n\n  return { label, value, searchValue };\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   * @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 ?? [valueField ?? `{{${identifierField}}}`];\n  /**\n   * The format is the same as {@link displayFields}.\n   */\n  const searchFields = fieldConfig.search_fields ?? displayFields;\n  /**\n   * Canonical, templatized value field.\n   * @example '{{name.first}}'\n   * @example '{{route}}#{{sections.*.name}}'\n   */\n  const _valueField = normalizeFieldName(valueField ?? '{{slug}}');\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  const baseFieldGroups = 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  [...listFieldConfigs.entries()].forEach(([fieldName, config]) => {\n    const { baseFieldName } = config;\n\n    if (!baseFieldGroups.has(baseFieldName)) {\n      baseFieldGroups.set(baseFieldName, []);\n    }\n\n    baseFieldGroups.get(baseFieldName).push([fieldName, config]);\n  });\n\n  return baseFieldGroups;\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  return {\n    label: label || '',\n    value: value || context.slug,\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 { getEntrySummaryFromContent } from '$lib/services/contents/entry/summary';\nimport { getFieldReplacement } 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.\n */\nexport const createSimpleOption = ({ templates, allFieldNames, context, fallbackContext }) => {\n  const { slug } = context;\n  const { _displayField, _valueField, _searchField } = templates;\n  const { content, locales, defaultLocale, identifierField } = fallbackContext;\n\n  const replacers = Object.fromEntries(\n    allFieldNames.map((fieldName) => [\n      fieldName,\n      getFieldReplacement(fieldName, context, fallbackContext),\n    ]),\n  );\n\n  let label = _displayField;\n  let value = _valueField;\n  let searchValue = _searchField;\n\n  Object.entries(replacers).forEach(([key, val]) => {\n    label = label.replaceAll(`{{${key}}}`, () => val);\n    value = value.replaceAll(`{{${key}}}`, () => val);\n    searchValue = searchValue.replaceAll(`{{${key}}}`, () => val);\n  });\n\n  // Handle empty label fallback\n  if (!label || label.trim() === '') {\n    label =\n      getEntrySummaryFromContent(content, { identifierField }) ||\n      getEntrySummaryFromContent(locales[defaultLocale]?.content || {}, { identifierField }) ||\n      slug;\n  }\n\n  return {\n    label: label || '',\n    value: value || slug,\n    searchValue: searchValue || label || '',\n  };\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 * PendingEntry,\n * RelationOption,\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 * 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 {PendingEntry[]} [params.pendingEntries] Entries created from a Relation field of the\n * draft being edited, which a Relation field of the entry can refer to before they are saved.\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 nested collection an entry’s slug is its path within the collection folder, ending with\n  // the file name shared by every entry. A reference to the entry leaves that name out, the same\n  // 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 [createSimpleOption({ templates, allFieldNames, context, fallbackContext })];\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 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 [\n    {\n      label: label || '',\n      value: value || slug,\n      searchValue: searchValue || label || '',\n    },\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 { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import { Entry, FlattenedEntryContent, InternalCollection } from '$lib/types/private';\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 * @returns {RelationFieldFilterOptions[]} Filters with template values resolved.\n */\nexport const resolveFilterValues = (filters, currentLocaleValues, currentSlug = undefined) =>\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      const resolved = currentLocaleValues\n        ? getFieldValue(currentLocaleValues, match[1])\n        : undefined;\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  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            : getFieldValue(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","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 { 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 { 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 * InternalLocaleCode,\n * PendingEntry,\n * RelationOption,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, RelationField, RelationFieldFilterOptions } from '$lib/types/public';\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 * Cache of the saved entries merged with the pending ones by {@link withPendingEntries}, keyed by\n * the saved entry list, then by the pending entry list. A nested Relation field resolves a label\n * for each entry its parent field references, and a new merged array on each call would give the\n * option cache a new key every time, building the whole option list again for every label.\n * @type {WeakMap<Entry[], WeakMap<PendingEntry[], { count: number, entries: Entry[] }>>}\n */\nconst mergedEntriesCache = new WeakMap();\n\n/**\n * Add the entries pending on the draft being edited that belong to the given collection to the\n * given saved entries, so a reference to one of them resolves before they are saved. The saved\n * entries are returned as they are when there’s nothing to add, keeping their identity for the\n * option cache; 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 {PendingEntry[]} [pendingEntries] Pending entries of any 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 WeakMap();\n    mergedEntriesCache.set(entries, pendingCache);\n  }\n\n  const cached = pendingCache.get(pendingEntries);\n\n  // The pending entries are held in a reactive array that grows in place, so the count tells a\n  // change apart, as they are only ever added while the draft is edited\n  if (cached?.count === pendingEntries.length) {\n    return cached.entries;\n  }\n\n  const pending = pendingEntries\n    .filter((pendingEntry) => pendingEntry.collectionName === collectionName)\n    .map(({ entry }) => entry);\n\n  const merged = pending.length ? [...entries, ...pending] : entries;\n\n  pendingCache.set(pendingEntries, { count: pendingEntries.length, entries: merged });\n\n  return merged;\n};\n\n/**\n * Build the option list for a Relation field from the given referenced entries. This is the\n * 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 {PendingEntry[]} [args.pendingEntries] Entries created from a Relation field of the draft\n * being edited. A label template can refer to another Relation field of the referenced entry, and\n * the entry that one points at may be pending too.\n * @returns {RelationOption[]} Options, unsorted.\n */\nconst buildOptions = ({\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 { identifier_field: identifierField = 'title' } = _type === 'entry' ? collection : {};\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.flatMap(({ refEntry, content }) =>\n    processEntry({\n      refEntry,\n      content,\n      collection,\n      templates,\n      fileName,\n      locale,\n      identifierField,\n      pendingEntries,\n    }),\n  );\n};\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 {PendingEntry[]} [args.pendingEntries] Entries created from a Relation field of the draft\n * being edited, so the labels referring to one of them through another Relation field resolve.\n * @returns {RelationOption[]} Options, sorted by label unless the field references a file or a\n * 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}) => {\n  const { collection: collectionName, file: fileName, filters } = fieldConfig;\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(filters ?? [], currentLocaleValues, currentSlug);\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.\n  const resolvedKey = resolvedFilters.flatMap(({ values }) => values).join('\\x00');\n  const ids = `${getObjectId(fieldConfig)}|${getObjectId(refEntries)}`;\n  // The pending entries are held in a reactive array that grows in place, so its identity doesn’t\n  // tell them apart; the count does, as they are only ever added while the draft is edited\n  const cacheKey = `${locale}|${ids}|${pendingEntries?.length ?? 0}|${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        // The options taken from a list in a single file follow the order of the list items, and\n        // those from the entries of a collection the user can reorder follow the manual order;\n        // 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(refEntries, /** @type {any} */ (collection))\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 {PendingEntry[]} [args.pendingEntries] Entries created from a Relation field of the draft\n * being edited. See {@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 {PendingEntry[]} [args.pendingEntries] Entries created from a Relation field of the draft\n * being edited, which the value can refer to before they are saved.\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   * Get the label by value.\n   * @param {any} _value Stored value.\n   * @returns {string} Label.\n   */\n  const getLabel = (_value) => optionLabelMap.get(_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","import { sanitize } from 'isomorphic-dompurify';\nimport { Marked } from 'marked';\nimport { parseEntities } from 'parse-entities';\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 * 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 * @param {string} str Original string.\n * @returns {string} Plain text.\n */\nexport const stripMarkdown = (str) => {\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","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 { 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 { getOrCreate } from '$lib/services/utils/cache';\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 * PendingEntry,\n * StringTransformation,\n * } from '$lib/types/private';\n * @import {\n * DateTimeField,\n * Field,\n * FieldKeyPath,\n * ListFieldWithSubField,\n * ListFieldWithSubFields,\n * ListFieldWithTypes,\n * LocaleCode,\n * NumberField,\n * RelationField,\n * SelectField,\n * } from '$lib/types/public';\n */\n\n/**\n * Cache of {@link Intl.NumberFormat} instances for {@link getFieldDisplayValue}, keyed by canonical\n * locale.\n * @type {Map<LocaleCode | undefined, Intl.NumberFormat>}\n */\nconst numberFormatterCache = new Map();\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 {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 {PendingEntry[]} [args.pendingEntries] Entries created from a Relation field of the draft\n * being edited, which a Relation field value can refer to before they are saved.\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  valueMap = {},\n  keyPath,\n  locale,\n  transformations,\n  isIndexFile = false,\n  pendingEntries = undefined,\n  plainText = false,\n}) => {\n  const fieldConfig = getField({ collectionName, fileName, valueMap, keyPath, isIndexFile });\n  let value = valueMap[keyPath];\n\n  // If the field doesn’t exist in `valueMap` and transformations are applied, return empty string\n  if (value === undefined && transformations?.length) {\n    return '';\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 stripItems = plainText && isRichTextField(field);\n\n      // Concat values of single field list or simple list\n      value = getListFormatter(locale).format(\n        getListItemKeys(valueMap, keyPath)\n          .map((key) => valueMap[key])\n          .filter((val) => typeof val === 'string')\n          .map((val) => (stripItems ? stripMarkdown(val) : val))\n          .filter((val) => !!val),\n      );\n    }\n  }\n\n  if (fieldConfig?.widget === 'number') {\n    const { value_type: valueType = 'int' } = /** @type {NumberField} */ (fieldConfig);\n\n    // An empty field, stored as `null` or an empty string, or missing, is left empty rather than\n    // formatted as `0` or `NaN`\n    if (\n      (valueType === 'int' || valueType === 'float') &&\n      value !== null &&\n      value !== undefined &&\n      value !== ''\n    ) {\n      const canonicalLocale = getCanonicalLocale(locale);\n\n      const numberFormatter = getOrCreate(numberFormatterCache, canonicalLocale, () =>\n        Intl.NumberFormat(canonicalLocale),\n      );\n\n      value = numberFormatter.format(Number(value));\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: { name, login, email } = {}, commitDate } = entry;\n\n  if (key === 'slug') {\n    return slug;\n  }\n\n  if (key === 'commit_author') {\n    return name || login || email;\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  // 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    content[key] === 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 content[key];\n};\n","import { locale as appLocale } from '@sveltia/i18n';\nimport { getDateTimeParts } from '@sveltia/utils/datetime';\nimport { stripSlashes } from '@sveltia/utils/string';\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 { getField } from '$lib/services/contents/entry/fields';\nimport { getFieldDisplayValue } from '$lib/services/contents/entry/values';\nimport {\n  hasLocalePlaceholder,\n  stripLocaleFolderPath,\n} from '$lib/services/contents/i18n/placeholder';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import {\n * CommitAuthor,\n * Entry,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalLocaleCode,\n * } from '$lib/types/private';\n * @import { RawEntryContent } 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 {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 {ReplacerSubContext} replaceSubContext Context for the `replaceSub` function.\n * @property {InternalLocaleCode} defaultLocale Default locale.\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\nconst BODY_HEADER_REGEX = /^#+\\s+(?<header>.+?)(?:\\s+\\{#.+?\\})?\\s*$/m;\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 * @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));\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.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 content.body.match(BODY_HEADER_REGEX)?.groups?.header ?? '';\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 { slug, entryPath, basePath, locales, localeSuffixes, commitDate, commitAuthor } = 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    let dirPath = entryPath.replace(/[^/]+$/, '');\n\n    if (basePath && hasLocalePlaceholder(basePath)) {\n      // The base path stands for a folder per locale\n      dirPath = stripLocaleFolderPath(dirPath, basePath);\n    } else if (basePath) {\n      // Remove basePath prefix with boundary awareness\n      const prefix = basePath.endsWith('/') ? basePath : `${basePath}/`;\n\n      if (dirPath.startsWith(prefix)) {\n        dirPath = dirPath.slice(prefix.length);\n      } else if (dirPath.startsWith(basePath)) {\n        dirPath = dirPath.slice(basePath.length);\n      }\n    }\n\n    return stripSlashes(dirPath);\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 commitAuthor?.name || commitAuthor?.login || commitAuthor?.email;\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 * 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    replaceSubContext,\n    defaultLocale,\n    fallbackSummary,\n  } = context;\n\n  const { value: tag, transformations: parsedTransformations } = parseTransformations(placeholder);\n  const keyPath = stripFieldTagPrefix(tag);\n  const getFieldArgs = { collectionName, valueMap, keyPath };\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 = valueMap[keyPath];\n    } else {\n      // A Relation field is displayed with a label taken from the referenced entry\n      if (getField(getFieldArgs)?.widget === 'relation') {\n        relationLabelResolved = true;\n      }\n\n      value = getFieldDisplayValue({ ...getFieldArgs, locale: defaultLocale });\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: defaultLocale,\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 * 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 * @returns {string} Formatted entry summary.\n */\nconst formatEntrySummary = (\n  collection,\n  entry,\n  { locale, useTemplate = false, allowMarkdown = false, template } = {},\n) => {\n  if (isCollectionIndexFile(collection, entry)) {\n    return /** @type {string} */ (getIndexFile(collection)?.label);\n  }\n\n  const {\n    _type,\n    name: collectionName,\n    _i18n: { defaultLocale },\n  } = collection;\n\n  const {\n    _file: { basePath } = {},\n    identifier_field: identifierField = 'title',\n    summary: collectionSummaryTemplate,\n  } = _type === 'entry' ? collection : {};\n\n  const summaryTemplate = template ?? collectionSummaryTemplate;\n  const { locales, slug, commitDate, commitAuthor } = entry;\n\n  const { content = {}, path: entryPath = '' } =\n    locales[locale ?? defaultLocale] ?? Object.values(locales)[0] ?? {};\n\n  const fallbackSummary =\n    getEntrySummaryFromContent(content, { identifierField }) || 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    replaceSubContext: {\n      slug,\n      entryPath,\n      basePath,\n      locales: Object.keys(locales),\n      localeSuffixes: getFileNameLocaleSuffixes(collection),\n      commitDate,\n      commitAuthor,\n    },\n    defaultLocale,\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 a nested collection’s tree, which have their own\n * `nested.summary` option.\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 { locale, useTemplate = false, allowMarkdown = false, template } = 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    // `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","import { generateUUID } from '@sveltia/utils/crypto';\nimport { stripSlashes } from '@sveltia/utils/string';\n\nimport { DATE_TIME_FIELDS } 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 { getEntrySummaryFromContent } from '$lib/services/contents/entry/summary';\nimport {\n  hasLocalePlaceholder,\n  stripLocaleFolderPath,\n} from '$lib/services/contents/i18n/placeholder';\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  switch (tag) {\n    case 'uuid':\n      return generateUUID();\n    case 'uuid_short':\n      return generateUUID('short');\n    case 'uuid_shorter':\n      return generateUUID('shorter');\n    default:\n      return undefined;\n  }\n};\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 nested collection, an entry’s slug is its path within the collection folder, which ends\n  // with the file name shared by every entry, e.g. `guides/intro/_index`. That file name is an\n  // 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 * @returns {string | undefined} The file path value or undefined if not a file path tag.\n */\nexport const handleFilePathTag = (tag, entryFilePath, basePath, localeSuffixes = []) => {\n  if (!entryFilePath) {\n    return '';\n  }\n\n  switch (tag) {\n    case 'dirname': {\n      // The folder is relative to the collection folder, so it must not keep the slash left behind\n      // by the removed base path, or a template like `media/{{dirname}}` would produce `media//sub`\n      // A base path with the `{{locale}}` placeholder stands for a folder per locale\n      // @see https://github.com/decaporg/decap-cms/issues/7752\n      const pathAfterBase = stripSlashes(\n        basePath && hasLocalePlaceholder(basePath)\n          ? stripLocaleFolderPath(entryFilePath, basePath)\n          : entryFilePath.replace(basePath ?? '', ''),\n      );\n\n      const lastSlashIndex = pathAfterBase.lastIndexOf('/');\n\n      return lastSlashIndex > 0 ? pathAfterBase.substring(0, lastSlashIndex) : '';\n    }\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 { 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 */\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    content,\n    entryFilePath,\n    locale,\n    dateTimeParts,\n    basePath,\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\n  if (type === 'preview_path' || type === 'media_folder') {\n    const filePathValue = handleFilePathTag(\n      tag,\n      entryFilePath,\n      basePath,\n      getFileNameLocaleSuffixes(collection),\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  // Handle field values\n  return content[stripFieldTagPrefix(tag)];\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` transformation is defined\n  const hasDefaultTransformation = parsedTransformations.some(\n    (tf) => tf.args.defaultValue !== undefined,\n  );\n\n  const hasComplexNestedTemplateArgs = parsedTransformations.some((tf) =>\n    [tf.args.defaultValue, tf.args.truthyValue, tf.args.falsyValue].some(\n      (arg) => typeof arg === 'string' && arg.includes('{{') && !/^{{[^{}]+}}$/.test(arg),\n    ),\n  );\n\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.\n   * @throws {Error} If the template is a `preview_path`.\n   */\n  const bailOnUnresolvableTag = () => {\n    if (type === 'preview_path') {\n      throw new Error(`Unresolvable template tag in preview path: ${tag}`);\n    }\n  };\n\n  if (value === undefined && !hasDefaultTransformation) {\n    bailOnUnresolvableTag();\n\n    return getRandomValue(replaceSubContext, `${locale}:fallback:${placeholder}`, () =>\n      generateUUID('short'),\n    );\n  }\n\n  if (\n    (value === undefined || value === '') &&\n    hasDefaultTransformation &&\n    hasComplexNestedTemplateArgs\n  ) {\n    bailOnUnresolvableTag();\n\n    return getRandomValue(\n      replaceSubContext,\n      `${locale}:fallback:${placeholder}`,\n      () => `${generateUUID('short')}-${generateUUID('short')}`,\n    );\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  // 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 { getDateTimeParts } from '@sveltia/utils/datetime';\nimport { escapeRegExp, truncate } from '@sveltia/utils/string';\n\nimport { replaceTemplatePlaceholder } from '$lib/services/common/template/replacers';\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { cmsConfig } from '$lib/services/config';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { renameIfNeeded } from '$lib/services/utils/file';\n\n/**\n * @import { ReplaceContext } from '$lib/services/common/template/replacers';\n * @import { FillTemplateOptions } from '$lib/types/private';\n */\n\n/**\n * Creates existing slugs list for uniqueness validation.\n * @param {string} collectionName Collection name.\n * @param {string | undefined} locale Locale string.\n * @returns {string[]} List of existing slugs.\n */\nconst getExistingSlugs = (collectionName, locale) =>\n  getEntriesByCollection(collectionName)\n    .map((e) => (locale ? e.locales[locale]?.slug : e.slug))\n    .filter(Boolean);\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    content: valueMap,\n    currentSlug,\n    locale,\n    dateTimeParts,\n    isIndexFile = false,\n  } = options;\n\n  const { _type, name: collectionName } = collection;\n\n  const {\n    identifier_field: identifierField = 'title',\n    slug_length: legacySlugLength = undefined,\n    _file: { basePath } = {},\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  const timeZone = slugOptions?.timezone === 'local' ? undefined : 'UTC';\n\n  /** @type {ReplaceContext} */\n  const context = {\n    replaceSubContext: {\n      ...options,\n      dateTimeParts: dateTimeParts ?? getDateTimeParts({ timeZone }),\n      identifierField,\n      basePath,\n    },\n    getFieldArgs: { collectionName, keyPath: '', valueMap, isIndexFile },\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  // Truncate a long slug if needed, and remove the replacement character the cut may leave at the\n  // end, which is a hyphen by default but can be configured with `slug.sanitize_replacement`. Like\n  // `slugify`, leave the end alone if the slug isn’t cut or `slug.trim` is turned off, so a slug\n  // can still end with the replacement\n  if (typeof maxlength === 'number') {\n    const { sanitize_replacement: replacement = '-', trim = true } = slugOptions ?? {};\n    const truncated = truncate(slug, maxlength, { ellipsis: '' });\n\n    if (truncated !== slug && replacement && trim) {\n      slug = truncated.replace(new RegExp(`(?:${escapeRegExp(replacement)})+$`), '');\n    } else {\n      slug = truncated;\n    }\n  }\n\n  return renameIfNeeded(slug, getExistingSlugs(collectionName, locale));\n};\n","import { decodeFilePath, getPathInfo } from '@sveltia/utils/file';\nimport { escapeRegExp, stripSlashes } from '@sveltia/utils/string';\nimport { flatten } from 'flat';\n\nimport {\n  allAssetFolders,\n  getAssetFolder,\n  globalAssetFolder,\n  selectedAssetFolder,\n} from '$lib/services/assets/folders';\nimport { allAssets, focusedAsset } from '$lib/services/assets/state';\nimport { focusedSubfolder, selectedSubfolderPath } from '$lib/services/assets/subfolders';\nimport { fillTemplate } from '$lib/services/common/template';\nimport { ESCAPED_PLACEHOLDER_REGEX } from '$lib/services/common/template/constants';\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 { getCollectionFilesByEntry } from '$lib/services/contents/collection/files';\nimport { getAssociatedCollections } from '$lib/services/contents/entry/collections';\nimport { getOrCreate, memoizeOnSource } from '$lib/services/utils/cache';\nimport { createPath, getDirName, resolvePath, stripPathPrefix } from '$lib/services/utils/file';\nimport { createRootEffect } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * Entry,\n * InternalCollection,\n * InternalCollectionFile,\n * TypedFieldKeyPath,\n * } 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 */\nconst getAssetPathMap = memoizeOnSource(\n  () => allAssets.current,\n  (_allAssets) => new Map(_allAssets.map((asset) => [asset.path, asset])),\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 * 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 * @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 }) => {\n  if (!hasTemplateTags(internalPath)) {\n    return internalPath;\n  }\n\n  const collection = collectionName\n    ? getCollection(collectionName)\n    : entry\n      ? getAssociatedCollections(entry)[0]\n      : undefined;\n\n  if (!entry || !collection) {\n    // Cannot resolve the path\n    return undefined;\n  }\n\n  const { slug, locales } = entry;\n  const { defaultLocale } = collection._i18n;\n  const locale = defaultLocale in locales ? defaultLocale : Object.keys(locales)[0];\n  const { content, path: entryFilePath } = locales[locale];\n\n  return fillTemplate(internalPath, {\n    type: 'media_folder',\n    collection,\n    content: flatten(content),\n    currentSlug: slug,\n    entryFilePath,\n    isIndexFile: isCollectionIndexFile(collection, entry),\n  });\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 * @returns {Asset | undefined} Found asset.\n */\nexport const getAssetByRelativePathAndCollection = ({\n  path,\n  entry,\n  collection,\n  file,\n  componentName,\n  typedKeyPath,\n}) => {\n  const { locales } = entry;\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    : /** @type {string | undefined} */ (folderOptions.media_folder);\n\n  const publicFolder =\n    fieldFolder?.publicPath !== undefined\n      ? fieldFolder.publicPath\n      : /** @type {string | undefined} */ (folderOptions.public_folder);\n\n  const locale = defaultLocale in locales ? defaultLocale : Object.keys(locales)[0];\n  const { path: entryFilePath, content: entryContent } = locales[locale];\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 = fillTemplate(mediaFolder, {\n      type: 'media_folder',\n      collection,\n      content: entryContent,\n      currentSlug: entry.slug,\n      entryFilePath,\n      isIndexFile: isCollectionIndexFile(collection, entry),\n    });\n  }\n\n  // Directory of the entry file, which is an empty string for an entry file at the repository root\n  const entryFolder = getDirName(entryFilePath);\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  let resolvedPath;\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    resolvedPath = resolvePath(createPath([mediaFolder.slice(1), localPath]));\n  } else {\n    // Original logic: concatenate entryFolder + mediaFolder + localPath for entry-relative folders\n    resolvedPath = resolvePath(createPath([entryFolder, mediaFolder, localPath]));\n  }\n\n  return getAssetPathMap().get(resolvedPath);\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 * @returns {Asset | undefined} Corresponding asset.\n */\nexport const getAssetByRelativePath = ({\n  path,\n  entry,\n  collectionName,\n  fileName,\n  componentName,\n  typedKeyPath,\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 = /** @type {AssetFolderInfo[]} */ (\n      [\n        componentName ? getAssetFolder({ componentName, typedKeyPath }) : undefined,\n        collectionName && typedKeyPath\n          ? getAssetFolder({ collectionName, fileName, typedKeyPath })\n          : undefined,\n        collectionName ? getAssetFolder({ collectionName, fileName }) : undefined,\n        collectionName ? getAssetFolder({ collectionName }) : undefined,\n        globalAssetFolder.current,\n      ].filter((folder) => !!folder && !folder.hasTemplateTags)\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  // Stop at the first collection or collection file that has the asset\n  const foundAsset = getAssociatedCollections(entry)\n    .values()\n    .flatMap((collection) => {\n      const collectionFiles = getCollectionFilesByEntry(collection, entry);\n      const args = { path, entry, collection, componentName, typedKeyPath };\n      /** @type {(InternalCollectionFile | undefined)[]} */\n      const files = collectionFiles.length ? collectionFiles : [undefined];\n\n      return files.values().map((file) => getAssetByRelativePathAndCollection({ ...args, file }));\n    })\n    .find(Boolean);\n\n  return (\n    foundAsset ??\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 = escapeRegExp(publicPath).replace(ESCAPED_PLACEHOLDER_REGEX, '.+?');\n\n    return new RegExp(`^${normalizedPath}${publicPath ? '(?=\\\\/|$)' : '$'}`);\n  });\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 * @returns {Asset | undefined} Corresponding asset.\n */\nexport const getAssetByAbsolutePath = ({\n  path,\n  entry,\n  collectionName,\n  fileName,\n  componentName,\n  typedKeyPath,\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 (internalPath !== undefined) {\n      // Deal with template tags like `/assets/images/{{slug}}`\n      internalPath = fillInternalPathTemplate({\n        internalPath,\n        collectionName: _collectionName,\n        entry,\n      });\n\n      if (internalPath === undefined) {\n        // Cannot resolve the path\n        return undefined;\n      }\n    }\n\n    // Handle assets stored in a subfolder of the internal path\n    if (publicPath && internalPath && dirName) {\n      if (publicPath === '/') {\n        internalPath = `${internalPath}${dirName}`;\n      } else if (dirName.startsWith(`${publicPath}/`)) {\n        internalPath = dirName.replace(publicPath, internalPath);\n      }\n    }\n\n    return getAssetPathMap().get(createPath([internalPath, baseName]));\n  };\n\n  const scanningFolders = /** @type {AssetFolderInfo[]} */ (\n    [\n      componentName ? getAssetFolder({ componentName, typedKeyPath }) : undefined,\n      typedKeyPath ? getAssetFolder({ collectionName, fileName, typedKeyPath }) : undefined,\n      getAssetFolder({ collectionName, fileName }),\n      getAssetFolder({ collectionName }),\n      globalAssetFolder.current,\n    ].filter((folder) => !!folder)\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 * 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 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 * @returns {Asset | undefined} Corresponding asset.\n */\nexport const getAssetByPath = ({ value, ...rest }) => {\n  // Remove potential fragment before decoding\n  const path = decodeFilePath(value.split('#')[0]);\n\n  // Handle a relative path\n  if (isRelativePath(path)) {\n    return getAssetByRelativePath({ path, ...rest });\n  }\n\n  return getAssetByAbsolutePath({ path, ...rest });\n};\n\n/**\n * Check if an asset belongs to the given asset folder.\n * @param {Asset} asset Asset.\n * @param {AssetFolderInfo} folder Folder info.\n * @returns {boolean} Result.\n */\nexport const isAssetInFolder = ({ folder: assetFolder }, folder) =>\n  assetFolder === folder ||\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 * 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 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) =>\n  allAssets.current.filter((a) => getDirName(a.path) === dirname);\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 }) => name.normalize().toLowerCase()));\n\n  return files.filter((file) => existingNames.has(file.name.normalize().toLowerCase()));\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';\nimport { exportCanvasAsBlob } from '$lib/services/utils/media/image/encode';\nimport { resizeCanvas } from '$lib/services/utils/media/image/resize';\n\n/**\n * @import { InternalImageTransformationOptions } from '$lib/types/private';\n */\n\n/**\n * PDF.js distribution URL. We don’t bundle the library due to the large size and multiple files.\n * However, having it as a dependency in `package.json` allows us to include the latest version in\n * the UNPKG URL, making it faster to load the script without waiting for a redirect.\n * @see https://github.com/mozilla/pdf.js\n */\nconst PDFJS_DIST_URL = getUnpkgURL('pdfjs-dist');\nconst PDFJS_MODULE_URL = `${PDFJS_DIST_URL}/build/pdf.min.mjs`;\nconst PDFJS_WORKER_URL = `${PDFJS_DIST_URL}/build/pdf.worker.min.mjs`;\n\nconst PDFJS_GET_DOC_OPTIONS = {\n  isEvalSupported: false,\n  disableAutoFetch: true,\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 * 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 (\n  blob,\n  { format = 'png', quality = 85, width = undefined, height = undefined, fit = 'scale-down' } = {},\n) => {\n  // Lazily load the PDF.js library\n  if (!pdfjs) {\n    try {\n      pdfjs = await import(/* @vite-ignore */ PDFJS_MODULE_URL);\n      pdfjs.GlobalWorkerOptions.workerSrc = PDFJS_WORKER_URL;\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\n  /** @type {import('pdfjs-dist').PDFDocumentLoadingTask | undefined} */\n  let loadingTask;\n\n  try {\n    loadingTask = pdfjs.getDocument({ ...PDFJS_GET_DOC_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\n  return exportCanvasAsBlob(canvas, { format, quality });\n};\n","import { escapeRegExp } from '@sveltia/utils/string';\nimport mime from 'mime';\n\nimport { getAssetFoldersByPath, globalAssetFolder } from '$lib/services/assets/folders';\nimport { canCreateThumbnail, hasPDFThumbnail } 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 { getEntryFolderPath } from '$lib/services/contents/entry/paths';\nimport { shareInFlight } from '$lib/services/utils/cache';\nimport { getRepositoryDatabase } from '$lib/services/utils/database';\nimport { createPath, createPathRegEx, encodeFilePath, getDirName } 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';\n\n/**\n * @import { IndexedDB } from '@sveltia/utils/storage';\n * @import {\n * Asset,\n * AssetFolderInfo,\n * Entry,\n * InternalCmsConfig,\n * } from '$lib/types/private';\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/** @type {IndexedDB | null | undefined} */\nlet thumbnailDB = 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/* 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 _resetThumbnailDB = () => {\n  thumbnailDB = undefined;\n  pendingThumbnailBlobs.clear();\n};\n\n/**\n * Initialize {@link thumbnailDB} if it hasn’t been initialized yet.\n */\nconst initThumbnailDB = () => {\n  if (thumbnailDB === undefined) {\n    thumbnailDB = getRepositoryDatabase(backend.current?.repository, 'asset-thumbnails') ?? null;\n  }\n};\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 * @param {boolean} isPDF Whether the asset is a PDF file.\n * @returns {Promise<Blob | undefined>} Thumbnail blob.\n */\nconst resolveThumbnailBlob = async (asset, isPDF) => {\n  /** @type {Blob | undefined} */\n  let thumbnailBlob = await thumbnailDB?.get(asset.sha);\n\n  if (!thumbnailBlob) {\n    const blob = await getThumbnailSourceBlob(asset);\n    const transform = isPDF ? renderPDF : transformImage;\n\n    thumbnailBlob = await transform(blob, THUMBNAIL_TRANSFORM_OPTIONS);\n\n    await thumbnailDB?.set(asset.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  initThumbnailDB();\n\n  const pending = pendingThumbnailBlobs.get(sha);\n\n  if (pending) {\n    return !!(await pending.catch(() => undefined));\n  }\n\n  return !!(await thumbnailDB?.get(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  const isPDF = hasPDFThumbnail(asset.name);\n\n  initThumbnailDB();\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 thumbnailDB?.get(sha);\n\n    return cachedBlob ? URL.createObjectURL(cachedBlob) : undefined;\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, isPDF),\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/* 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};\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  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 path of the given asset in an entry-relative folder, relative to the entry’s folder.\n * @param {Asset} asset Asset.\n * @param {Entry} [entry] Associated entry. Can be `undefined` when editing a new draft.\n * @returns {string | undefined} Relative path, e.g. `images/photo.jpg`, or `undefined` if it\n * cannot be determined.\n */\nconst getEntryRelativePath = (asset, entry) => {\n  // A file at the repository root has no folder path\n  const assetFolderPath = getDirName(asset.path);\n  const entryFolderPath = entry ? getEntryFolderPath(entry) : 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 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 * @returns {string | undefined} URL or `undefined` if it cannot be determined.\n */\nexport const getAssetPublicURL = (\n  asset,\n  { pathOnly = false, allowSpecial = false, entry = undefined } = {},\n) => {\n  const { publicPath, entryRelative, hasTemplateTags } = resolvePublicFolder(asset);\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    return pathOnly ? getEntryRelativePath(asset, entry) : undefined;\n  }\n\n  const { _baseURL: baseURL = '', output: { encode_file_path: encodingEnabled = false } = {} } =\n    /** @type {InternalCmsConfig} */ (cmsConfig.current);\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 * 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\n/**\n * Percent-encode an object key for use in a URL path, keeping the path separators intact.\n * @param {string} key Object key.\n * @param {(segment: string) => string} [encodeSegment] Function to encode each path segment.\n * Default: `encodeURIComponent`.\n * @returns {string} Encoded key.\n */\nexport const encodeKey = (key, encodeSegment = encodeURIComponent) =>\n  key\n    .split('/')\n    .map((segment) => encodeSegment(segment))\n    .join('/');\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","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.\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 * @returns {Promise<T[]>} Results of all the fetched pages.\n */\nexport const fetchPages = async (fetchPage, { maxPages = 10 } = {}) => {\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 || page === maxPages) {\n      break;\n    }\n\n    cursor = next;\n\n    // Wait for a bit before requesting the next page\n    // eslint-disable-next-line no-await-in-loop\n    await sleep(50);\n  }\n\n  return results;\n};\n","/* eslint-disable no-await-in-loop */\n\nimport { sleep } from '@sveltia/utils/misc';\n\nimport { getAssetKind } from '$lib/services/assets/kinds';\nimport { filterAssetsByQuery } from '$lib/services/integrations/media-libraries/cloud/search';\nimport {\n  getFileKey,\n  getPrefix,\n  getRelativeKey,\n} from '$lib/services/integrations/media-libraries/cloud/shared/keys';\nimport { fetchPages } from '$lib/services/integrations/media-libraries/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 * 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: { config: C, credential: string, prefix: string, cursor?: string }) =>\n * Promise<{ items: T[], cursor?: string }>} listPage Function to fetch a page of objects under the\n * given prefix, starting at the given continuation cursor. The returned cursor is `undefined` on\n * 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: { key: string, config: C, credential: string }) => Promise<void>}\n * deleteObject Function to delete the object with the given key.\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\n/**\n * Fetch the objects under the configured prefix, 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.\n * @returns {Promise<{ files: T[], folders: string[] }>} Objects, split into the files and the\n * folder placeholders, the latter given as folder paths relative to the prefix.\n */\nexport const fetchListing = async (provider, config, options, { maxPages = 10 } = {}) => {\n  const credential = provider.requireCredential(options);\n  const prefix = getPrefix(config);\n  /** @type {T[]} */\n  const files = [];\n  /** @type {string[]} */\n  const folders = [];\n\n  const items = await fetchPages(\n    async (/** @type {string | undefined} */ cursor) => {\n      const result = await provider.listPage({ config, credential, prefix, 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 dirPath = getRelativeKey(config, key).replace(/\\/$/, '');\n\n      // The placeholder of the prefix itself isn’t a folder below it\n      if (dirPath) {\n        folders.push(dirPath);\n      }\n    } else {\n      files.push(item);\n    }\n  });\n\n  return { files, folders };\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 } = await fetchListing(provider, config, options);\n\n  return {\n    assets: provider.parseResults(filterByKind(provider, files, options), config, options.apiKey),\n    folders,\n  };\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 * Upload files one by one to the folder given in the fetch options.\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 */\nexport const uploadObjects = async (provider, files, config, options) => {\n  if (files.length === 0) {\n    return [];\n  }\n\n  const credential = provider.requireCredential(options);\n  const { dirPath = '' } = options;\n  /** @type {T[]} */\n  const uploadedObjects = [];\n\n  // eslint-disable-next-line no-restricted-syntax\n  for (const file of files) {\n    // Extract only the filename to prevent path traversal via crafted File objects\n    const sanitizedName = file.name.split(/[/\\\\]/).filter(Boolean).at(-1) ?? file.name;\n    const key = getFileKey(config, dirPath ? `${dirPath}/${sanitizedName}` : sanitizedName);\n\n    uploadedObjects.push(await provider.putObject({ key, 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 = provider.requireCredential(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 = provider.requireCredential(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 * 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 = getRelativeKey(config, asset.id).split('/').slice(0, -1).join('/');\n\n  return dirName ? `${dirName}/${newName}` : newName;\n};\n\n/**\n * Create the operations of an object storage service, binding the given provider to the shared\n * list, browse, search, upload, delete and replace operations. A file is renamed by moving it\n * within its folder.\n * @template T\n * @template {CloudStorageConfig} C\n * @param {ObjectStorageProvider<T, C>} provider Service provider.\n * @param {Pick<ObjectStorageOperations<C>, 'move' | 'createFolder' | 'deleteFolder'>} operations\n * Service-specific operations.\n * @returns {ObjectStorageOperations<C>} Operations.\n */\nexport const createObjectStorageOperations = (provider, { move, createFolder, deleteFolder }) => ({\n  /**\n   * List the files under the configured prefix.\n   * @param {C} config Service configuration.\n   * @param {MediaLibraryFetchOptions} options Fetch options.\n   * @returns {Promise<ExternalAsset[]>} Assets.\n   */\n  list: (config, options) => listObjects(provider, config, options),\n  /**\n   * List the files and the empty folders under the configured prefix.\n   * @param {C} config Service configuration.\n   * @param {MediaLibraryFetchOptions} options Fetch options.\n   * @returns {Promise<ExternalFolderListing>} Files and folders.\n   */\n  browse: (config, options) => browseObjects(provider, config, options),\n  /**\n   * Search the files under the configured prefix.\n   * @param {string} query Search query.\n   * @param {C} config Service configuration.\n   * @param {MediaLibraryFetchOptions} options Fetch options.\n   * @returns {Promise<ExternalAsset[]>} Assets.\n   */\n  search: (query, config, options) => searchObjects(provider, query, config, options),\n  /**\n   * Upload files to the folder given in the fetch options.\n   * @param {File[]} files Files to upload.\n   * @param {C} config Service configuration.\n   * @param {MediaLibraryFetchOptions} options Fetch options.\n   * @returns {Promise<ExternalAsset[]>} Uploaded assets.\n   */\n  upload: (files, config, options) => uploadObjects(provider, files, config, options),\n  /**\n   * Delete files.\n   * @param {ExternalAsset[]} assets Assets to delete.\n   * @param {C} config Service configuration.\n   * @param {MediaLibraryFetchOptions} options Fetch options.\n   * @returns {Promise<void>}\n   */\n  delete: (assets, config, options) => deleteObjects(provider, assets, config, options),\n  /**\n   * Rename a file, keeping it in its folder.\n   * @param {ExternalAsset} asset Asset to rename.\n   * @param {string} newName New file name, without a directory.\n   * @param {C} config Service configuration.\n   * @param {MediaLibraryFetchOptions} options Fetch options.\n   * @returns {Promise<ExternalAsset>} Renamed asset.\n   */\n  rename: (asset, newName, config, options) =>\n    move(asset, getRenamedPath(config, asset, newName), config, options),\n  /**\n   * Replace a file, keeping the object key so that the URL stays the same.\n   * @param {ExternalAsset} asset Asset to replace.\n   * @param {File} file New file.\n   * @param {C} config Service configuration.\n   * @param {MediaLibraryFetchOptions} options Fetch options.\n   * @returns {Promise<ExternalAsset>} Replaced asset.\n   */\n  replace: (asset, file, config, options) => replaceObject(provider, asset, file, config, options),\n  move,\n  createFolder,\n  deleteFolder,\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 {(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 Service label.\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 * 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.serviceLabel = 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 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 arrow functions rather than prototype methods,\n  // because consumers destructure them from the service object, which would 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   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<ExternalAsset[]>} Assets.\n   */\n  list = async (options) => this.operations.list(this.getConfig(options), options);\n\n  /**\n   * List the files and the empty folders on the service.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<ExternalFolderListing>} Files and folders.\n   */\n  browse = async (options) => this.operations.browse(this.getConfig(options), options);\n\n  /**\n   * Search files on the service.\n   * @param {string} query Search query.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<ExternalAsset[]>} Assets.\n   */\n  search = async (query, options) =>\n    this.operations.search(query, this.getConfig(options), options);\n\n  /**\n   * Upload files to the service.\n   * @param {File[]} files Files to upload.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<ExternalAsset[]>} Uploaded assets.\n   */\n  upload = async (files, options) =>\n    this.operations.upload(files, this.getConfig(options), options);\n\n  /**\n   * Delete files from the service.\n   * @param {ExternalAsset[]} assets Assets to delete.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<void>}\n   */\n  delete = async (assets, options) =>\n    this.operations.delete(assets, this.getConfig(options), options);\n\n  /**\n   * Rename a file on the service.\n   * @param {ExternalAsset} asset Asset to rename.\n   * @param {string} newName New file name.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<ExternalAsset>} Renamed asset.\n   */\n  rename = async (asset, newName, options) =>\n    this.operations.rename(asset, newName, this.getConfig(options), options);\n\n  /**\n   * Replace a file on the service with a new file.\n   * @param {ExternalAsset} asset Asset to replace.\n   * @param {File} file New file.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<ExternalAsset>} Replaced asset.\n   */\n  replace = async (asset, file, options) =>\n    this.operations.replace(asset, file, this.getConfig(options), options);\n\n  /**\n   * Move a file on the service to another path.\n   * @param {ExternalAsset} asset Asset to move.\n   * @param {string} newPath New path relative to the configured prefix.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<ExternalAsset>} Moved asset.\n   */\n  move = async (asset, newPath, options) =>\n    this.operations.move(asset, newPath, this.getConfig(options), options);\n\n  /**\n   * Create an empty folder on the service.\n   * @param {string} dirPath Folder path relative to the configured prefix.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<void>}\n   */\n  createFolder = async (dirPath, options) =>\n    this.operations.createFolder(dirPath, this.getConfig(options), options);\n\n  /**\n   * Remove the placeholder of a folder on the service.\n   * @param {string} dirPath Folder path relative to the configured prefix.\n   * @param {MediaLibraryFetchOptions} options Options containing the configuration.\n   * @returns {Promise<void>}\n   */\n  deleteFolder = async (dirPath, options) =>\n    this.operations.deleteFolder(dirPath, this.getConfig(options), options);\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 {\n  encodeKey,\n  getFileKey,\n  getFolderKey,\n  getRelativeKey,\n} from '$lib/services/integrations/media-libraries/cloud/shared/keys';\nimport {\n  assertResponseOK,\n  createObjectStorageOperations,\n} from '$lib/services/integrations/media-libraries/cloud/shared/object-storage';\nimport { ObjectStorageService } from '$lib/services/integrations/media-libraries/cloud/shared/service';\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 * Remove any trailing slashes from the given URL.\n * @param {string} url URL.\n * @returns {string} Trimmed URL.\n */\nconst trimSlashes = (url) => url.replace(/\\/+$/, '');\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    ? trimSlashes(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)}/${encodeKey(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 = key.split('/').pop() || key;\n    const displayKey = getRelativeKey(config, key);\n    const encodedKey = encodeKey(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 ? `${trimSlashes(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 * @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 }) => {\n  const searchParams = new URLSearchParams({\n    restype: 'container',\n    comp: 'list',\n    maxresults: String(MAX_RESULTS),\n    ...(prefix && { prefix }),\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 * @returns {Promise<void>}\n * @see https://learn.microsoft.com/en-us/rest/api/storageservices/delete-blob\n */\nconst deleteBlob = async ({ key, config, credential: token }) => {\n  const response = await fetch(buildBlobRequestUrl(config, key, token), { method: 'DELETE' });\n\n  await assertResponseOK(response, `Failed to delete blob ${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  deleteObject: deleteBlob,\n};\n\n/**\n * Move a blob in the configured container to another path. The Blob service has no move operation,\n * so the blob is copied to the new name with the synchronous `Put Blob From URL` operation, and\n * then the original is deleted. The account’s CORS rules must allow the `PUT` and `DELETE` methods\n * as well as the `x-ms-copy-source` header, in addition to `x-ms-blob-type`; otherwise the browser\n * blocks the request at the preflight stage.\n * @param {ExternalAsset} asset Asset to move. Its `id` is the blob name.\n * @param {string} newPath New path relative to the configured prefix.\n * @param {AzureMediaLibrary} config Azure Blob Storage configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the SAS token).\n * @returns {Promise<ExternalAsset>} Moved asset.\n * @see https://learn.microsoft.com/en-us/rest/api/storageservices/put-blob-from-url\n */\nexport const moveBlob = async (asset, newPath, config, options) => {\n  const token = requireToken(options);\n  const { id: key, size, lastModified } = asset;\n  const newKey = getFileKey(config, newPath);\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  await deleteBlob({ key, config, credential: token });\n\n  return parseBlobResults(\n    [\n      {\n        Name: newKey,\n        Properties: {\n          ...(lastModified && { 'Last-Modified': lastModified.toUTCString() }),\n          ...(size && { 'Content-Length': String(size) }),\n        },\n      },\n    ],\n    config,\n    token,\n  )[0];\n};\n\n/**\n * Create an empty folder in the configured container by putting a zero-byte placeholder blob at\n * the folder name, the way Azure Storage Explorer creates a virtual directory.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @param {AzureMediaLibrary} config Azure Blob Storage configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the SAS token).\n * @returns {Promise<void>}\n */\nexport const createFolder = async (dirPath, config, options) => {\n  const token = requireToken(options);\n  const key = getFolderKey(config, dirPath);\n\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  return undefined;\n};\n\n/**\n * Remove the placeholder blob of a folder in the configured container. A folder that has no\n * placeholder, because it only ever held files, is as good as removed.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @param {AzureMediaLibrary} config Azure Blob Storage configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (`apiKey` contains the SAS token).\n * @returns {Promise<void>}\n */\nexport const deleteFolder = async (dirPath, config, options) => {\n  const token = requireToken(options);\n  const key = getFolderKey(config, dirPath);\n  const response = await fetch(buildBlobRequestUrl(config, key, token), { method: 'DELETE' });\n\n  await assertResponseOK(response, `Failed to delete folder ${key}`, { allowNotFound: true });\n\n  return undefined;\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 ? [`${trimSlashes(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    move: moveBlob,\n    createFolder,\n    deleteFolder,\n  }),\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","/* eslint-disable no-await-in-loop */\n\nimport { getHash } from '@sveltia/utils/crypto';\nimport { sleep } from '@sveltia/utils/misc';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { cmsConfig } from '$lib/services/config/state';\nimport { assertResponseOK } from '$lib/services/integrations/media-libraries/cloud/shared/object-storage';\nimport {\n  findLibraryOptions,\n  resolveLibraryOptions,\n} from '$lib/services/integrations/media-libraries/options';\nimport { fetchPages } from '$lib/services/integrations/media-libraries/paging';\nimport { createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * ExternalAsset,\n * MediaLibraryFetchOptions,\n * MediaLibraryService,\n * } from '$lib/types/private';\n * @import { CloudinaryMediaLibrary, CmsConfig, MediaField } from '$lib/types/public';\n */\n\n/**\n * @typedef {object} CloudinaryResource\n * @property {string} asset_id Asset ID.\n * @property {string} filename Filename without extension.\n * @property {string} format File format/extension.\n * @property {string} resource_type Resource type (image, video, raw).\n * @property {string} type Upload type.\n * @property {string} secure_url Secure URL.\n * @property {number} bytes File size in bytes.\n * @property {string} created_at Creation timestamp.\n * @property {number} [width] Image width in pixels.\n * @property {number} [height] Image height in pixels.\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 * @typedef {object} CloudinaryListResponse\n * @property {CloudinaryResource[]} resources List of resources.\n * @property {string} [next_cursor] Next page cursor.\n */\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 * Convert transformation object to Cloudinary transformation string.\n * @param {Record<string, any>} transformation Transformation object. E.g. `{ width: 400, crop:\n * 'scale' }`.\n * @returns {string} Transformation string. E.g. `w_400,c_scale`.\n * @see https://cloudinary.com/documentation/transformation_reference\n * @see https://decapcms.org/docs/cloudinary/#image-transformations\n * @see https://sveltiacms.app/en/docs/media/cloudinary#image-transformations\n */\nexport const transformationToString = (transformation) => {\n  // Mapping from full parameter names to Cloudinary URL abbreviations\n  /** @type {Record<string, string>} */\n  const parameterMap = {\n    angle: 'a',\n    audio_codec: 'ac',\n    audio_frequency: 'af',\n    aspect_ratio: 'ar',\n    background: 'b',\n    border: 'bo',\n    color: 'co',\n    crop: 'c',\n    default_image: 'd',\n    delay: 'dl',\n    density: 'dn',\n    dpr: 'dpr',\n    duration: 'du',\n    effect: 'e',\n    end_offset: 'eo',\n    fetch_format: 'f',\n    flags: 'fl',\n    fps: 'fps',\n    gravity: 'g',\n    height: 'h',\n    overlay: 'l',\n    opacity: 'o',\n    page: 'pg',\n    quality: 'q',\n    radius: 'r',\n    start_offset: 'so',\n    streaming_profile: 'sp',\n    transformation: 't',\n    underlay: 'u',\n    video_codec: 'vc',\n    video_sampling: 'vs',\n    width: 'w',\n    x: 'x',\n    y: 'y',\n    zoom: 'z',\n  };\n\n  /** @type {string[]} */\n  const parts = [];\n\n  // Process each key in the transformation object\n  Object.keys(transformation).forEach((key) => {\n    const value = transformation[key];\n    const abbreviation = parameterMap[key] || key;\n\n    // Skip undefined/null values\n    if (value === undefined || value === null) {\n      return;\n    }\n\n    // Handle different value types\n    if (typeof value === 'boolean') {\n      // For boolean flags, only include if true\n      if (value) {\n        parts.push(abbreviation);\n      }\n    } else if (Array.isArray(value)) {\n      // For arrays, join with dots (e.g., for flags)\n      parts.push(`${abbreviation}_${value.join('.')}`);\n    } else {\n      // For all other values, use key_value format\n      parts.push(`${abbreviation}_${value}`);\n    }\n  });\n\n  // Join all parts with commas\n  return parts.join(',');\n};\n\n/**\n * Parse API results into ExternalAsset format.\n * @param {CloudinaryResource[]} 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/cloudinary/#decap-cms-configuration-options\n * @see https://sveltiacms.app/en/docs/media/cloudinary#configuration\n */\nexport const parseResults = (results, { fieldConfig } = {}) => {\n  const {\n    output_filename_only: fileNameOnly = false,\n    use_transformations: useTransformations = true,\n    config: { default_transformations: defaultTransformations = [] } = {},\n  } = resolveLibraryOptions('cloudinary', fieldConfig) || {};\n\n  const transformation = /** @type {Record<string, any>[][]} */ (defaultTransformations)?.[0]?.[0];\n  const hasTransformation = useTransformations && isObject(transformation);\n\n  return results.map((result) => {\n    const {\n      asset_id: assetId,\n      resource_type: resourceType,\n      secure_url: url,\n      created_at: timestamp,\n      bytes: size,\n    } = result;\n\n    const fileName = /** @type {string} */ (url.split('/').pop());\n\n    return {\n      id: assetId,\n      description: fileName,\n      previewURL: url.replace('/upload/', '/upload/w_400,c_limit/'),\n      downloadURL: fileNameOnly\n        ? fileName\n        : hasTransformation\n          ? url.replace('/upload/', `/upload/${transformationToString(transformation)}/`)\n          : url,\n      fileName,\n      lastModified: new Date(timestamp),\n      size,\n      kind: resourceType === 'image' ? 'image' : resourceType === 'video' ? 'video' : 'other',\n    };\n  });\n};\n\n/**\n * Generate Basic Auth header for Cloudinary API.\n * @param {string} apiKey API key.\n * @param {string} apiSecret API secret.\n * @returns {string} Basic Auth header value.\n */\nexport const generateAuthHeader = (apiKey, apiSecret) => {\n  const credentials = `${apiKey}:${apiSecret}`;\n  const encoded = btoa(credentials);\n\n  return `Basic ${encoded}`;\n};\n\n/**\n * Fetch resources from Cloudinary API with pagination.\n * @param {MediaLibraryFetchOptions} options Options containing the API secret (apiKey).\n * @param {object} [config] Additional configuration.\n * @param {number} [config.maxPages] Maximum number of pages to fetch. Default: 10.\n * @param {string} [config.expression] Search expression for filtering.\n * @returns {Promise<ExternalAsset[]>} Assets.\n * @see https://cloudinary.com/documentation/admin_api#search_for_resources\n */\nexport const fetchResources = async (options, { maxPages = 10, expression } = {}) => {\n  const { kind, fieldConfig, apiKey: apiSecret } = options;\n  const { cloudName, apiKey } = getCloudConfig(fieldConfig);\n\n  if (!cloudName) {\n    return Promise.reject(new Error('Cloudinary cloud name is not configured'));\n  }\n\n  if (!apiKey) {\n    return Promise.reject(new Error('Cloudinary API key is not configured'));\n  }\n\n  if (!apiSecret) {\n    return Promise.reject(new Error('Cloudinary API secret is not provided'));\n  }\n\n  const authHeader = generateAuthHeader(apiKey, apiSecret);\n  const endpoint = `https://api.cloudinary.com/v1_1/${cloudName}/resources/search`;\n\n  const headers = {\n    'Content-Type': 'application/json',\n    Authorization: authHeader,\n  };\n\n  // Build expression with kind filter if specified\n  let filterExpression = expression;\n\n  if (kind === 'image' && !expression) {\n    filterExpression = 'resource_type:image';\n  } else if (kind === 'image' && expression) {\n    filterExpression = `(${expression}) AND resource_type:image`;\n  }\n\n  const allResources = await fetchPages(\n    async (/** @type {string | undefined} */ nextCursor) => {\n      const params = new URLSearchParams({\n        max_results: '100',\n        ...(filterExpression && { expression: filterExpression }),\n        ...(nextCursor && { next_cursor: nextCursor }),\n      });\n\n      const response = await fetch(`${endpoint}?${params}`, { headers });\n\n      await assertResponseOK(response, 'Failed to fetch resources');\n\n      /** @type {CloudinaryListResponse} */\n      const data = await response.json();\n\n      return { results: data.resources, next: data.next_cursor };\n    },\n    { maxPages },\n  );\n\n  return parseResults(allResources, { fieldConfig });\n};\n\n/**\n * List resources from Cloudinary.\n * @param {MediaLibraryFetchOptions} options Options containing the API secret (apiKey).\n * @returns {Promise<ExternalAsset[]>} Assets.\n */\nexport const list = async (options) => fetchResources(options);\n\n/**\n * Search resources in Cloudinary using the Search API.\n * @param {string} query Search query.\n * @param {MediaLibraryFetchOptions} options Options containing the API secret (apiKey).\n * @returns {Promise<ExternalAsset[]>} Assets.\n */\nexport const search = async (query, options) => {\n  // Build a search expression that searches in public_id and filename\n  const expression = `public_id:*${query}* OR filename:*${query}*`;\n\n  return fetchResources(options, { expression });\n};\n\n/**\n * Generate signature for Cloudinary upload.\n * @param {Record<string, string | number>} params Parameters to sign.\n * @param {string} apiSecret API secret.\n * @returns {Promise<string>} Signature.\n * @see https://cloudinary.com/documentation/upload_images#generating_authentication_signatures\n */\nexport const generateSignature = async (params, apiSecret) => {\n  // Sort parameters alphabetically and create string to sign\n  const sortedParams = Object.keys(params)\n    .sort()\n    .map((key) => `${key}=${params[key]}`)\n    .join('&');\n\n  return getHash(`${sortedParams}${apiSecret}`, { algorithm: 'SHA-256' });\n};\n\n/**\n * Upload files to Cloudinary.\n * @param {File[]} files Files to upload.\n * @param {MediaLibraryFetchOptions} options Options containing the API secret (apiKey).\n * @returns {Promise<ExternalAsset[]>} Uploaded assets.\n * @see https://cloudinary.com/documentation/image_upload_api_reference\n */\nexport const upload = async (files, options) => {\n  if (files.length === 0) {\n    return [];\n  }\n\n  const { fieldConfig, apiKey: apiSecret } = options;\n  const { cloudName, apiKey } = getCloudConfig(fieldConfig);\n\n  if (!cloudName) {\n    return Promise.reject(new Error('Cloudinary cloud name is not configured'));\n  }\n\n  if (!apiKey) {\n    return Promise.reject(new Error('Cloudinary API key is not configured'));\n  }\n\n  if (!apiSecret) {\n    return Promise.reject(new Error('Cloudinary API secret is not provided'));\n  }\n\n  const endpoint = `https://api.cloudinary.com/v1_1/${cloudName}/auto/upload`;\n  const timestamp = Math.floor(Date.now() / 1000);\n  /** @type {CloudinaryResource[]} */\n  const uploadedResources = [];\n\n  // Upload files one by one (Cloudinary doesn’t support batch uploads in the same way)\n  // eslint-disable-next-line no-restricted-syntax\n  for (const file of files) {\n    const params = {\n      timestamp,\n    };\n\n    const signature = await generateSignature(params, apiSecret);\n    const formData = new FormData();\n\n    formData.append('file', file);\n    formData.append('api_key', apiKey);\n    formData.append('timestamp', String(timestamp));\n    formData.append('signature', signature);\n\n    const response = await fetch(endpoint, {\n      method: 'POST',\n      body: formData,\n    });\n\n    await assertResponseOK(response, `Failed to upload file ${file.name}`);\n\n    /** @type {CloudinaryResource} */\n    const data = await response.json();\n\n    uploadedResources.push(data);\n\n    // Wait a bit between uploads to avoid rate limiting\n    if (files.length > 1) {\n      await sleep(50);\n    }\n  }\n\n  return parseResults(uploadedResources, { fieldConfig });\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 * Cloudinary media library service integration. The `list`, `search`, and `upload` methods are not\n * used at this time because Cloudinary has a CORS restriction that prevents direct API access from\n * the browser. Instead, the Cloudinary Media Library widget is used for authentication and file\n * selection/uploading.\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","/**\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 * 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","import { getHash } from '@sveltia/utils/crypto';\n\nimport { getAssetKind } from '$lib/services/assets/kinds';\nimport {\n  encodeKey as encodeKeyPath,\n  getFileKey,\n  getFolderKey,\n  getRelativeKey,\n} from '$lib/services/integrations/media-libraries/cloud/shared/keys';\nimport {\n  assertResponseOK,\n  createObjectStorageOperations,\n  deleteObjects,\n} from '$lib/services/integrations/media-libraries/cloud/shared/object-storage';\nimport { hmacSha256, toHex } from '$lib/services/utils/crypto';\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 * Percent-encode a string as RFC 3986 requires. Unlike `encodeURIComponent()`, the characters\n * `!'()*` are encoded as well, because Signature Version 4 requires every character other than the\n * unreserved ones to be encoded in the canonical URI and query string.\n * @param {string} str String to encode.\n * @returns {string} Encoded string.\n * @see https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html\n */\nconst encodeRfc3986 = (str) =>\n  encodeURIComponent(str).replace(\n    /[!'()*]/g,\n    (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`,\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 `${publicUrl.replace(/\\/+$/, '')}/${key}`;\n  }\n\n  if (endpoint) {\n    return `${endpoint.replace(/\\/+$/, '')}/${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) => encodeKeyPath(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 = key.split('/').pop() || 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 * @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 }) => {\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    ...(cursor && { 'continuation-token': cursor }),\n  });\n\n  const url = endpoint\n    ? `${endpoint.replace(/\\/+$/, '')}/${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 * @returns {Promise<void>}\n * @see https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteObject.html\n */\nconst deleteS3Object = async ({ key, config, credential: secretAccessKey }) => {\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}`);\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  /**\n   * Convert objects into the `ExternalAsset` format. S3 URLs carry no credential.\n   * @param {S3Object[]} objects Objects.\n   * @param {S3Config} config S3 configuration.\n   * @returns {ExternalAsset[]} Assets.\n   */\n  parseResults: (objects, config) => parseS3Results(objects, config),\n  putObject: putS3Object,\n  deleteObject: deleteS3Object,\n};\n\n/**\n * Move an object on S3-compatible storage to another path. S3 has no move operation, so the object\n * is copied to the new key and then the original is deleted. The bucket’s CORS policy must allow\n * the `PUT` and `DELETE` methods as well as the `x-amz-copy-source` and `x-amz-metadata-directive`\n * headers (an `AllowedHeaders` of `*` is the simplest); otherwise the browser blocks the request at\n * the preflight stage.\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 {S3Config} config S3 configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (apiKey contains secret access key).\n * @returns {Promise<ExternalAsset>} Moved asset.\n * @see https://docs.aws.amazon.com/AmazonS3/latest/API/API_CopyObject.html\n */\nexport const moveS3Object = async (asset, newPath, config, options) => {\n  const { bucket } = config;\n  const secretAccessKey = requireSecretAccessKey(options);\n  const { id: key, size = 0 } = asset;\n  const newKey = getFileKey(config, newPath);\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  await deleteS3Object({ key, config, credential: secretAccessKey });\n\n  return parseS3Results(\n    [{ Key: newKey, LastModified: new Date().toISOString(), ETag: '', Size: size }],\n    config,\n  )[0];\n};\n\n/**\n * Create an empty folder on S3-compatible storage by putting a zero-byte placeholder object at the\n * folder key, the way the AWS console does.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @param {S3Config} config S3 configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (apiKey contains secret access key).\n * @returns {Promise<void>}\n */\nexport const createS3Folder = async (dirPath, config, options) => {\n  const secretAccessKey = requireSecretAccessKey(options);\n  const key = getFolderKey(config, dirPath);\n\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  return undefined;\n};\n\n/**\n * Remove the placeholder object of a folder on S3-compatible storage. S3 reports success for a key\n * that doesn’t exist, so a folder that has no placeholder is fine.\n * @param {string} dirPath Folder path relative to the configured prefix.\n * @param {S3Config} config S3 configuration.\n * @param {MediaLibraryFetchOptions} options Fetch options (apiKey contains secret access key).\n * @returns {Promise<void>}\n */\nexport const deleteS3Folder = async (dirPath, config, options) =>\n  deleteObjects(\n    provider,\n    [/** @type {ExternalAsset} */ ({ id: getFolderKey(config, dirPath) })],\n    config,\n    options,\n  );\n\n/**\n * Operations of an S3-compatible object storage service.\n * @type {ObjectStorageOperations<S3Config>}\n */\nexport const s3Operations = createObjectStorageOperations(provider, {\n  move: moveS3Object,\n  createFolder: createS3Folder,\n  deleteFolder: deleteS3Folder,\n});\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 Service label.\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.\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  /**\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    resolveConfig = (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  apiKeyPattern: /^[A-Za-z0-9/+=]{40}$/,\n});\n\nexport default awsS3;\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 * 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   * Add the B2 region 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: `https://s3.${libOptions.region}.backblazeb2.com`,\n    public_url:\n      libOptions.public_url ??\n      `https://${libOptions.bucket}.s3.${libOptions.region}.backblazeb2.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 * 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 * @import { S3Config } from '$lib/types/private';\n * @import { S3MediaLibrary } from '$lib/types/public';\n */\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   * Add the Spaces region 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: `https://${libOptions.region}.digitaloceanspaces.com`,\n    public_url:\n      libOptions.public_url ??\n      `https://${libOptions.bucket}.${libOptions.region}.digitaloceanspaces.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 * 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   * Add the Scaleway region 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: `https://s3.${libOptions.region}.scw.cloud`,\n    public_url:\n      libOptions.public_url ?? `https://${libOptions.bucket}.s3.${libOptions.region}.scw.cloud`,\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 * 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","import { getPathInfo } from '@sveltia/utils/file';\n\nimport { slugify } from '$lib/services/common/slug';\nimport { renameIfNeeded, sanitizeFileName } from '$lib/services/utils/file';\n\n/**\n * Format the file name for uploading, ensuring it is sanitized and optionally slugified.\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 * @returns {string} The formatted file name, sanitized and possibly slugified.\n */\nexport const formatFileName = (\n  originalName,\n  { slugificationEnabled = false, assetNamesInSameFolder = [] } = {},\n) => {\n  let fileName = sanitizeFileName(originalName);\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  return renameIfNeeded(fileName, assetNamesInSameFolder);\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 { cmsConfig } from '$lib/services/config/state';\nimport { assertResponseOK } from '$lib/services/integrations/media-libraries/cloud/shared/object-storage';\nimport {\n  findLibraryOptions,\n  resolveLibraryOptions,\n} from '$lib/services/integrations/media-libraries/options';\nimport { fetchPages } from '$lib/services/integrations/media-libraries/paging';\nimport { splitIntoChunks } from '$lib/services/utils/array';\nimport { hmacSha256, toHex } from '$lib/services/utils/crypto';\n\n/**\n * @import {\n * ExternalAsset,\n * MediaLibraryFetchOptions,\n * MediaLibraryService,\n * } from '$lib/types/private';\n * @import { CmsConfig, MediaField, UploadcareMediaLibrary } from '$lib/types/public';\n */\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 * 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    const isVideo = mimeType.startsWith('video/');\n\n    return {\n      id: uuid,\n      description: fileName,\n      previewURL: `${baseURL}${isImage ? '-/preview/400x400/' : ''}`,\n      downloadURL:\n        `${baseURL}${isImage && defaultOperations ? `-${defaultOperations}` : ''}` +\n        `${autoFilename ? fileName : ''}`,\n      fileName,\n      lastModified: new Date(timestamp),\n      size,\n      kind: isImage ? 'image' : isVideo ? 'video' : 'other',\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 * 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 === 'image') {\n        results = results.filter((file) => file.is_image);\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 { publicKey, secretKey } = getKeys(options);\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\n  // Handle both single and multiple file responses\n  const uploadedFiles = Object.entries(data)\n    .filter(([key]) => !key.startsWith('UPLOADCARE_'))\n    .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: `https://ucarecdn.com/${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.\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  try {\n    const { origin } = new URL(options.config?.cdnBase ?? 'https://ucarecdn.com/');\n\n    return url.startsWith(`${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 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  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 { Entry, MediaFieldSource, TypedFieldKeyPath } 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 * @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}) => {\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  });\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 {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 * @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 * @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","/* eslint-disable no-continue */\n/* eslint-disable no-restricted-syntax */\n\nimport { getMediaFieldSource } 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 } from '$lib/services/contents/entry/fields';\nimport { MEDIA_FIELD_TYPES, RICH_TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\n\n/**\n * @import {\n * Asset,\n * AssetReference,\n * Entry,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalCollectionFile,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Regular expression to match `![alt](src \"title\")`, capturing the source. The alt text runs up to\n * the first `](`, so it can contain brackets, and the source up to the first `)` or an optional\n * double-quoted title, which can contain parentheses and escaped quotes.\n *\n * The pattern runs on untrusted Markdown, so it’s written to match in linear time. Every part can\n * only be matched one way, and neither the alt text nor the source can contain `![`, so a failed\n * match at one `![` doesn’t read the text after the next one again. A title is only looked for\n * right after the source’s last non-space character, and it can’t contain an unescaped quote, so\n * each quote is read as the start of a title at most once. An image nested in the alt text or\n * source of an unclosed one is matched on its own instead.\n */\nexport const MARKDOWN_IMAGE_REGEX =\n  /!\\[(?:[^\\]\\n!]|!(?!\\[)|\\](?!\\())*\\]\\(((?:[^\\n!)]|!(?!\\[))+?)(?:(?<!\\s)\\s+\"(?:[^\"\\\\\\n]|\\\\.)*\")?\\)/g;\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 * Get the targets the given field value or image source refers to.\n * @param {AssetReferenceMatcher} matcher Matcher.\n * @param {string} src Field value or image source found in it.\n * @param {object} context Context to resolve the value to an asset with.\n * @param {Entry} context.entry Entry.\n * @param {string} context.collectionName Collection name.\n * @param {string} [context.fileName] Collection file name.\n * @returns {number[]} Indexes of the targets.\n */\nconst getMatchingTargets = (matcher, src, { entry, collectionName, fileName }) => {\n  const indexes = matcher.byURL.get(src) ?? [];\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 } = getMediaFieldSource({ entry, collectionName, fileName, value: src }) ?? {};\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.\n * @param {AssetReferenceMatcher} matcher Matcher.\n * @param {number[]} indexes Indexes of the targets referred to.\n * @param {string} src Reference being replaced.\n * @returns {string | undefined} New URL, if any.\n */\nconst getNewURL = (matcher, indexes, src) =>\n  indexes\n    .map((index) => {\n      const { newURL } = matcher.targets[index];\n\n      return typeof newURL === 'function' ? newURL(src) : newURL;\n    })\n    .find(Boolean);\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 the source of an image in Markdown, so a\n * value that’s neither can be skipped before the costly field lookup.\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  matcher.byURL.has(value) ||\n  (value.includes('![') &&\n    [...value.matchAll(MARKDOWN_IMAGE_REGEX)].some(([, src]) => matcher.byURL.has(src)));\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 * @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}) => {\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  const context = { entry, collectionName, fileName };\n\n  if (MEDIA_FIELD_TYPES.includes(fieldType)) {\n    const matched = getMatchingTargets(matcher, value, context);\n    const newURL = getNewURL(matcher, matched, value);\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 images in markdown body\n  if (RICH_TEXT_FIELD_TYPES.includes(fieldType)) {\n    let replacing = false;\n\n    // Swap the URL within each matched image only, rather than its first occurrence in the text,\n    // which can be a link to the same file, the alt text, or the new URL written by a previous\n    // replacement. The new value is built from the original one, so doing this again, once for\n    // each collection the entry belongs to, gives the same result\n    const replaced = value.replace(MARKDOWN_IMAGE_REGEX, (image, /** @type {string} */ src) => {\n      const matched = getMatchingTargets(matcher, src, context);\n\n      if (!matched.length) {\n        return image;\n      }\n\n      const newURL = getNewURL(matcher, matched, src);\n\n      matched.forEach((index) => indexes.add(index));\n      replacing ||= !!newURL;\n\n      // The source follows the first `](`, as the alt text is matched lazily\n      const index = image.indexOf('](') + 2;\n\n      return `${image.slice(0, index)}${newURL || src}${image.slice(index + src.length)}`;\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 = { matcher, collectionName: collection.name, entry, content, keyPath };\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.\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, { entries = allEntries.current } = {}) =>\n  findAssetReferences(targets, { entries });\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 } 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","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 { 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 } 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  getAssociatedCollections(entry).flatMap((collection) => {\n    const collectionName = collection.name;\n    const isIndexFile = isCollectionIndexFile(collection, entry);\n    const collectionFiles = getCollectionFilesByEntry(collection, entry);\n\n    const fields = collectionFiles.length\n      ? collectionFiles.map(({ name: fileName }) =>\n          getField({ collectionName, fileName, valueMap: content, keyPath, isIndexFile }),\n        )\n      : [getField({ collectionName, valueMap: content, keyPath, isIndexFile })];\n\n    return fields.map((field) => field?.widget ?? 'string');\n  });\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 { 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 { prefs } from '$lib/services/user/prefs.svelte';\nimport { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\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)}/${id.split('/').map(encodeURIComponent).join('/')}`;\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. A file uploaded under an existing name overwrites\n * the asset on most services, 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 * 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.\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 = prefs.apiKeys?.[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  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 { sortItemsByKey } from '$lib/services/common/view';\n\n/**\n * @import { Asset, SortingConditions } from '$lib/types/private';\n */\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: { name, login, email } = {}, commitDate } = asset;\n\n  if (key === 'commit_author') {\n    return name || login || email;\n  }\n\n  if (key === 'commit_date') {\n    return commitDate;\n  }\n\n  // Exclude the file extension when sorting by name to sort numbered files properly, e.g.\n  // `hero.png`, `hero-1.png`, `hero-2.png` instead of `hero-1.png`, `hero-2.png`, `hero.png`\n  if (key === 'name') {\n    return asset.name.split('.')[0];\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 { selectedAssetFolder } from '$lib/services/assets/folders';\nimport { publishedAssets, selectedAssets, uploadingAssets } 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 {\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    // An asset’s folder is usually the very object the selection was made from, so identity\n    // settles it without walking the folder; the deep comparison is the fallback for a folder\n    // restored from `window.history.state`, which is an equal but separate object.\n    return _allAssets.filter(\n      ({ folder }) => folder === _selectedAssetFolder || equal(folder, _selectedAssetFolder),\n    );\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      selectedSubfolderPath.current.split('/').at(-1) ||\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.\n * @template T\n * @param {T[]} assets Listed assets.\n * @param {(asset: T) => boolean} isCurrent Whether an asset is the one 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 = (assets, isCurrent) => {\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\ncreateRootEffect(() => {\n  const assets = listedAssets.current;\n\n  void filterConditions.current;\n  selectedAssets.current = [];\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 * @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","/**\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 * 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 { createDerivedState, createRawState } from '$lib/services/utils/state.svelte';\nimport { decodeURIComponentSafely } 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 * Percent-encode each segment of the given route path, keeping the slashes, so a file or folder\n * name containing a `%`, `#` or `?` sign makes it through the URL hash intact and is decoded back\n * to the same name by {@link parseLocation}. Build every route that contains an entry or asset\n * path with this before passing it to {@link goto} or {@link goBack}.\n * @param {string} path Route path without a query string, e.g. `/assets/images/50%off.jpg`.\n * @returns {string} Encoded path, e.g. `/assets/images/50%25off.jpg`.\n */\nexport const encodeRoutePath = (path) => path.split('/').map(encodeURIComponent).join('/');\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 { origin, hash } = new URL(href);\n  const { pathname, searchParams } = new URL(`${origin}${hash.substring(1)}`);\n\n  return {\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(pathname.replace(/(?!^)\\/+$/, '')),\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// 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\nglobalThis.addEventListener?.(\n  'keydown',\n  () => {\n    activeTransition?.skipTransition();\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    },\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\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      });\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 trigged 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 encodeRoutePath}.\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  const { origin, pathname, hash } = window.location;\n  const oldURL = `${origin}${pathname}${hash}`;\n  const newURL = `${origin}${pathname}#${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(\n    `${encodeRoutePath(`/collections/${collectionName}/entries/${subPath}`)}${query ? `?${query}` : ''}`,\n    {\n      replaceState: true,\n    },\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', 'config', '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  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 nested collection, so the user\n * 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 nested collection, 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    ? encodeRoutePath(`/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","import { allAssets } from '$lib/services/assets/state';\nimport { backend } from '$lib/services/backends';\nimport { advanceRepositoryHead } from '$lib/services/backends/git/shared/file-cache';\nimport { 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/**\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  const lastCommit = await /** @type {NonNullable<typeof fetchLastCommit>} */ (fetchLastCommit)();\n\n  if (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    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  // 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.\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  // Waiting for the promise is what matters; the result, or a failure, is the other caller’s\n  await pending?.catch(() => undefined);\n\n  commitCount += 1;\n\n  try {\n    return await commit();\n  } finally {\n    commitCount -= 1;\n  }\n};\n","import { checkForRemoteChanges, MIN_CHECK_GAP } from '$lib/services/backends/refresh';\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, reporting a failure rather than letting it escape the timer.\n * @param {number} [maxAge] Skip the check if one was started within this many milliseconds.\n */\nconst check = async (maxAge = 0) => {\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\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(MIN_CHECK_GAP);\n  }\n};\n\n/**\n * Start checking the repository for someone else’s commits, on schedule and whenever the user\n * comes back to 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 * 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","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 * @returns {Promise<PageLiveness>} Result.\n */\nexport const pingURL = async (url) => {\n  const cached = cache.get(url);\n\n  if (cached && 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  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 { cmsConfig } from '$lib/services/config';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\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","import { backend } from '$lib/services/backends';\nimport { mergeLockedBranch } from '$lib/services/backends/branch-access';\nimport { cmsConfig } from '$lib/services/config';\nimport { allEntries, findEntryByPaths } from '$lib/services/contents';\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 { getPublishMode, isWorkflowConfigured } from '$lib/services/workflow/config';\nimport { openAuthoring } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import {\n * Entry,\n * InternalCollection,\n * UnpublishedEntry,\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    getPublishMode({ cmsConfig: cmsConfig.current, collection }) === 'editorial_workflow');\n\n/**\n * List of unpublished entries retrieved from the backend’s open pull requests.\n * @type {{ current: UnpublishedEntry[] }}\n */\nexport const unpublishedEntries = createRawState([]);\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 * 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(\n    (entry) =>\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/**\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 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  unpublishedEntries.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 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 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.\n * @param {WorkflowPullRequest} pullRequest Pull request.\n * @returns {boolean} Result.\n */\nexport const canMergePullRequest = (pullRequest) =>\n  pullRequest.canMerge !== false && !mergeLockedBranch.current;\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, and the\n * collection’s `publish` option can hide the control altogether, so an editor can move an entry\n * through the review stages but leave the actual publishing to someone else. An Open Authoring\n * contributor can’t merge a pull request on the configured repository, and neither can a user who\n * 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 = ({ workflow: { status, pullRequest } }, collection) =>\n  !openAuthoring.current &&\n  canMergePullRequest(pullRequest) &&\n  (status === 'pending_publish' || status === 'pending_deletion') &&\n  collection?.publish !== false;\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","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 { unpublishedEntries } 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  unpublishedEntries.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","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 { allAssets } from '$lib/services/assets/state';\n\n/**\n * @import { Asset, 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 * 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. 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  allAssets.current = allAssets.current.flatMap((asset) =>\n    asset.workflow?.branch === branch ? (asset.workflow.replacedAsset ?? []) : asset,\n  );\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 { getPathInfo } from '@sveltia/utils/file';\n\nimport { parseAssetFileInfo } from '$lib/services/backends/git/shared/parse-files';\nimport { createFileList } from '$lib/services/backends/process';\nimport { isInRootDir } from '$lib/services/backends/root-dir';\nimport { allEntries, findEntryByPaths } from '$lib/services/contents';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport { prepareEntries } from '$lib/services/contents/file/process';\nimport { parseBranchName } from '$lib/services/workflow/branch';\n\n/**\n * @import {\n * Asset,\n * BaseFileListItemProps,\n * Entry,\n * WorkflowStatus,\n * UnpublishedEntry,\n * WorkflowPullRequest,\n * } from '$lib/types/private';\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 {Entry} entry Entry parsed from the pull request.\n * @param {string[]} previousPaths File paths the pull request renamed the entry from.\n * @returns {Entry} Entry with the unchanged locales merged in.\n */\nconst completeEntry = (entry, previousPaths) => {\n  const paths = new Set([...getEntryPaths(entry), ...previousPaths]);\n  // `allEntries` holds the version currently on the configured branch\n  const publishedEntry = findEntryByPaths(paths);\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\n    locales: { ...publishedEntry.locales, ...entry.locales },\n    slug: renamed ? entry.slug : publishedEntry.slug,\n    subPath: renamed ? entry.subPath : publishedEntry.subPath,\n  };\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 * 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 parsed = parseBranchName(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 }) => ({\n        path,\n        sha,\n        size,\n        text,\n        name: getPathInfo(path).basename,\n      }))\n  );\n\n  const { entryFiles, assetFiles } = createFileList(files);\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 previousPaths = vacatedPaths.length\n    ? createFileList(\n        vacatedPaths.map((path) => ({\n          path,\n          name: getPathInfo(path).basename,\n          sha: '',\n          size: 0,\n        })),\n      )\n        .entryFiles.filter(({ folder }) => folder.collectionName === collectionName)\n        .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  const targetFiles = entryFiles.filter(\n    ({ folder, text }) => folder.collectionName === collectionName && text !== undefined,\n  );\n\n  // A pull request that only removes entry files is an Unpublish: there’s nothing to parse, so\n  // reuse the published entry it removes. Its content is what the list and the editor display\n  // while the removal awaits publication.\n  if (!targetFiles.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        ...entry,\n        workflow: {\n          pullRequest,\n          // A removal opened before the dedicated status existed carries `pending_publish`, so the\n          // 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      assets,\n    };\n  }\n\n  const { entries } = await prepareEntries(targetFiles);\n  const { fileName } = targetFiles[0].folder;\n\n  return {\n    entries: entries.map((entry) => ({\n      ...completeEntry(entry, previousPaths),\n      workflow: {\n        pullRequest,\n        status: pullRequest.status,\n        collectionName,\n        fileName,\n        previousPaths,\n      },\n    })),\n    assets,\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 { backend } from '$lib/services/backends';\nimport { cmsConfig } from '$lib/services/config';\nimport {\n  unpublishedEntries,\n  unpublishedEntriesLoaded,\n  unpublishedEntriesLoading,\n  workflowEnabled,\n} from '$lib/services/workflow';\nimport { mergeWorkflowAssets } from '$lib/services/workflow/assets';\nimport { convertPullRequests } from '$lib/services/workflow/entries';\nimport { openAuthoringInitialized } from '$lib/services/workflow/open-authoring';\n\n/**\n * @import { WorkflowPullRequest } from '$lib/types/private';\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 * 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 = backend.current?.workflow;\n\n  if (!workflowEnabled.current || !workflow || !isWorkflowReady()) {\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 unpublishedEntries} 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  try {\n    const { entries, assets } = await convertPullRequests(await pullRequests);\n\n    unpublishedEntries.current = entries;\n    mergeWorkflowAssets(assets);\n  } catch (/** @type {any} */ ex) {\n    // eslint-disable-next-line no-console\n    console.error(ex);\n  } finally {\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","import { _ } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\nimport { LocalStorage } from '@sveltia/utils/storage';\n\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 { repositoryHead } 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 { prefs } from '$lib/services/user/prefs.svelte';\nimport {\n  publishingBranches,\n  unpublishedEntries,\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 { BackendService, InternalCmsConfig, User } 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   * Account that a magic link signs the user in to, while they’re asked whether to go ahead. The\n   * link can be crafted by anyone, so it’s only used once the user has recognized the account.\n   * @type {{ account: User, resolve: (confirmed: boolean) => void } | undefined}\n   */\n  magicLinkConfirmation: undefined,\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.\n */\nconst clearUserCache = async () => {\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 * 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. Other preferences, like the theme and language, are kept. This is only done on an\n * explicit sign-out, not when an expired or revoked token sends the user back to the sign-in form.\n */\nconst clearIntegrationCredentials = () => {\n  prefs.apiKeys = {};\n  delete prefs.logins;\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 generated for QR code sign-in to extract the token and preferences.\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 = JSON.parse(atob(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    }\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  // Read the keys one at a time, stopping at the first hit\n  const userCache = await [USER_STORAGE_KEY, ...LEGACY_USER_STORAGE_KEYS].reduce(\n    async (previous, key) => (await previous) || LocalStorage.get(key),\n    /** @type {Promise<any>} */ (Promise.resolve(undefined)),\n  );\n\n  return isObject(userCache) && typeof userCache.backendName === 'string' ? userCache : undefined;\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 {BackendService | undefined} Backend instance to be used.\n */\nexport const getBackend = (_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    _user?.backendName === 'local' || _user?.backendName === 'proxy'\n      ? 'local'\n      : /** @type {InternalCmsConfig} */ (cmsConfig.current).backend.name;\n\n  return selectBackend(_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 = 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  const confirmed = await new Promise((resolve) => {\n    auth.magicLinkConfirmation = { account: /** @type {User} */ (account), resolve };\n  });\n\n  auth.magicLinkConfirmation = undefined;\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.\n * @param {Record<string, any>} copiedPrefs Preferences passed with the link.\n */\nexport const copyMagicLinkPrefs = (copiedPrefs) => {\n  if ('deployHookURL' in copiedPrefs) {\n    delete prefs.deployHookAuthHeader;\n  }\n\n  Object.assign(prefs, copiedPrefs);\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  // The pull requests don’t depend on the files, so they’re requested at the same time\n  const pullRequests = startLoadingPullRequests();\n\n  await _backend.fetchFiles();\n  await loadUnpublishedEntries(pullRequests);\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 = 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  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\n  // Copy user preferences passed with QR code\n  if (verified && copiedPrefs) {\n    copyMagicLinkPrefs(copiedPrefs);\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 */\nexport const signInManually = async (_backendName, token) => {\n  resetError();\n\n  const _backend = selectBackend(_backendName);\n\n  if (!_backend) {\n    return;\n  }\n\n  let _user;\n\n  auth.signingIn = true;\n\n  try {\n    _user = await _backend.signIn({ token, auto: false });\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  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 * Sign out from the current backend.\n */\nexport const signOut = async () => {\n  stopRemoteChangePolling();\n  await backend.current?.signOut();\n  await clearUserCache();\n  clearIntegrationCredentials();\n\n  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  unpublishedEntries.current = [];\n  unpublishedEntriesLoaded.current = false;\n  publishingBranches.current = [];\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 * @import { Backend, 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 { base_url: baseURL, app_id: appId } = /** @type {GiteaBackend} */ (backendConfig);\n\n  return {\n    serviceLabel:\n      name === 'gitea' && baseURL === 'https://codeberg.org' ? 'Codeberg' : backendLabel,\n    tokenOptionHidden: !isTestRepo && authMethods?.includes('token') === false,\n    oauthOptionHidden: !isTestRepo && authMethods?.includes('oauth') === false,\n    oauthOptionDisabled: name === 'gitea' && !appId,\n  };\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, ConfirmationDialog, Icon, PromptDialog, Spacer } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import { allBackendServices } from '$lib/services/backends';\n  import { cmsConfig } from '$lib/services/config';\n  import { auth, signInAutomatically, signInManually } 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 { 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  const backend = $derived(allBackendServices[backendName]);\n  const isTestRepo = $derived(backendName === 'test-repo');\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  /* 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 } = auth.magicLinkConfirmation?.account ?? {};\n\n    return login || name || '';\n  });\n  /* v8 ignore stop */\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  {: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              'https://sveltiacms.app/en/docs/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 !oauthOptionHidden}\n      <Button\n        variant={showLocalBackendOption ? 'secondary' : 'primary'}\n        label={isTestRepo\n          ? _('work_with_test_repo')\n          : _('sign_in_with_x', { values: { service: serviceLabel } })}\n        disabled={oauthOptionDisabled}\n        onclick={async () => {\n          await signInManually(backendName);\n        }}\n      />\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={!!auth.magicLinkConfirmation}\n  title={_('sign_in_with_link')}\n  okLabel={_('sign_in')}\n  onOk={() => {\n    auth.magicLinkConfirmation?.resolve(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    auth.magicLinkConfirmation?.resolve(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    :global {\n      .button {\n        width: 320px;\n      }\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 { encodeBase64 } from '@sveltia/utils/file';\nimport mime from 'mime';\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 {\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.\n */\nconst getDataURL = async (blob, options) => {\n  const transformedBlob = await transformImage(blob, options);\n  const data = await encodeBase64(transformedBlob);\n\n  return `data:image/webp;base64,${data}`;\n};\n\n/**\n * The app icon URL, derived from the app logo URL. It generates a WebP thumbnail of the logo for\n * use in the app manifest and as the Apple touch icon. If the transformation fails, it falls back\n * to no icon. The available sizes are 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 response = await fetch(logoURL);\n\n      if (!response.ok) {\n        throw new Error('Failed to fetch logo');\n      }\n\n      const blob = await response.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\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: 'image/webp' },\n      { src: iconURLs.large, sizes: '512x512', type: 'image/webp' },\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","<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 { 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 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    {#if cmsConfigLoaded.current}\n      <img src={appLogoURL.current} alt=\"\" class=\"logo\" />\n      <h1>{appTitle.current}</h1>\n    {/if}\n    {#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    justify-content: center;\n    align-items: center;\n    gap: 16px;\n    padding: 32px;\n\n    .inner {\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","<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","import { UNPKG_BASE_URL, version as userVersion } from '$lib/services/app';\n\n/**\n * URL of the `package.json` of the latest published version.\n */\nconst PACKAGE_JSON_URL = `${UNPKG_BASE_URL}/package.json`;\n/**\n * URL of the script that loads the latest version, as opposed to one pinned to a version.\n */\nconst SCRIPT_URL = `${UNPKG_BASE_URL}/dist/sveltia-cms.js`;\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 the application.\n * @returns {Promise<string | undefined>} Version, or `undefined` if it couldn’t be fetched.\n */\nexport const getLatestVersion = async () => {\n  try {\n    const response = await fetch(PACKAGE_JSON_URL);\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 * Check whether a new version of the application is available, and whether a reload would pick it\n * up. It would if the script is loaded from the CDN without a version pinned. If it’s pinned in the\n * script tag or installed via npm, a reload won’t update the instance, so a console warning is\n * shown instead.\n * @returns {Promise<boolean>} `true` if a reload would update the application.\n */\nexport const isUpdateAvailable = async () => {\n  const latestVersion = await getLatestVersion();\n\n  if (!latestVersion || latestVersion === userVersion) {\n    return false;\n  }\n\n  if (document.querySelector(`script[src=\"${SCRIPT_URL}\"]`)) {\n    return true;\n  }\n\n  // eslint-disable-next-line no-console\n  console.warn(\n    `[Sveltia CMS] A new version (${latestVersion}) is available. ` +\n      'Update the pinned version in your script tag or package.json to upgrade.',\n  );\n\n  return false;\n};\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}\",\"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\",\"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_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\",\"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\",\"sign_out\":\"Sign Out\",\"install_as_app\":\"Install as App\",\"contents\":\"Contents\",\"assets\":\"Assets\",\"editorial_workflow\":\"Editorial Workflow\",\"cms_config\":\"CMS Configuration\",\"menu\":\"Menu\",\"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\",\"switching_language\":\"Switching to {$locale}…\",\"locale_load_failed\":\"Couldn’t load the {$locale} translation. Please try again later.\",\"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\",\"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}.\",\"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\",\"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\",\"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_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.}}\",\"enter_new_name_for_external_folder\":\".input {$count :integer} .match $count 0 {{Enter a new name below.}} one {{Enter a new name below. The file in the folder will be moved along, and its URL will change, so update any entry using it.}} * {{Enter a new name below. The {$count} files in the folder will be moved along, and their URLs will change, so update any entries using them.}}\",\"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.\",\"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\",\"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.\"},\"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.}}\",\"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.\",\"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.}}\",\"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.\",\"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\",\"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.\",\"failed\":\"The preview couldn’t be built.\",\"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.\"},\"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.\"},\"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.\"}},\"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_item\":\"Reorder Item\",\"list_item_value\":\"Item Value\",\"add_x\":\"Add {$name}\",\"list_item_options\":\"List Item Options\",\"add_item_above\":\"Add Item Above\",\"add_item_below\":\"Add Item Below\",\"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.\"},\"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.\",\"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:\"},\"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\"},\"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.\"}},\"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\"},\"aws_s3\":{\"auth_key_label\":\"Secret Access Key\"},\"bunny_storage\":{\"auth_key_label\":\"Storage Zone Password\"},\"cloudflare_r2\":{\"auth_key_label\":\"Secret Access Key\"},\"digitalocean_spaces\":{\"auth_key_label\":\"Secret Access Key\"}},\"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.\",\"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` publish mode. 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.\",\"oauth_no_app_id\":\"OAuth application ID is not defined.\",\"open_authoring_no_workflow\":\"The `open_authoring` option requires the `editorial_workflow` publish mode. See the <a>documentation</a> for details.\",\"no_auth_methods\":\"The `auth_methods` option must contain at least one method.\",\"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.\",\"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://`.\",\"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.\",\"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, including Open Authoring, is 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_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_sortable_field\":\"The `sortable_fields` 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.\",\"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`.\",\"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}`.\",\"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, 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.\",\"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.\",\"unsupported_ignored_option\":\"The `{$prop}` option is not supported in Sveltia CMS. It will be ignored.\",\"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.\",\"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.\",\"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.\"},\"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}.\",\"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.\",\"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?\",\"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.\",\"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\"},\"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\",\"site_configuration_editor\":\"Site Configuration Editor\",\"prefs\":{\"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>.\"},\"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.\"}},\"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\"}},\"advanced\":{\"title\":\"Advanced\",\"beta\":{\"title\":\"Beta Features\",\"description\":\"Enable some beta features that may be unstable or unlocalized.\",\"switch_label\":\"Join Beta Program\"},\"developer_mode\":{\"title\":\"Developer Mode\",\"description\":\"Enable some developer-oriented features, including detailed console logs and native context menus.\",\"switch_label\":\"Enable Developer Mode\"},\"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.\",\"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.\"}},\"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.\"}}}},\"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\nimport defaultLocaleStrings from '$lib/locales/en-US.yaml';\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    appLocaleLoading.current = undefined;\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  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 {\n    /* eslint-disable prefer-const */\n    plan,\n    kind = 'entry',\n    count,\n    /* eslint-enable prefer-const */\n  } = $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\n  import CascadeDeleteNote from '$lib/components/common/cascade-delete-note.svelte';\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 {string} [buttonDescription] The `aria-label` attribute on the button.\n   * @property {string} [dialogDescription] Description to be displayed on the dialog.\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    /* eslint-disable prefer-const */\n    assets = [],\n    disabled = false,\n    deleteAssets,\n    planDeletion = undefined,\n    buttonDescription = '',\n    dialogDescription = '',\n    onDelete = undefined,\n    useButton = true,\n    /* eslint-enable prefer-const */\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\n  const Component = $derived(useButton ? Button : MenuItem);\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\n    planDeletion(selection).then((result) => {\n      // The dialog may have been reopened for another selection meanwhile\n      if (showDialog && assets === selection) {\n        plan = result;\n      }\n    });\n  });\n</script>\n\n<Component\n  variant=\"ghost\"\n  disabled={disabled || !assets.length}\n  label={_('delete')}\n  aria-label={buttonDescription}\n  onclick={() => {\n    showDialog = true;\n  }}\n/>\n\n<ConfirmationDialog\n  bind:open={showDialog}\n  title={_('delete_assets', { values: { count: assets.length } })}\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; the note explains why -->\n  {#if !blocked}\n    {dialogDescription}\n  {/if}\n  {#if plan}\n    <CascadeDeleteNote {plan} kind=\"asset\" count={assets.length} />\n  {/if}\n</ConfirmationDialog>\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 {\n    /* eslint-disable prefer-const */\n    'aria-label': ariaLabel,\n    useShortcut = false,\n    onclick = undefined,\n    /* eslint-enable prefer-const */\n  } = $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","import { tick } from 'svelte';\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    const container = document.querySelector('#page-container');\n\n    if (container instanceof HTMLElement) {\n      container.tabIndex = -1;\n      container.focus();\n    }\n  };\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  const startTime = performance.now();\n\n  /**\n   * Check where the focus is, once the content has been updated.\n   */\n  const check = () => {\n    const { activeElement } = document;\n\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;\n    }\n\n    const listbox = container.querySelector('[role=\"listbox\"]');\n\n    if (listbox instanceof HTMLElement) {\n      listbox.focus();\n\n      return;\n    }\n\n    if (activeElement === document.body && container.isConnected) {\n      container.tabIndex = -1;\n      container.focus();\n    }\n\n    if (performance.now() - startTime < timeout) {\n      window.requestAnimationFrame(check);\n    }\n  };\n\n  window.requestAnimationFrame(check);\n};\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    /* eslint-disable prefer-const */\n    title = undefined,\n    contentKey = undefined,\n    onBack,\n    onPrevious = undefined,\n    onNext = undefined,\n    actions,\n    editOptions,\n    preview,\n    info = undefined,\n    /* eslint-enable prefer-const */\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 {\n    /* eslint-disable prefer-const */\n    assets = [],\n    getName,\n    getBlob,\n    useButton = true,\n    /* eslint-enable prefer-const */\n  } = $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 {\n    /* eslint-disable prefer-const */\n    items,\n    count,\n    useButton = true,\n    /* eslint-enable prefer-const */\n  } = $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 { 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 * 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 { getDateTimeParts } from '@sveltia/utils/datetime';\nimport { getPathInfo } from '@sveltia/utils/file';\n\nimport { formatFileName } from '$lib/services/assets/file-name';\nimport { replaceTemplatePlaceholder } from '$lib/services/common/template/replacers';\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { cmsConfig } from '$lib/services/config';\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 * 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  const timeZone = cmsConfig.current?.slug?.timezone === 'local' ? undefined : 'UTC';\n\n  return {\n    template,\n    slugificationEnabled,\n    randomValues: new Map(),\n    dateTimeParts: getDateTimeParts({ timeZone }),\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 {object} args Arguments.\n * @param {AssetNameTemplate} args.nameTemplate Template.\n * @param {string} args.originalName Original file name, which `{{filename}}` and `{{extension}}`\n * stand for.\n * @param {InternalCollection} [args.collection] Collection of the entry the file is added to.\n * @param {string} [args.collectionFileName] Collection file name. File/singleton collection only.\n * @param {FlattenedEntryContent} [args.content] Content of the entry in the default locale.\n * @param {string} [args.slug] Slug of the entry in the default locale.\n * @param {boolean} [args.isIndexFile] Whether the entry is the collection’s special index file.\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 =\n    collection?._type === 'entry' ? (collection.identifier_field ?? 'title') : 'title';\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 template is filled with the default locale’s slug and content, so a file\n * used in several locales gets one name, which is then sanitized, and slugified if the\n * `slugify_filename` 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 { collection, fileName, defaultLocale, currentValues, isIndexFile } = draft;\n\n  const name = fillAssetNameTemplate({\n    nameTemplate,\n    originalName: file.name,\n    collection,\n    collectionFileName: fileName,\n    content: currentValues[defaultLocale],\n    slug: defaultLocaleSlug,\n    isIndexFile,\n  });\n\n  return formatFileName(name, { slugificationEnabled: nameTemplate.slugificationEnabled });\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 { createRawState, createRootEffect } from '$lib/services/utils/state.svelte';\n\n/**\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 * @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 } = {},\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        })\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 * 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    const results = await Promise.all(\n      originalFiles.map((file) => processFile(file, config, { nameTemplate })),\n    );\n\n    if (superseded) {\n      return;\n    }\n\n    processedAssets.current = {\n      processing: false,\n      ...partitionProcessedFiles(results),\n      transformedFileMap: new WeakMap(\n        results\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 {\n  externalAssetCounts,\n  externalAssets,\n  externalAssetsError,\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 { 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 { normalizeFileNameTemplate } from '$lib/services/integrations/media-libraries/default';\nimport { createPath } from '$lib/services/utils/file';\nimport { createDeepState, createRawState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { AssetSubfolder, ExternalAsset, MediaLibraryService } 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 * Successful operations are reported through {@link assetUpdatesToast}, like repository assets.\n * @type {{ current: { show: boolean, status: 'info' | '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\n  try {\n    const fetchOptions = getFetchOptions(service);\n\n    // A service with folder support lists its empty folders along with the files\n    const { assets, folders } = 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      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 * @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 } = {}) => {\n  const nameTemplate = replacing ? undefined : normalizeFileNameTemplate(options.filename_template);\n\n  const processed = await Promise.all(\n    files.map((file) => processFile(file, options, { nameTemplate })),\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    }\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.\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  try {\n    const renamedAsset = await service.rename(asset, newName, getFetchOptions(service));\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 * 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 list is reloaded from the\n * service afterwards, whether or not every move went through, so it never shows a file at a path\n * 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 = [...dirPath.split('/').slice(0, -1), newName].join('/');\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  const assets = getExternalSubfolderAssets(dirPath);\n  const folders = getExternalFolderTree(dirPath);\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    // Move the files one at a time, as the services do\n    // eslint-disable-next-line no-restricted-syntax\n    for (const asset of assets) {\n      // eslint-disable-next-line no-await-in-loop\n      await service.move(asset, rebase(asset.description), fetchOptions);\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  const assets = getExternalSubfolderAssets(dirPath);\n  const folders = getExternalFolderTree(dirPath);\n\n  externalAssetsToast.current = { show: true, status: 'info', message: 'deleting_folder' };\n\n  try {\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 { isTextFileType } from '@sveltia/utils/file';\nimport mime from 'mime';\n\nimport { SUPPORTED_IMAGE_TYPES } from '$lib/services/utils/media/image';\nimport { transformImage } from '$lib/services/utils/media/image/transform';\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 {\n    /* eslint-disable prefer-const */\n    assets = [],\n    useButton = true,\n    /* eslint-enable prefer-const */\n  } = $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 and Replace items, and any extra 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 {() => 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 {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    /* eslint-disable prefer-const */\n    readOnly = false,\n    canEdit = false,\n    canRename = false,\n    canReplace = false,\n    onEdit = undefined,\n    onRename = undefined,\n    onReplace = undefined,\n    extraItems = undefined,\n    moreItems = undefined,\n    /* eslint-enable prefer-const */\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 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 Edit options menu for an asset on a cloud storage service: Rename 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\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 {Snippet} [extraItems] Slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    asset,\n    extraItems = undefined,\n    /* eslint-enable prefer-const */\n  } = $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  onRename={service?.rename\n    ? () => {\n        renamingExternalAsset.current = asset;\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","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","/**\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  import mime from 'mime';\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\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    /* eslint-disable prefer-const */\n    fileName,\n    kind,\n    size = undefined,\n    hasDimensions = false,\n    dimensions = undefined,\n    duration = undefined,\n    /* eslint-enable prefer-const */\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 {\n    /* eslint-disable prefer-const */\n    preview = undefined,\n    children,\n    /* eslint-enable prefer-const */\n  } = $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 { encodeRoutePath, goto } from '$lib/services/app/navigation';\n  import { getCollectionLabel } from '$lib/services/contents/collection';\n  import {\n    getCollectionFileLabel,\n    getCollectionFilesByEntry,\n  } from '$lib/services/contents/collection/files';\n  import { getAssociatedCollections } from '$lib/services/contents/entry/collections';\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 {\n    /* eslint-disable prefer-const */\n    entries,\n    /* eslint-enable prefer-const */\n  } = $props();\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 !entries}\n    <p>{_('loading')}</p>\n  {:else}\n    {#each entries as entry (entry.id)}\n      {#each getAssociatedCollections(entry) 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: encodeRoutePath(`/collections/${collection.name}/entries/${file.name}`),\n              collectionLabel,\n              entryLabel: getCollectionFileLabel(file),\n            })}\n          {:else}\n            {@render usedEntryLink({\n              link: encodeRoutePath(`/collections/${collection.name}/entries/${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","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 { removeVisibilityResolver, waitForVisibility } from '@sveltia/utils/element';\n  import { onMount, untrack } from 'svelte';\n\n  import {\n    getAssetBlobURL,\n    getAssetThumbnailURL,\n    revokeAssetBlobURLIfNeeded,\n    revokeBlobURLIfNeeded,\n  } from '$lib/services/assets/info';\n  import { hasPDFThumbnail, THUMBNAIL_KINDS } from '$lib/services/assets/kinds';\n  import { requestFlushSync } from '$lib/services/utils/render';\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 {() => 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    /* eslint-disable prefer-const */\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    onError = () => undefined,\n    ...rest\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {HTMLImageElement | HTMLMediaElement | undefined} */\n  let mediaElement = $state();\n  let hasError = $state(false);\n  let loaded = $state(false);\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(src);\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 && hasPDFThumbnail(asset.name)) ||\n      (isThumbnail && THUMBNAIL_KINDS.includes(kind)),\n  );\n\n  let updatingSrc = false;\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. Kept outside the reactive graph so the cleanup below can\n   * read it after the component is destroyed.\n   * @type {string[]}\n   */\n  const ownedURLs = [];\n  /**\n   * The asset this preview last rendered, kept outside the reactive graph like {@link ownedURLs}.\n   *\n   * The cleanup below runs while the component is being destroyed, and reading the `asset` prop\n   * there would read whatever the parent passes it from — a `$derived` holding the thumbnail of a\n   * collapsed Object field or List item. Svelte answers a read made while an effect is being torn\n   * down by walking that derived’s dependency graph to see whether it has to be recomputed, and\n   * that walk doesn’t memoize: in a deeply nested entry editor, where every level multiplies the\n   * number of paths to the same derived, expanding one field froze the browser for tens of seconds.\n   * The cleanup reads this copy instead, so it touches nothing reactive.\n   * @type {Asset | undefined}\n   * @see https://github.com/sveltia/sveltia-cms/issues/1006\n   */\n  let currentAsset = undefined;\n  /**\n   * Whether the component has been destroyed. A URL lookup that finishes afterwards releases what\n   * it created, as the cleanup below has already run, and reads nothing reactive.\n   */\n  let destroyed = false;\n\n  /**\n   * Remember an object URL this preview created, so that it can be released later.\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   * 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, one at a time */\n    if (!asset || !mediaElement || updatingSrc) {\n      return;\n    }\n\n    updatingSrc = true;\n    hasError = false;\n\n    if (loading === 'lazy') {\n      await waitForVisibility(mediaElement);\n    }\n\n    // Read up front, as a derived can’t be read once the component has been destroyed\n    const previousSrc = resolvedSrc;\n    const thumbnail = isThumbnail;\n    let nextSrc = previousSrc;\n\n    try {\n      const url = thumbnail ? await getAssetThumbnailURL(asset) : await getAssetBlobURL(asset);\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 (destroyed) {\n        revokeBlobURLIfNeeded(url);\n\n        return;\n      }\n\n      nextSrc = url;\n      resolvedSrc = url;\n    } catch {\n      hasError = true;\n    }\n\n    if (thumbnail) {\n      ownURL(nextSrc);\n    }\n\n    if (previousSrc !== nextSrc) {\n      releaseOwnedURL(previousSrc);\n    }\n\n    if (blurBackground && !blurImageURL && nextSrc) {\n      blurImageURL = nextSrc;\n    }\n\n    updatingSrc = false;\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    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      if (failed) {\n        // Show the fallback icon rather than an empty tile that never finishes its transition\n        hasError = true;\n\n        return;\n      }\n    }\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    loaded = true;\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 (destroyed) {\n          revokeBlobURLIfNeeded(url);\n\n          return;\n        }\n\n        blurImageURL = url;\n        ownURL(blurImageURL);\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  $effect(() => {\n    currentAsset = asset;\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      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  // eslint-disable-next-line arrow-body-style\n  onMount(() => {\n    // Clean up\n    return () => {\n      destroyed = true;\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\n      // outlives 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 (mediaElement) {\n        removeVisibilityResolver(mediaElement);\n      }\n    };\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","<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\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 {\n    /* eslint-disable prefer-const */\n    asset,\n    /* eslint-enable prefer-const */\n  } = $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   * Asset the details were last requested for. The panel stays mounted while the focus moves from\n   * one asset to another, so a slow lookup for an asset focused earlier must not overwrite the\n   * details of the one focused now.\n   * @type {ExternalAsset | undefined}\n   */\n  let requestedAsset;\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    requestedAsset = _asset;\n    details = {};\n    usedEntries = undefined;\n\n    try {\n      const _details = await getExternalAssetDetails(_asset);\n\n      if (requestedAsset !== _asset) {\n        return;\n      }\n\n      details = _details;\n    } catch {\n      // The file could not be loaded; leave the media info out\n    }\n\n    const _usedEntries = await getExternalAssetUsedEntries(_asset);\n\n    if (requestedAsset === _asset) {\n      usedEntries = _usedEntries;\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","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. Inline styles are kept, because the syntax highlighting relies on them, but\n * filtered by {@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', 'input', 'button', 'textarea', 'select', 'option'],\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.\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  '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: 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","<!--\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 {\n    /* eslint-disable prefer-const */\n    text,\n    name,\n    /* eslint-enable prefer-const */\n  } = $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","<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 {\n    /* eslint-disable prefer-const */\n    message,\n    backPath = '/collections',\n    /* eslint-enable prefer-const */\n  } = $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","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 * Normalize the given string for search value comparison. Since `transliterate` is slow, we only\n * apply basic normalization.\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  return value\n    .normalize('NFD')\n    .replace(/\\p{Diacritic}/gu, '')\n    .toLocaleLowerCase();\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 { groupItems, sortItemsByKey } from '$lib/services/common/view';\nimport { getNormalizedValueCache, hasMatch, normalize } from '$lib/services/search/util';\nimport { 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  // Exclude the file extension when sorting by name to sort numbered files properly, e.g.\n  // `hero.png`, `hero-1.png`, `hero-2.png` instead of `hero-1.png`, `hero-2.png`, `hero.png`\n  return asset.fileName.split('.')[0];\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: dirPath.split('/').at(-1) || 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 * 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  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  import { isTextFileType } from '@sveltia/utils/file';\n  import mime from 'mime';\n\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 TextPreview from '$lib/components/assets/list/text-preview.svelte';\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import { goBack, goto } from '$lib/services/app/navigation';\n  import {\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 { listedExternalAssets } from '$lib/services/assets/external/view';\n  import { isMediaKind } from '$lib/services/assets/kinds';\n  import { getAdjacentAssets } from '$lib/services/assets/view';\n  import { env } from '$lib/services/user/env.svelte';\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(listedExternalAssets.current, ({ id }) => id === asset?.id),\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        buttonDescription={_('delete_assets', { values: { count: 1 } })}\n        dialogDescription={_('confirm_deleting_this_asset')}\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 if isMediaKind(kind)}\n      <AssetPreview\n        {kind}\n        src={downloadURL}\n        blurBackground={['image', 'video'].includes(kind)}\n        checkerboard={kind === 'image'}\n        alt={kind === 'image' ? fileName : undefined}\n        controls={['audio', 'video'].includes(kind)}\n      />\n    {:else if type === 'application/pdf'}\n      <iframe src={downloadURL} title={fileName} sandbox=\"allow-scripts\"></iframe>\n    {:else if type && isTextFileType(type)}\n      {#await fetchExternalAssetBlob(asset).then((blob) => blob.text())}\n        <EmptyState>\n          <span role=\"alert\">{_('loading')}</span>\n        </EmptyState>\n      {:then text}\n        <TextPreview {text} name={fileName} />\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  {/snippet}\n  {#snippet info()}\n    {#if asset}\n      <InfoPanel {asset} />\n    {/if}\n  {/snippet}\n</DetailsOverlay>\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 { isObject } from '@sveltia/utils/object';\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  } 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 {\n    /* eslint-disable prefer-const */\n    fieldConfig,\n    kind,\n    multiple = false,\n    hidden = false,\n    onSelect,\n    /* eslint-enable prefer-const */\n  } = $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 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: libOptions.config.folder?.path ?? '',\n        resource_type: kind ?? 'raw',\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: { secure_url: string; derived?: { secure_url: string }[] }[] }} assets The\n   * 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        return { url: /** @type {string} */ (url.split('/').pop()) };\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.\n   * @param {MessageEvent} event The message event.\n   */\n  const onMessage = ({ origin, data }) => {\n    if (origin !== FRAME_ORIGIN) {\n      return;\n    }\n\n    if (typeof data === 'string') {\n      try {\n        data = JSON.parse(data);\n      } catch {\n        return;\n      }\n    }\n\n    if (!isObject(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 === 'consoleLoaded') {\n      consoleLoaded.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","<!--\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","<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    /* eslint-disable prefer-const */\n    files = $bindable([]),\n    transformedFileMap = undefined,\n    removable = true,\n    showThumbnail = true,\n    /* eslint-enable prefer-const */\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","<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 { 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    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\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    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    event.preventDefault();\n\n    if (disabled || !event.dataTransfer) {\n      return;\n    }\n\n    dragging = false;\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) {\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","<!--\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 {\n    /* eslint-disable prefer-const */\n    children = undefined,\n    ...rest\n    /* eslint-enable prefer-const */\n  } = $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 {Snippet} [children] Slot content.\n   */\n\n  /** @type {Props & Record<string, any>} */\n  let {\n    /* eslint-disable prefer-const */\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    children = undefined,\n    ...rest\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div role=\"none\" class=\"{viewType}-view\">\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) {\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  .list-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</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    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\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 { 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   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\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<!-- @todo Add support for drag to move. -->\n\n<GridRow\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 {\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 { browsingExternalFolders } from '$lib/services/assets/external/view';\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 {number} index Index of the asset in the list.\n   * @property {ViewType} viewType View type.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    asset,\n    index,\n    viewType,\n    /* eslint-enable prefer-const */\n  } = $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  /**\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    const service = selectedCloudService.current;\n\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={index}\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/>\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 { 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   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    subfolder,\n    rowIndex,\n    viewType,\n    hasCheckboxColumn = false,\n    onOpen,\n    onFocus = undefined,\n    onRename = undefined,\n    onDelete = undefined,\n    actionsDisabled = false,\n    /* eslint-enable prefer-const */\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  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    /* 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 {\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 {\n    /* eslint-disable prefer-const */\n    subfolder,\n    rowIndex,\n    viewType,\n    /* eslint-enable prefer-const */\n  } = $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  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 {\n    /* eslint-disable prefer-const */\n    label = undefined,\n    disabled = false,\n    onclick,\n    /* eslint-enable prefer-const */\n  } = $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 {\n    /* eslint-disable prefer-const */\n    label = undefined,\n    /* eslint-enable prefer-const */\n  } = $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","import { _ } from '@sveltia/i18n';\nimport { sanitize } from 'isomorphic-dompurify';\n\nimport { LINK_SANITIZE_OPTIONS } from '$lib/services/utils/string';\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","import { prefs } from '$lib/services/user/prefs.svelte';\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 * 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  @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 { getServiceDescription } 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 {\n    /* eslint-disable prefer-const */\n    serviceProps,\n    error = undefined,\n    onAuth = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const {\n    serviceType = 'stock_assets',\n    serviceId = '',\n    serviceLabel = '',\n    authType = 'api_key',\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: _(`cloud_storage.${serviceId}.auth_key_label`, {\n                default: _(`cloud_storage.auth.${authType}.key_label`),\n              }),\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","<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\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  /**\n   * Row index of each listed asset, counted across the groups rather than within each one, as the\n   * rows of every group make up one grid. The subfolders come first, so they offset the index.\n   */\n  const rowIndexMap = $derived(\n    new Map(\n      Object.values(externalAssetGroups.current)\n        .flat(1)\n        .map(({ id }, index) => [id, index + subfolderCount]),\n    ),\n  );\n\n  /**\n   * Get the row index of a listed asset.\n   * @param {ExternalAsset} asset Asset.\n   * @returns {number} 0-based index.\n   */\n  const getRowIndex = (asset) => /** @type {number} */ (rowIndexMap.get(asset.id));\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      {#await sleep() then}\n        <AssetListItem {asset} index={getRowIndex(asset)} {viewType} />\n      {/await}\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 {\n    /* eslint-disable prefer-const */\n    name,\n    path = undefined,\n    folderCount = undefined,\n    assetCount,\n    /* eslint-enable prefer-const */\n  } = $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  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  import { Dialog, TextInput } from '@sveltia/ui';\n\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} [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    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    title,\n    okLabel,\n    description,\n    name = '',\n    takenNames,\n    onSubmit,\n    onClose = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const componentId = $props.id();\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<Dialog\n  {title}\n  bind:open\n  {okLabel}\n  okDisabled={!!error || unchanged}\n  onOk={() => {\n    onSubmit(formatSubfolderName(newName));\n  }}\n  {onClose}\n>\n  <p>{description}</p>\n  <div role=\"none\">\n    <TextInput\n      dir=\"auto\"\n      flex\n      bind:value={newName}\n      ariaLabel={_('new_folder_name')}\n      {invalid}\n      aria-errormessage=\"{componentId}-error\"\n      oninput={() => {\n        nameEdited = true;\n      }}\n    />\n  </div>\n  <div role=\"none\" class=\"error\" id=\"{componentId}-error\">\n    {#if invalid}\n      {_(`new_folder_error.${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  .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  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 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   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    disabled = false,\n    onclick,\n    /* eslint-enable prefer-const */\n  } = $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={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","<!--\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 {\n    /* eslint-disable prefer-const */\n    path = undefined,\n    disabled = false,\n    state = undefined,\n    /* eslint-enable prefer-const */\n  } = $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  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 {\n    /* eslint-disable prefer-const */\n    items,\n    class: className = '',\n    /* eslint-enable prefer-const */\n  } = $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  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 {\n    /* eslint-disable prefer-const */\n    rootLabel,\n    subfolderNames = [],\n    onBrowse,\n    actions = undefined,\n    fab = undefined,\n    /* eslint-enable prefer-const */\n  } = $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        buttonDescription={_('delete_selected_assets', { values: { count: assets.length } })}\n        dialogDescription={_(\n          // Every asset listed in the view, as in a repository folder\n          assets.length > 1 && assets.length === listedExternalAssets.current.length\n            ? 'confirm_deleting_all_assets'\n            : 'confirm_deleting_selected_assets',\n          { values: { count: assets.length } },\n        )}\n      />\n    {/if}\n    {#if service.rename || service.replace}\n      <EditOptionsButton {asset} />\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  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    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    oldExtension = undefined,\n    newExtension = undefined,\n    okLabel = '',\n    onOk = undefined,\n    onCancel = undefined,\n    ...restProps\n    /* eslint-enable prefer-const */\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  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 { Dialog, TextInput } from '@sveltia/ui';\n  import { getPathInfo } from '@sveltia/utils/file';\n  import { tick } from 'svelte';\n\n  import FileExtensionChangeDialog from '$lib/components/assets/shared/file-extension-change-dialog.svelte';\n  import { formatFileName } 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 {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    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    name,\n    otherNames,\n    usedEntryCount = 0,\n    blockedMessage = undefined,\n    slugificationEnabled = false,\n    onRename,\n    onClose = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const componentId = $props.id();\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  /** Name the file will be renamed to, which may be different from the entered name. */\n  const finalName = $derived(\n    slugificationEnabled && trimmedName\n      ? formatFileName(trimmedName, { slugificationEnabled })\n      : trimmedName,\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.by(() => {\n    if (!trimmedName) return 'empty';\n    if (trimmedName.includes('/')) return 'character';\n    if (otherNames.includes(finalName)) return 'duplicate';\n    return undefined;\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<Dialog\n  title={_('rename_x', { values: { name } })}\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>\n  {#if blockedMessage}\n    <p role=\"alert\">{blockedMessage}</p>\n  {:else}\n    <p>\n      {_('enter_new_name_for_asset', { values: { count: usedEntryCount } })}\n    </p>\n  {/if}\n  <div role=\"none\">\n    <TextInput\n      dir=\"auto\"\n      bind:value={newName}\n      bind:element={inputElement}\n      flex\n      disabled={!!blockedMessage}\n      {invalid}\n      aria-errormessage=\"{componentId}-error\"\n    />\n  </div>\n  {#if !invalid && finalName !== trimmedName}\n    <div role=\"status\" class=\"note\">\n      {_('file_will_be_saved_as', { values: { name: finalName } })}\n    </div>\n  {/if}\n  <div role=\"none\" class=\"error\" id=\"{componentId}-error\">\n    {#if invalid}\n      {_(`enter_new_name_for_asset_error.${error}`)}\n    {/if}\n  </div>\n</Dialog>\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\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  Rename Asset dialog for an asset on a cloud storage service. Unlike the dialog for repository\n  assets, there are no entries to update, and the new name is checked against the other assets in\n  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\n  const asset = $derived(renamingExternalAsset.current);\n  // Open while there’s an asset to act on. Closing the dialog writes `open` back, and the asset is\n  // let go of once the dialog has closed\n  let open = $derived(!!asset);\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  /**\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  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.\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 {\n    listedExternalAssets,\n    listedExternalSubfolders,\n  } from '$lib/services/assets/external/view';\n  import { getTakenNames } from '$lib/services/assets/subfolders';\n\n  const subfolder = $derived(renamingExternalSubfolder.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 ? getExternalSubfolderAssets(subfolder.path).length : 0);\n  /* v8 ignore stop */\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_external_folder', { values: { count: assetCount } })}\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 {\n    /* eslint-disable prefer-const */\n    asset,\n    children,\n    fallback = undefined,\n    /* eslint-enable prefer-const */\n  } = $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","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Menu, MenuButton, MenuItemCheckbox, 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 } 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    /* eslint-disable prefer-const */\n    currentView,\n    'aria-controls': ariaControls,\n    label = '',\n    disabled = false,\n    multiple = false,\n    noneLabel = '',\n    filters = [],\n    /* eslint-enable prefer-const */\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        <MenuItemRadio\n          label={noneLabel || _('sort_keys.none')}\n          checked={!currentView.current.filter}\n          onSelect={() => {\n            currentView.current = {\n              ...currentView.current,\n              filter: undefined,\n            };\n          }}\n        />\n        {#each filters as filter (getConditionKey(getViewConditions(filter)))}\n          {@const { label: _label } = filter}\n          {@const conditions = getViewConditions(filter)}\n          {@const key = getConditionKey(conditions)}\n          <MenuItemRadio\n            label={_label}\n            checked={!!currentView.current.filter &&\n              getConditionKey(currentView.current.filter) === key}\n            onSelect={() => {\n              currentView.current = {\n                ...currentView.current,\n                filter: conditions,\n              };\n            }}\n          />\n        {/each}\n      {/if}\n    </Menu>\n  {/snippet}\n</MenuButton>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Divider, Menu, MenuButton, MenuItem, MenuItemRadio } from '@sveltia/ui';\n\n  import {\n    getCollapsibleGroupNames,\n    getConditionKey,\n    getViewConditions,\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    /* eslint-disable prefer-const */\n    currentView,\n    'aria-controls': ariaControls,\n    label = '',\n    disabled = false,\n    noneLabel = '',\n    groups = [],\n    groupNames = [],\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const collapsibleGroupNames = $derived(getCollapsibleGroupNames(groupNames));\n  const canExpandAll = $derived(\n    collapsibleGroupNames.some((name) => isGroupCollapsed(currentView.current, name)),\n  );\n  const canCollapseAll = $derived(\n    collapsibleGroupNames.some((name) => !isGroupCollapsed(currentView.current, name)),\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      <MenuItemRadio\n        label={noneLabel || _('sort_keys.none')}\n        checked={!currentView.current.group}\n        onSelect={() => {\n          currentView.current = {\n            ...currentView.current,\n            group: null,\n          };\n        }}\n      />\n      {#each groups as group (getConditionKey(getViewConditions(group)))}\n        {@const { label: _label } = group}\n        {@const conditions = getViewConditions(group)}\n        {@const key = getConditionKey(conditions)}\n        <MenuItemRadio\n          label={_label}\n          checked={!!currentView.current.group &&\n            getConditionKey(currentView.current.group) === key}\n          onSelect={() => {\n            currentView.current = {\n              ...currentView.current,\n              group: conditions,\n            };\n          }}\n        />\n      {/each}\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          );\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          );\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 {\n    /* eslint-disable prefer-const */\n    allItems,\n    selectedItems,\n    /* eslint-enable prefer-const */\n  } = $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","import { isObject } from '@sveltia/utils/object';\n\nimport { getViewConditions } from '$lib/services/common/view';\n\n/**\n * @import { FilteringConditions, GroupingConditions, SortOrder } from '$lib/types/private';\n * @import { 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 * Parse custom sortable fields configuration.\n * @param {string[] | SortableFields} customSortableFields Custom sortable fields configuration.\n * @returns {{ keys: string[], defaultKey?: string, defaultOrder?: SortOrder }} Parsed sortable\n * 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\n  if (isValidArray(customSortableFields)) {\n    return { keys: 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 { _ } 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 { getField } from '$lib/services/contents/entry/fields';\nimport { isNumeric } from '$lib/services/utils/number';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { InternalEntryCollection, SortingConditions, SortOrder } from '$lib/types/private';\n * @import { Field, FieldKeyPath, NumberField } 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: 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 {{ keys: string[], defaultKey?: string, defaultOrder?: SortOrder }} Parsed sortable\n * 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[], default: SortingConditions }} A list of sortable fields and default\n * 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\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');\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    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  if (key in SPECIAL_SORT_KEY_TYPES) {\n    return SPECIAL_SORT_KEY_TYPES[key];\n  }\n\n  if (fieldConfig?.widget === 'boolean') {\n    return Boolean;\n  }\n\n  if (fieldConfig?.widget === 'number') {\n    const { value_type: valueType = 'int' } = /** @type {NumberField} */ (fieldConfig);\n\n    if (valueType === 'int' || valueType === 'float') {\n      return Number;\n    }\n  }\n\n  return String;\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\n        // @ts-ignore Hidden field doesn’t have `label` property\n        return getField({ collectionName: collection.name, keyPath })?.label || _key;\n      })\n      .filter(Boolean)\n      .join(' – ');\n  }\n\n  // @ts-ignore Hidden field doesn’t have `label` property\n  return collection.fields?.find(({ name }) => name === key)?.label || key;\n};\n\n/**\n * List of available sort keys for the selected entry collection. `getSortKeyLabel()` may return a\n * localized label, and it reads the current app locale, so the list is also recomputed when the\n * locale changes.\n * @type {{ readonly current: { key: string, label: string }[] }}\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 } = getSortConfig({\n    collection,\n    isCommitAuthorAvailable: _allEntries.some((entry) => !!entry.commitAuthor),\n    isCommitDateAvailable: _allEntries.some((entry) => !!entry.commitDate),\n  });\n\n  return keys.map((key) => ({ key, label: getSortKeyLabel({ collection, key }) }));\n});\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 { 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    /* eslint-disable prefer-const */\n    currentView,\n    'aria-controls': ariaControls,\n    label = '',\n    disabled = false,\n    sortKeys = [],\n    collectionName = undefined,\n    /* eslint-enable prefer-const */\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' && sortKeys.length > 1}\n          <Divider />\n        {/if}\n      {/each}\n    </Menu>\n  {/snippet}\n</MenuButton>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, SelectButton, SelectButtonGroup } from '@sveltia/ui';\n\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import { AssetListView, EntryListView, SelectAssetsView } 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   */\n\n  /** @type {Props & Record<string, any>} */\n  let {\n    /* eslint-disable prefer-const */\n    disabled = false,\n    currentView,\n    ...rest\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const isGridView = $derived(currentView.current.type === 'grid');\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  {#if env.isLargeScreen}\n    <SelectButtonGroup {disabled} ariaLabel={_('switch_view')} {...rest}>\n      <SelectButton\n        {disabled}\n        selected={!isGridView}\n        variant=\"ghost\"\n        iconic\n        aria-label={_('list_view')}\n        onSelect={() => {\n          currentView.current = { ...currentView.current, type: 'list' };\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"format_list_bulleted\" />\n        {/snippet}\n      </SelectButton>\n      <SelectButton\n        {disabled}\n        selected={isGridView}\n        variant=\"ghost\"\n        iconic\n        aria-label={_('grid_view')}\n        onSelect={() => {\n          currentView.current = { ...currentView.current, type: 'grid' };\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"grid_view\" />\n        {/snippet}\n      </SelectButton>\n    </SelectButtonGroup>\n  {:else}\n    <Button\n      {disabled}\n      variant=\"ghost\"\n      iconic\n      aria-label={_(isGridView ? 'switch_to_list_view' : 'switch_to_grid_view')}\n      onclick={() => {\n        currentView.current = { ...currentView.current, type: isGridView ? 'list' : 'grid' };\n      }}\n    >\n      {#snippet startIcon()}\n        <Icon name={isGridView ? 'format_list_bulleted' : 'grid_view'} />\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","<!--\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    /* eslint-disable prefer-const */\n    allItems,\n    selectedItems,\n    totalCount,\n    sortKeys,\n    groups = [],\n    groupNames = [],\n    searchTerms = undefined,\n    /* eslint-enable prefer-const */\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    <Divider orientation=\"vertical\" />\n    <Button\n      variant=\"ghost\"\n      iconic\n      disabled={!hasListedAssets}\n      pressed={!!currentView.current.showInfo}\n      aria-controls=\"asset-info\"\n      aria-expanded={!!currentView.current.showInfo}\n      aria-label={_(currentView.current.showInfo ? 'hide_info' : 'show_info')}\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","<script>\n  import { _ } from '@sveltia/i18n';\n  import { AlertDialog } from '@sveltia/ui';\n\n  import { formatSize } from '$lib/services/assets/file-size';\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   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    maxSize,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  let open = $state(false);\n  /** @type {string[]} */\n  let oversizedFileNames = $state.raw([]);\n  /** @type {string[]} */\n  let invalidFileNames = $state.raw([]);\n\n  /**\n   * Show the dialog if any files were rejected. Nothing happens if both lists are empty.\n   * @param {RejectedFileNames} args Names of the rejected files.\n   */\n  export const report = (args) => {\n    if (!args.oversizedFileNames.length && !args.invalidFileNames.length) {\n      return;\n    }\n\n    ({ oversizedFileNames, invalidFileNames } = args);\n    open = true;\n  };\n\n  /**\n   * The dialog covers both rejection reasons, 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(\n    oversizedFileNames.length && invalidFileNames.length\n      ? _('assets_dialog.rejected_files.title')\n      : invalidFileNames.length\n        ? _('assets_dialog.invalid_file.title')\n        : _('assets_dialog.large_file.title'),\n  );\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</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","<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    /* eslint-disable prefer-const */\n    primaryToolbar = undefined,\n    secondaryToolbar = undefined,\n    mainContent = undefined,\n    secondarySidebar = undefined,\n    ...rest\n    /* eslint-enable prefer-const */\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","<!--\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, 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    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    <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 {\n  announcedPageStatus,\n  encodeRoutePath,\n  goto,\n  parseLocation,\n} 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';\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 * 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(encodeRoutePath(`/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: assetId.split('/').pop() },\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\n    goto('/assets/-/all');\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  }\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 folder can have a dot in\n  // its name too, e.g. `v1.2`. Browse the folder if there is no asset at the path\n  if (fileName) {\n    const fullPath = `${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  overlaidAsset.current = allAssets.current.find(\n    (asset) => asset.path === `${folderPath}/${fileName}`,\n  );\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 { canPreviewAsset } from '$lib/services/assets/kinds';\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 {\n    /* eslint-disable prefer-const */\n    asset,\n    viewType,\n    /* eslint-enable prefer-const */\n  } = $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  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 { encodeRoutePath, goto } from '$lib/services/app/navigation';\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\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 {\n    /* eslint-disable prefer-const */\n    subfolder,\n    rowIndex,\n    viewType,\n    /* eslint-enable prefer-const */\n  } = $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(encodeRoutePath(`/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  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 {\n    /* eslint-disable prefer-const */\n    label = undefined,\n    /* eslint-enable prefer-const */\n  } = $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  import { sleep } from '@sveltia/utils/misc';\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      {#await sleep() then}\n        <AssetListItem {asset} {viewType} />\n      {/await}\n    {/key}\n  {/snippet}\n  {#snippet emptyAction()}\n    <UploadAssetsButton label={_('upload_assets')} />\n  {/snippet}\n</AssetListContainer>\n","import { _ } from '@sveltia/i18n';\n\nimport { lockedBranch } from '$lib/services/backends/branch-access';\nimport { cmsConfig } from '$lib/services/config/state';\nimport { getPublishMode } from '$lib/services/workflow/config';\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 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 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  getPublishMode({ cmsConfig: cmsConfig.current, collection }) !== 'editorial_workflow';\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}) or because the signed-in user can’t push to the\n * configured branch (see {@link isLockedByBranch}).\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);\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. 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 && isReadonly({ collection: draft.collection, collectionFile: draft.collectionFile });\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  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 { getField } from '$lib/services/contents/entry/fields';\nimport { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\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.\n * @param {GetFieldArgs} args Arguments for the {@link 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 { keyPath } = args;\n\n  if (!keyPath.includes('.')) {\n    return undefined;\n  }\n\n  const fieldConfig = getField({ ...args, keyPath: keyPath.replace(PAIR_KEY_PATH_REGEX, '') });\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.\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      key.slice(prefix.length),\n      content[key],\n    ])\n  );\n};\n\n/**\n * Replace the key-value pairs stored in the given flattened content.\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}.${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 } 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 * @returns {boolean} Whether any pairs have been reordered.\n */\nexport const isPairOrderModified = ({ draft, isRealKey }) => {\n  const { collectionName, fileName, isIndexFile, originalValues, currentValues } = draft;\n\n  return Object.entries(currentValues).some(([locale, currentValueMap]) => {\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 } from '@sveltia/utils/object';\nimport { stripSlashes } from '@sveltia/utils/string';\nimport equal from 'fast-deep-equal';\n\nimport { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\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 = /\\.__sc_\\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 { EntryDraft, FlattenedEntryContent, LocaleContentMap } 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    [...(keyPath in valueMap ? [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 * Compare the original and current values of every locale in the draft.\n * @param {LocaleContentMap} originalValues Original values.\n * @param {LocaleContentMap} currentValues Current values.\n * @returns {boolean} Whether the values differ.\n */\nconst areValuesModified = (originalValues, currentValues) => {\n  const currentLocales = Object.keys(currentValues);\n\n  if (currentLocales.length !== Object.keys(originalValues).length) {\n    return true;\n  }\n\n  return currentLocales.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    originalValues,\n    currentValues,\n  } = draft;\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(originalValues, currentValues) ||\n    // Reordering the pairs of a KeyValue field changes no value, only the order they are saved in\n    isPairOrderModified({ draft, isRealKey })\n  );\n};\n","import { isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { MULTI_VALUE_FIELD_TYPES } from '$lib/services/contents/fields';\n\n/**\n * @import {\n * Field,\n * FieldKeyPath,\n * FieldWithSubFields,\n * FieldWithTypes,\n * ListFieldWithSubField,\n * } 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  const isList = fieldType === 'list';\n\n  keyPathList.push(keyPath);\n\n  if (isList || fieldType === 'object') {\n    const { fields: subFields } = /** @type {FieldWithSubFields} */ (field);\n    const { types, typeKey = 'type' } = /** @type {FieldWithTypes} */ (field);\n\n    if (subFields) {\n      subFields.forEach((subField) => {\n        parseField({\n          field: subField,\n          keyPath: isList ? `${keyPath}.*.${subField.name}` : `${keyPath}.${subField.name}`,\n          keyPathList,\n        });\n      });\n    } else if (types) {\n      keyPathList.push(isList ? `${keyPath}.*.${typeKey}` : `${keyPath}.${typeKey}`);\n\n      types.forEach((type) => {\n        type.fields?.forEach((subField) => {\n          parseField({\n            field: subField,\n            keyPath: isList ? `${keyPath}.*.${subField.name}` : `${keyPath}.${subField.name}`,\n            keyPathList,\n          });\n        });\n      });\n    } else if (isList) {\n      const { field: subField } = /** @type {ListFieldWithSubField} */ (field);\n\n      if (subField) {\n        parseField({\n          field: subField,\n          keyPath: `${keyPath}.*`,\n          keyPathList,\n        });\n      } else {\n        keyPathList.push(`${keyPath}.*`);\n      }\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 { FlattenedEntryContent, InternalCollection } 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  if (collection?._type !== 'entry') {\n    return undefined;\n  }\n\n  const { aliases_field: aliasesField = DEFAULT_ALIASES_KEY } = collection;\n  // `false` and an empty string both disable the feature\n  const aliasesKey = aliasesField === true ? DEFAULT_ALIASES_KEY : aliasesField || 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 (!aliasesKey || fields.some(({ name }) => name === aliasesKey)) {\n    return undefined;\n  }\n\n  return aliasesKey;\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) && /^\\d+$/.test(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 { 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 { parseDateTimeConfig } from '$lib/services/contents/fields/date-time/config';\nimport { resolveFileConfig } from '$lib/services/contents/file/config';\nimport { TOML_FORMATS } from '$lib/services/contents/file/constants';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { isValueEmpty, unflattenKeys } 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, 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 * 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    const tomlDate = new TomlDate(value);\n\n    // Ignore invalid dates to prevent serialization errors. This occurs when the field is optional\n    // and no value is provided, such as an empty string. In such cases, save nothing. We cannot\n    // save `null` because TOML doesn’t support it, and an empty string may not be the expected\n    // value for a date field.\n    value = tomlDate.isValid() ? tomlDate : undefined;\n  }\n\n  if (\n    omitEmptyOptionalFields &&\n    field &&\n    !isFieldRequired({ fieldConfig: field, locale }) &&\n    isValueEmpty(value)\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  } 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 * 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 {FlattenedEntryContent} args.valueMap Flattened entry content.\n * @param {string} [args.canonicalSlugKey] Property name of a canonical slug.\n * @param {string} [args.aliasesKey] Property name of the entry’s URL aliases. Placed right after\n * the canonical slug, 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.\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 → aliases → order → configured fields → remainder.\n */\nconst finalizeContent = ({\n  collectionName,\n  fileName,\n  fields,\n  locale,\n  valueMap,\n  canonicalSlugKey,\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\n  // Add the slug first\n  if (canonicalSlugKey && canonicalSlugKey in unsortedMap) {\n    copyProperty({ ...copyArgs, key: canonicalSlugKey });\n  }\n\n  // Add the URL aliases next so they appear at the top of the output, close to the slug they relate\n  // to. The property normally holds a list, which is flattened into indexed key paths, but copy the\n  // property itself too in case the user stores something else in it\n  if (aliasesKey) {\n    if (aliasesKey in unsortedMap) {\n      copyProperty({ ...copyArgs, key: aliasesKey });\n    }\n\n    getAliasKeyPaths(unsortedMap, aliasesKey).forEach((keyPath) => {\n      copyProperty({ ...copyArgs, key: keyPath });\n    });\n  }\n\n  // Add the order field next so it appears at the top of the output\n  if (orderKey && orderKey in unsortedMap) {\n    copyProperty({ ...copyArgs, key: orderKey });\n  }\n\n  /**\n   * Copy a KeyValue field’s key-value pairs to the sorted property map.\n   * @param {string} keyPath Concrete key path of the field.\n   * @param {Field} field Field configuration.\n   */\n  const copyKeyValueField = (keyPath, field) => {\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\n      // with 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\n    // it can’t make a difference to the output. `copyProperty()` still omits the empty object if\n    // the field is optional and the `omit_empty_optional_fields` output option is enabled\n    if (!pairKeyPaths.length) {\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      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 {string} keyPath Concrete key path of the field.\n   * @param {Field} field Field configuration.\n   */\n  const copyOpaqueField = (keyPath, field) => {\n    if (keyPath in unsortedMap) {\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  // Move the listed properties to a new object\n  createKeyPathList(fields).forEach((keyPath) => {\n    const field = getField({ ...getFieldArgs, keyPath });\n\n    // A KeyValue field is handled on its own, even if it holds a value at its own key path, which\n    // is the placeholder of an empty field\n    if (field?.widget === 'keyvalue' && !keyPath.includes('*')) {\n      copyKeyValueField(keyPath, field);\n    } else if (field && !keyPath.includes('*') && isOpaqueField(field)) {\n      copyOpaqueField(keyPath, field);\n    } else if (keyPath in unsortedMap) {\n      copyProperty({ ...copyArgs, key: keyPath, field });\n    } else {\n      // Resolve the wildcards in the key path to the concrete key paths of the list items, e.g.\n      // `list.*.title` → `list.0.title`, `list.1.title`. A KeyValue field has no value at its own\n      // key path when it holds pairs, so look for the key paths below it as well\n      const regex = getWildcardKeyPathRegex(keyPath);\n\n      const concreteKeyPaths = new Set(\n        Object.keys(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\n          // key path so that field metadata (e.g. `required`) is available to `copyProperty`\n          const resolvedField = field ?? getField({ ...getFieldArgs, keyPath: concreteKeyPath });\n\n          if (resolvedField?.widget === 'keyvalue') {\n            copyKeyValueField(concreteKeyPath, resolvedField);\n          } else if (resolvedField && isOpaqueField(resolvedField)) {\n            copyOpaqueField(concreteKeyPath, resolvedField);\n          } else if (concreteKeyPath in unsortedMap) {\n            copyProperty({ ...copyArgs, key: concreteKeyPath, field: resolvedField });\n          }\n        });\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 * 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 * @returns {RawEntryContent} Modified and unflattened content.\n */\nexport const serializeContent = ({ draft, locale, valueMap }) => {\n  const { collection, collectionName, collectionFile, fields, isIndexFile } = draft;\n\n  const {\n    _i18n: {\n      canonicalSlug: { key: canonicalSlugKey },\n    },\n  } = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  const { format } = resolveFileConfig({ collection, collectionFile, isIndexFile });\n  const isTomlOutput = TOML_FORMATS.includes(format);\n\n  const content = finalizeContent({\n    collectionName,\n    fileName: collectionFile?.name,\n    fields,\n    locale,\n    valueMap,\n    canonicalSlugKey,\n    aliasesKey: getAliasesKey({ collection, fields }),\n    orderKey: getOrderFieldKey(collection),\n    isIndexFile,\n    isTomlOutput,\n  });\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.\n  if (!isTomlOutput && hasRootField(fields, 'list')) {\n    return content[fields[0].name] ?? [];\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 { isNonEmptyString } from '$lib/services/utils/string';\n\n/**\n * @import { Entry, InternalCollection, InternalCollectionFile } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\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.\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  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(getFieldComments(field.fields, `${keyPath}.`)));\n      }\n\n      return entries;\n    }),\n  );\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 * @returns {Record<string, any>} Serializable content object passed to `formatEntryFile()`.\n */\nexport const buildSingleFileContent = ({ config, entry, draft }) => {\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    });\n  }\n\n  const localeContents = Object.fromEntries(\n    Object.entries(entry.locales)\n      .filter(([, le]) => !!le.content)\n      .map(([locale, le]) => [locale, serializeContent({ draft, locale, valueMap: le.content })]),\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 } from 'yaml';\n\nimport { customFileFormatRegistry } from '$lib/services/api/registries';\nimport { cmsConfig } from '$lib/services/config';\nimport { FRONTMATTER_FORMATS } from '$lib/services/contents/file/constants';\n\n/**\n * @import { Scalar, ToStringOptions } from 'yaml';\n * @import { FileConfig, InternalLocaleCode } from '$lib/types/private';\n * @import {\n * FieldKeyPath,\n * JsonFormatOptions,\n * RawEntryContent,\n * YamlFormatOptions,\n * } from '$lib/types/public';\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  return JSON.stringify(\n    obj,\n    null,\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) => stringifyTOML(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    const comment = comments[keyPath];\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 * 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 { indent_size: indent = 2, indent_sequences: indentSeq = true, quote = 'none' } = options;\n  const { quote: legacyQuote = false } = legacyOptions;\n\n  /** @type {ToStringOptions} */\n  const toStringOptions = {\n    indent,\n    indentSeq,\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  const doc = new Document(obj);\n\n  addYAMLComments(doc.contents, comments);\n\n  return doc.toString(toStringOptions).trim();\n};\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 * @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 }) => {\n  const {\n    format,\n    fmDelimiters,\n    bodyField: { key: bodyKey = 'body', inline: bodyInline = false } = {},\n    yamlQuote = false,\n  } = _file;\n\n  const [sd, ed] = fmDelimiters ?? ['---', '---'];\n  let body = '';\n\n  if (!bodyInline && bodyKey in content) {\n    body = typeof content[bodyKey] === 'string' ? content[bodyKey] : '';\n    delete content[bodyKey];\n  }\n\n  // Support Markdown without a front matter block, particularly for VitePress\n  if (!Object.keys(content).length) {\n    return `${body}\\n`;\n  }\n\n  let head = '';\n\n  if (format === 'frontmatter' || format === 'yaml-frontmatter') {\n    head = formatYAML(content, undefined, { quote: yamlQuote }, comments);\n  } else if (format === 'toml-frontmatter') {\n    head = formatTOML(content);\n  } else if (format === 'json-frontmatter') {\n    head = formatJSON(content);\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\n    // another pair of braces\n    if (sd === '{' && ed === '}') {\n      head = head.slice(1, -1).replace(/^\\n/, '').replace(/\\n$/, '');\n    }\n  } else {\n    throw new Error(`Unsupported front matter format: ${format}`);\n  }\n\n  return `${sd}\\n${head}\\n${ed}\\n${!bodyInline && body ? `\\n${body}\\n` : ''}`;\n};\n\n/**\n * Format raw entry content.\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 * @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 }) => {\n  const { format, yamlQuote = false } = _file;\n  const customFormatter = customFileFormatRegistry.get(format)?.formatter;\n\n  if (customFormatter) {\n    const output = await customFormatter(content);\n\n    if (typeof output !== 'string') {\n      throw new TypeError(\n        `The \\`toFile\\` method registered for the custom “${format}” format must return a string`,\n      );\n    }\n\n    return `${output.trim()}\\n`;\n  }\n\n  if (format === 'raw') {\n    return typeof content.body === 'string' ? `${content.body}\\n` : '';\n  }\n\n  const isYAML = /^ya?ml$/.test(format);\n\n  const isFrontMatter =\n    format === 'frontmatter' || FRONTMATTER_FORMATS.includes(/** @type {any} */ (format));\n\n  if (!isYAML && format !== 'toml' && format !== 'json' && !isFrontMatter) {\n    throw new Error(\n      customFileFormatRegistry.has(format)\n        ? `Entries in the custom “${format}” format can’t be saved, as no \\`toFile\\` method was ` +\n            'registered for it with `CMS.registerCustomFormat()`'\n        : `Entries in the unknown “${format}” format can’t be saved`,\n    );\n  }\n\n  try {\n    if (isYAML) {\n      return `${formatYAML(content, undefined, { quote: yamlQuote }, comments)}\\n`;\n    }\n\n    if (format === 'toml') {\n      return `${formatTOML(content)}\\n`;\n    }\n\n    if (format === 'json') {\n      return `${formatJSON(content)}\\n`;\n    }\n\n    return formatFrontMatter({ content, _file, comments });\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","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 * } 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 * @returns {Promise<string>} Formatted file data.\n */\nexport const formatEntryData = ({ draft, config, _file, entry, locale }) =>\n  formatEntryFile(\n    locale === undefined\n      ? {\n          content: buildSingleFileContent({ config, entry, draft }),\n          _file,\n          comments: getSingleFileComments({ config, fields: draft.fields }),\n        }\n      : {\n          content: serializeContent({ draft, locale, valueMap: entry.locales[locale].content }),\n          _file,\n          comments: getFieldComments(draft.fields),\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 { 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 = ({\n  i18nEnabled,\n  structureMap: { i18nSingleFile, i18nSingleFileDefaultRoot } = /** @type {any} */ ({}),\n}) => !i18nEnabled || !!i18nSingleFile || !!i18nSingleFileDefaultRoot;\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      const [previousSha, data] = await Promise.all([\n        getPreviousSha({ cacheDB, previousPath: currentPath }),\n        formatEntryData({\n          draft,\n          config,\n          _file: getSavedFileConfig({ _file, previousPath: currentPath, path: change.path }),\n          entry,\n          locale,\n        }),\n      ]);\n\n      return { ...change, previousSha, data };\n    }),\n  );\n\n  return /** @type {FileChange[]} */ (changes.filter(Boolean));\n};\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 { 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\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      const response = await fetch(this.url);\n\n      if (!response.ok) {\n        throw new Error(`HTTP ${response.status}`);\n      }\n\n      return encodeBase64(await response.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 { 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 { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { getCollectionFileEntry } from '$lib/services/contents/collection/files';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getEntryOptions } from '$lib/services/contents/fields/relation/helpers';\nimport { getOrCreate, memoizeOnSource } from '$lib/services/utils/cache';\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 { ApiAsset, ApiEntry, FieldKeyPath, GetAsset, RelationField } 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 * @returns {GetAsset} Function that gets asset URLs.\n */\nexport const createGetAsset =\n  ({ entry, collectionName, fileName, files, typedKeyPath, componentNames }) =>\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 };\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 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 expected by\n * Netlify/Decap CMS preview templates and custom field types.\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 */\nexport const getMetaData = ({ locale, getFieldArgs }) => {\n  const { valueMap = {} } = getFieldArgs;\n  /** @type {Record<string, any>} */\n  const metaData = {};\n  /** @type {Map<string, Entry[]>} */\n  const refEntriesCache = new Map();\n\n  Object.entries(valueMap).forEach(([key, value]) => {\n    const keyPath = /** @type {FieldKeyPath} */ (key.replace(/\\.\\d+$/, ''));\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      metaData[keyPath] ??= {};\n      metaData[keyPath][refCollection] ??= {};\n      // The option values are strings, while a value written by hand may be a number, e.g. `1`\n      metaData[keyPath][refCollection][value] = getReferencedEntryLookup(\n        refEntries,\n        locale,\n        /** @type {RelationField} */ (field),\n      ).get(String(value))?.locales[locale]?.content;\n    }\n  });\n\n  return /** @type {import('immutable').MapOf<any>} */ (getImmutable().fromJS(metaData));\n};\n\n/**\n * Build a synthetic entry object with current values for live preview updates.\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,\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 }),\n  };\n};\n","import { getImmutable } from '$lib/services/api/immutable';\nimport { buildPreviewData } from '$lib/services/api/preview-data';\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  const data = buildPreviewData({ draft, locale: /** @type {any} */ (locale) });\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.\n * @param {object} args Arguments.\n * @param {InternalLocaleCode} args.locale Locale code.\n * @param {FieldKeyPath} args.keyPath Field key path.\n */\nexport const unregisterCustomFieldInstance = ({ locale, keyPath }) => {\n  const cacheKey = getCacheKey(locale, keyPath);\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 './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/**\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    new Intl.DateTimeFormat('en-US', { timeZone: inputTimeZone, timeZoneName: 'longOffset' })\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      new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' })\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 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 { getDate, getParser, parseWithFormatFallback } from './parse.js';\nimport { getTimeZoneForStoredValue } from './timezone.js';\n\n/**\n * @import { DateTimeFieldNormalizedProps } from '$lib/types/private';\n * @import { DateTimeField } from '$lib/types/public';\n */\n\ndayjs.extend(dayjsCustomParseFormat);\ndayjs.extend(dayjsLocalizedFormat);\ndayjs.extend(dayjsUTC);\ndayjs.extend(dayjsTimeZone);\n\nconst DATE_ONLY_MATCH_REGEX = /^(?<date>\\d{4}-[01]\\d-[0-3]\\d)\\b/;\nconst TIME_SUFFIX_MATCH_REGEX = /(?:^|T)(?<time>[0-2]\\d:[0-5]\\d)\\b/;\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 * @returns {boolean} `true` if the stored value should be replaced.\n */\nexport const shouldUpdateValue = ({ newValue, currentValue, fieldConfig }) => {\n  if (newValue === undefined || newValue === currentValue) {\n    return false;\n  }\n\n  const newDate = getDate(newValue, fieldConfig);\n  const oldDate = getDate(currentValue, fieldConfig);\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 * 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 * @returns {string | undefined} The final value.\n */\nexport const getCurrentValue = ({ inputValue, currentValue, fieldConfig, timeZone, outputUTC }) => {\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    // When the input is in UTC, parse as UTC; otherwise parse as local (timezone conversion happens\n    // below via `.tz()` or `.utc()`)\n    const parse = getParser(inputTimeZone === 'utc');\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 parsed.format(format);\n    }\n\n    // Apply IANA timezone context first, then optionally convert to UTC\n    if (effectiveTimeZone) {\n      parsed = parsed.tz(effectiveTimeZone, true);\n    }\n\n    if (_outputUTC && inputTimeZone !== 'utc') {\n      parsed = parsed.utc();\n    }\n\n    return parsed.format(format);\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 dayjs.tz(inputValue, timeZone).format('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 * @returns {string} Current date/time.\n */\nexport const getCurrentStorableValue = (\n  fieldConfig,\n  { date = undefined, includeSeconds = false } = {},\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    })\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 * @returns {string | undefined} New value.\n */\nexport const getInputValue = ({ currentValue, fieldConfig, timeZone }) => {\n  const { dateOnly, timeOnly, inputTimeZone, format, outputUTC } = parseDateTimeConfig(fieldConfig);\n  const displayTimeZone = getTimeZoneForStoredValue(currentValue, fieldConfig) ?? timeZone;\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, 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({ value: currentValue, format, parseAsUTC: false });\n\n    return parsed.isValid() ? parsed.format('YYYY-MM-DD') : '';\n  }\n\n  // `currentValue` is always truthy here (the empty-string guard above returned early). When a\n  // custom timezone is active with a format and `output_utc` is `false`, `getDate()` would parse\n  // the stored value as browser-local time (wrong epoch when local ≠ input timezone). Interpret it\n  // as being in the selected timezone using `.tz(tz, true)` instead. Note: the `output_utc: true`\n  // case is handled correctly by `getDate()` via `parseAsUTC`.\n  let dateForParts;\n\n  if (displayTimeZone && format && !outputUTC) {\n    try {\n      const parsed = dayjs(currentValue, format).tz(displayTimeZone, true);\n\n      // `.tz()` returns invalid (without throwing) in rare edge cases; fall through to `??=` below\n      dateForParts = parsed.isValid() ? parsed.toDate() : undefined;\n    } catch {\n      // `.tz()` can throw a RangeError for invalid dates in some dayjs versions\n    }\n\n    dateForParts ??= getDate(currentValue, fieldConfig);\n  } else {\n    dateForParts = getDate(currentValue, fieldConfig);\n  }\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","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 }) => {\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({ currentValue: value, fieldConfig: config, timeZone });\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 { cmsConfig } from '$lib/services/config';\n\n/**\n * @import { TextEditorBlockType, TextEditorInlineType, TextEditorMode } 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:image:`.\n * @type {RegExp}\n */\nexport const COMPONENT_NAME_PREFIX_REGEX = /^.+?:\\w+:/;\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 * The default `buttons` property options.\n * @type {RichTextEditorButtonName[]}\n */\nexport const DEFAULT_BUTTONS = [\n  'bold',\n  'italic',\n  'strikethrough',\n  'code',\n  'link',\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  'quote',\n];\n\n/**\n * Key is a name used in Netlify/Decap CMS, value is a name used in Sveltia UI.\n * @type {Record<RichTextEditorButtonName | 'code-block', TextEditorInlineType |\n * TextEditorBlockType>}\n */\nexport const BUTTON_NAME_MAP = {\n  bold: 'bold',\n  italic: 'italic',\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  quote: 'blockquote',\n  'code-block': 'code-block',\n};\n\n/**\n * Built-in editor component names. `code-block` is a button in Sveltia CMS, but it’s included here\n * for consistency with the Netlify/Decap CMS API.\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 { _ } from '@sveltia/i18n';\n\nimport { 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 { COMPONENT_NAME_PREFIX_REGEX } from '$lib/services/contents/fields/rich-text';\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 * VisibleField,\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.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 { collectionName, fileName, isIndexFile, 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          collectionName,\n          fileName,\n          isIndexFile,\n          // A rich text editor component field is looked up in the component definition\n          componentName: prefix ? extraValueMap[`${prefix}__sc_component_name`] : undefined,\n          keyPath: keyPath.replace(COMPONENT_NAME_PREFIX_REGEX, ''), // Remove component name prefix\n          valueMap,\n        });\n\n        return {\n          keyPath,\n          label: /** @type {VisibleField | undefined} */ (field)?.label || field?.name || '',\n          messages,\n        };\n      })\n  );\n};\n","import { isFieldRequired } from '$lib/services/contents/entry/fields';\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  const hasNumber = 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    (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  let trimValue = 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';\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  const {\n    output_code_only: outputCodeOnly = false,\n    keys: outputKeys = { code: 'code', lang: 'lang' },\n  } = /** @type {CodeField} */ (fieldConfig);\n\n  return !outputCodeOnly && [outputKeys.code, outputKeys.lang].includes(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 {\n    output_code_only: outputCodeOnly = false,\n    keys: outputKeys = { code: 'code', lang: 'lang' },\n  } = 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 = !outputCodeOnly ? valueMap[`${keyPath}.${outputKeys.code}`] : value;\n\n  return { skip: false, keyPath, value: resolvedValue };\n};\n","import { getField } from '$lib/services/contents/entry/fields';\nimport { getPairsFromContent } from '$lib/services/contents/fields/key-value/pairs';\nimport { COMPONENT_NAME_PREFIX_REGEX } 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: _keyPath.replace(COMPONENT_NAME_PREFIX_REGEX, ''), // Remove component name prefix\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  if (required && !pairs.length) {\n    validity.valueMissing = true;\n  } else if (typeof min === 'number' && pairs.length < min) {\n    validity.rangeUnderflow = true;\n  } else if (typeof max === 'number' && pairs.length > max) {\n    validity.rangeOverflow = true;\n  }\n\n  return { skip: false, keyPath: _keyPath, empty: !pairs.length };\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 * } 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","import { isObject } from '@sveltia/utils/object';\n\nimport { formatSummary as formatObjectSummary } from '$lib/services/contents/fields/object/helpers';\n\n/**\n * @import { FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n * @import { 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 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","/**\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 * Regular expression to match a key path relative to its list that is an item index alone.\n */\nconst 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  if (required && !size) {\n    validity.valueMissing = true;\n  } else if (typeof min === 'number' && size < min) {\n    validity.rangeUnderflow = true;\n  } else if (typeof max === 'number' && size > max) {\n    validity.rangeOverflow = true;\n  }\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 && INDEX_REGEX.test(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';\n\n/**\n * @import { EntryDraft, UnpublishedEntry, WorkflowStatus } from '$lib/types/private';\n */\n\n/**\n * Get the current Editorial Workflow status of the entry the given draft is editing. The status can\n * change while the editor stays open — from the status menu, or on the Editorial Workflow page — so\n * it’s read from the store rather than from the draft’s snapshot of the entry.\n * @param {EntryDraft} draft Draft being edited.\n * @returns {WorkflowStatus | undefined} Status, or `undefined` if the entry has no pull request.\n */\nconst getWorkflowStatus = (draft) =>\n  getUnpublishedEntryByDraft(draft)?.workflow.status ??\n  /** @type {UnpublishedEntry | undefined} */ (draft.originalEntry)?.workflow?.status;\n\n/**\n * Check whether the required fields of the given draft have to be filled in for it to be saved.\n * With Editorial Workflow an entry lives in a pull request until it’s published, so one that’s\n * still in the drafting stage can be saved incomplete, and the fields left empty aren’t marked as\n * errors. Anywhere else a save puts the entry straight on the site, and a workflow entry that has\n * moved on from the drafting stage is on 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 */\nexport const isRequiredEnforced = (draft) =>\n  // An entry that has no pull request yet starts as a draft\n  !isWorkflowDraft(draft) || (getWorkflowStatus(draft) ?? 'draft') !== 'draft';\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};\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","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. The value isn’t localized, so every\n * locale gets the same one. A field in a rich text editor component isn’t covered, because its\n * value is stored in the Markdown rather than in the draft’s values; the 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   * Values keyed by field configuration, so a field shared by locales and list items is only\n   * formatted once.\n   * @type {Map<Field, string>}\n   */\n  const valueCache = new Map();\n\n  Object.values(currentValues).forEach((valueMap) => {\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          }),\n        );\n      }\n    });\n  });\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` or its alias\n * `translate`, so the field can be edited in every locale.\n * @param {Field['i18n']} i18n Field-level `i18n` option.\n * @returns {boolean} Result.\n */\nexport const isFieldTranslatable = (i18n) => i18n === true || i18n === 'translate';\n\n/**\n * Check if a field holds a value in every locale, i.e. Its field-level `i18n` option is `true`, its\n * alias `translate` or `duplicate`, where the default locale’s value is copied to other locales.\n * @param {Field['i18n']} i18n Field-level `i18n` option.\n * @returns {boolean} Result.\n */\nexport const isFieldLocalized = (i18n) => isFieldTranslatable(i18n) || i18n === 'duplicate';\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 { 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 { DEFAULT_VALIDITY, finalizeValidity } from '$lib/services/contents/draft/validate/validity';\nimport {\n  getField,\n  getFieldKind,\n  isFieldMultiple,\n  isFieldRequired,\n  LIST_KEY_PATH_REGEX,\n} from '$lib/services/contents/entry/fields';\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 { COMPONENT_NAME_PREFIX_REGEX } from '$lib/services/contents/fields/rich-text';\nimport { isOptionValue } from '$lib/services/contents/fields/select/helpers';\nimport { isFieldI18nDisabled } from '$lib/services/contents/i18n/fields';\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/**\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, collectionName, fileName, collectionFile, files, isIndexFile } = draft;\n  let { keyPath, value } = args;\n\n  /** @type {GetFieldArgs} */\n  const getFieldArgs = {\n    collectionName,\n    fileName,\n    componentName,\n    valueMap,\n    keyPath: keyPath.replace(COMPONENT_NAME_PREFIX_REGEX, ''), // Remove component name prefix\n    isIndexFile,\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 } = (collectionFile ?? collection)._i18n;\n\n  // Skip validation on non-editable fields\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  ) {\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  const required = isFieldRequired({ fieldConfig, locale });\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  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  // 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    relaxEmptyFieldValidity(validity, enforceRequired);\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 { collectionName, fileName, isIndexFile, validities, validationMessages } = draft;\n  const getFieldArgs = { collectionName, fileName, isIndexFile, 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, or is in an item of, are re-validated as well, since their item count may have\n * changed, e.g. `tags` for `tags.3` and `speakers` for `speakers.0.name`. This is a no-op until the\n * entry has been validated once, which normally happens on a save attempt, because no error is\n * 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 */\nexport const revalidateField = ({ draft, locale, keyPath, value, valueMap }) => {\n  const { collectionName, fileName, isIndexFile } = draft;\n\n  revalidateSingleField({ draft, locale, keyPath, value, valueMap });\n\n  [...keyPath.matchAll(LIST_ITEM_INDEX_REGEX)].forEach(({ index }) => {\n    const listKeyPath = keyPath.slice(0, index);\n    const getFieldArgs = { collectionName, fileName, isIndexFile, 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: keyPath.replace(COMPONENT_NAME_PREFIX_REGEX, ''), // Remove component name prefix\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 { collectionName, fileName, isIndexFile } = draft;\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: {\n      collectionName,\n      fileName,\n      isIndexFile,\n      keyPath: keyPath.replace(COMPONENT_NAME_PREFIX_REGEX, ''), // Remove component name prefix\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 = LIST_KEY_PATH_REGEX.test(keyPath)\n    ? keyPath.replace(LIST_KEY_PATH_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 { 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 { 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';\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 * @returns {Record<string, string> | undefined} Date and time parts.\n */\nexport const extractDateTime = ({ dateFieldName, fields, content }) => {\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);\n\n  if (!isValidDate(date)) {\n    return undefined;\n  }\n\n  const { utc, outputUTC } = parseDateTimeConfig(config);\n  const timeZone = utc || outputUTC ? 'UTC' : undefined;\n\n  return getDateTimeParts({ date, timeZone });\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 {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  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 });\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      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 {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  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    locale,\n    slug,\n    entryFilePath,\n    content,\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    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  `${backend.current?.repository?.blobBaseURL}/${entry.locales[locale]?.path}?plain=1`;\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 { 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 { allAssets } from '$lib/services/assets/state';\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 { 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, 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 = defaultLocale in locales ? defaultLocale : Object.keys(locales)[0];\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 };\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:\n * `$effect(() => loadEntryThumbnail(collection, entry, (src) => { thumbnail = src; }))`.\n * @param {InternalEntryCollection} collection Entry’s collection.\n * @param {Entry} entry Entry.\n * @param {(src: string | undefined) => void} onLoad Function called with the thumbnail URL once\n * it’s loaded, and with `undefined` when it’s released, so the image stops pointing at it. It’s not\n * 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    if (thumbnail) {\n      onLoad(undefined);\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/**\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 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.values(locales)\n        .flatMap(({ 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 });\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\n    const entryFolderPaths = new Set(\n      /** @type {string[]} */ (\n        Object.values(entry.locales)\n          .map(({ path }) => getPathInfo(path).dirname)\n          .filter((dirPath) => dirPath !== undefined)\n      ),\n    );\n\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 nested collection, an entry can have others stored beneath it, and each\n       * 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 assets stored alongside the given entry, which are moved or removed with it. Only a\n * collection whose asset folder is entry-relative stores assets with its entries.\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 * The entries of a collection storing all of them in one file share the folder of the file, and an\n * asset there can be used by any of them, so none of the assets belongs to one entry alone. Only\n * the versions the entry has are returned: a file another pull request put at the same path isn’t\n * the entry’s to remove.\n */\nexport const getEntryRelativeAssets = ({ entry, collectionName, fileName }) =>\n  getAssetFolder({ collectionName, fileName })?.entryRelative &&\n  !isArrayFileCollection(getCollection(collectionName))\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","import { isObject } from '@sveltia/utils/object';\nimport { flatten } from 'flat';\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 { user } from '$lib/services/user/account.svelte';\n\n/**\n * @import {\n * Entry,\n * InternalCollection,\n * InternalCollectionFile,\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 */\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  const otherLocales = Object.keys(locales).filter((locale) => locale !== defaultLocale);\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. A\n    // multi-file i18n entry can be missing its default locale file, in which case any locale stands\n    // in rather than the destructuring throwing\n    const { content, path } = locales[defaultLocale] ?? Object.values(locales)[0] ?? {};\n\n    // eslint-disable-next-line no-await-in-loop\n    const 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\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[defaultLocale].content = flatten(map.data);\n\n        otherLocales.forEach((locale) => {\n          if (isObject(map.i18n[locale]?.data)) {\n            locales[locale].content = flatten(map.i18n[locale].data);\n          }\n        });\n      } else {\n        // `map` is always a plain object here (guaranteed by `isMap(updatedMap)` above)\n        locales[defaultLocale].content = flatten(map);\n      }\n    }\n  }\n};\n","import { getPreviewPath } from '$lib/services/contents/entry';\nimport {\n  getAliasesKey,\n  getAliasKeyPaths,\n  removeAliases,\n} from '$lib/services/contents/entry/aliases';\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 * Normalize the given path so it can be used as an alias. Both Hugo and Zola resolve an alias\n * relative to the current page unless it starts with a slash, so make it site-relative.\n * @param {string | undefined} path Path generated from the `preview_path` template.\n * @returns {string | undefined} Normalized path, or `undefined` if the path is not available.\n */\nconst normalizePath = (path) => (path === undefined ? undefined : `/${path.replace(/^\\//, '')}`);\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  const getPreviewPathArgs = { collection, locale };\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 previousPath = normalizePath(\n    getPreviewPath({\n      ...getPreviewPathArgs,\n      slug: originalSlug,\n      path: originalPath,\n      content: originalContent,\n    }),\n  );\n\n  const currentPath = normalizePath(getPreviewPath({ ...getPreviewPathArgs, slug, path, content }));\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 { isObject } from '@sveltia/utils/object';\n\n/**\n * @import { InternalCollection, InternalSlugOptions } 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 */\nexport const getSlugOptions = (collection) => {\n  const {\n    slug,\n    identifier_field: identifierField = 'title',\n    file,\n  } = /** @type {EntryCollection} */ (collection);\n\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 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: stages.includes('update') },\n    localized,\n    hint: options.hint,\n    pattern: options.pattern,\n  };\n};\n","import { fillTemplate } from '$lib/services/common/template';\nimport { DATE_TIME_FIELDS, UUID_TYPES } from '$lib/services/common/template/constants';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { parseTransformations } from '$lib/services/common/transformations';\nimport { getIndexFile } from '$lib/services/contents/collection/entries/index-file';\nimport { getSlugOptions, LEGACY_SLUG_EDITOR_TAG } from '$lib/services/contents/collection/slug';\nimport { getOrCreate } from '$lib/services/utils/cache';\n\n/**\n * @import {\n * EntryDraft,\n * EntryFileMap,\n * EntrySlugVariants,\n * FillTemplateOptions,\n * FlattenedEntryContent,\n * InternalCollection,\n * InternalEntryCollection,\n * LocaleSlugMap,\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 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, currentSlugs, 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: currentSlugs?.[defaultLocale] ?? currentSlugs?._,\n    },\n    locale: defaultLocale,\n    isIndexFile,\n    randomValues: getRandomValues(draft),\n  };\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, currentSlugs, slugEditor } = draft;\n\n  if (collection._type !== 'entry') {\n    return '';\n  }\n\n  const { template, editorRequired } = getSlugOptions(collection);\n  const editorValue = currentSlugs?.[locale] ?? currentSlugs?._;\n\n  if (!templateOnly && !editorRequired && slugEditor[locale] && editorValue?.trim()) {\n    return LEGACY_SLUG_EDITOR_TAG;\n  }\n\n  return template;\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 {boolean} [args.templateOnly] See {@link getSlugTemplate}.\n * @returns {string} Localized slug.\n */\nexport const getLocalizedSlug = ({ draft, locale, localizingKeyPaths, templateOnly = false }) => {\n  const {\n    isNew,\n    collection,\n    collectionFile,\n    originalLocales,\n    currentSlugs,\n    currentValues,\n    files,\n    isIndexFile,\n  } = draft;\n\n  const {\n    _i18n: { defaultLocale },\n  } = collectionFile ?? collection;\n\n  const _slug = currentSlugs?.[locale] ?? currentSlugs?._;\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    return fillTemplate(getSlugTemplate({ draft, locale, templateOnly }), {\n      collection,\n      locale,\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        ...resolveBlobURLs(currentValues[defaultLocale], files),\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      isIndexFile,\n      randomValues: getRandomValues(draft),\n    });\n  }\n\n  return /** @type {string} */ (_slug);\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 */\nconst getLocalizingKeyPaths = (collection) => {\n  const { template, localized } = getSlugOptions(collection);\n  /** @type {Set<string>} */\n  const keyPaths = new Set();\n\n  [...template.matchAll(/{{(.+?)}}/g)].forEach(([, 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: {\n      i18nEnabled,\n      structureMap: { i18nSingleFile, i18nSingleFileDefaultRoot },\n    },\n  } = collection;\n\n  return (\n    // A monolingual collection has only one locale, so there’s nothing to localize\n    i18nEnabled &&\n    !i18nSingleFile &&\n    !i18nSingleFileDefaultRoot &&\n    collection._type === 'entry' &&\n    (getSlugOptions(collection).localized || !!getLocalizingKeyPaths(collection).length)\n  );\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 * @returns {LocaleSlugMap | undefined} Localized slug map.\n */\nexport const getLocalizedSlugs = ({ draft, defaultLocaleSlug, templateOnly = false }) => {\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({ draft, locale, localizingKeyPaths, templateOnly });\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 * @returns {EntrySlugVariants} Slugs.\n */\nexport const getSlugs = ({ draft, templateOnly = false }) => {\n  const { isNew, collection, collectionFile, fileName, currentSlugs, 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  const defaultLocaleSlug =\n    fileName ??\n    (isNew\n      ? fillTemplate(\n          getSlugTemplate({ draft, locale: defaultLocale, templateOnly }),\n          fillSlugOptions,\n        )\n      : /** @type {string} */ (currentSlugs?.[defaultLocale] ?? currentSlugs?._));\n\n  const localizedSlugs = getLocalizedSlugs({ draft, defaultLocaleSlug, templateOnly });\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 { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport {\n  DEFAULT_INDEX_FILE_NAMES,\n  getEntryDirPath,\n  getNestedIndexFileName,\n  isNestedCollection,\n} from '$lib/services/contents/collection/nested';\nimport { hasLocalizedSlugs } from '$lib/services/contents/draft/slugs';\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 at the given path.\n * @param {string} dirPath Folder path relative to the collection folder.\n * @returns {string} Last path segment. An empty string for the collection folder itself.\n */\nexport const getFolderName = (dirPath) => dirPath.slice(dirPath.lastIndexOf('/') + 1);\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) => getFolderName(getEntryDirPath(subPath));\n\n/**\n * Check whether the folders of a nested collection go by a different name in each locale. That’s\n * the case when the entry slugs are localized: a folder is named after the entry it belongs to,\n * which is stored either in it or beside it, so the folder chain above an entry is localized along\n * 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  isNestedCollection(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 {InternalCollection} collection Collection.\n * @returns {Entry[]} Entries.\n */\nconst 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 nested collection. The path editor\n * chooses a folder once, in the default locale, and the folders go by localized names in the other\n * locales, so each locale’s file has to be stored below the localized chain instead. Each folder\n * takes its name from the entry it belongs to, as described in {@link getLocalizedFolderName}. A\n * folder without such an entry, or whose entry lacks the locale, keeps 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 { 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 {\n  getFolderName,\n  getOwnFolderName,\n  localizeDirPath,\n} from '$lib/services/contents/collection/nested/i18n';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { hasLocalizedSlugs } 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 } 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 nested collection,\n * 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([localizeDirPath({ collection, dirPath, 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 : getFolderName(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  return createPath([localizeDirPath({ collection, dirPath, 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 * 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 } = 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        ? fillTemplate(subPath, {\n            collection: entryCollection,\n            locale,\n            content: currentValues[defaultLocale],\n            currentSlug: slug,\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 { getPathInfo } from '@sveltia/utils/file';\nimport equal from 'fast-deep-equal';\n\nimport { getAssetsByDirName } from '$lib/services/assets';\nimport { formatFileName } 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 { fillTemplate } from '$lib/services/common/template';\nimport { getSharedEntryFileName } from '$lib/services/contents/collection/nested';\nimport { createEntryPath } from '$lib/services/contents/draft/save/entry-path';\nimport { getFillSlugOptions } from '$lib/services/contents/draft/slugs';\nimport {\n  createPath,\n  encodeFilePath,\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 * InternalCollection,\n * InternalEntryCollection,\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 * 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 * 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 * Check whether an entry file is the index file that every entry in a nested collection is stored\n * 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 = filePath.slice(filePath.lastIndexOf('/') + 1);\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 * 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 nested collection is an index file, with or without a `path` option\n * getOwnedEntryFolderPath(collection, 'content/pages/about/_index.md') // `index_file: _index`\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('/') ? subPath.split('/').at(-1) : 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 * 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`.\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  return resolvePath(fillTemplateIfNeeded(publicPath, fillSlugOptions));\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      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 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 * savingAssetProps: SavingAsset }} Arguments.\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\n  return {\n    assetFolderPaths,\n    assetNamesInSameFolder: getAssetsByDirName(resolvedInternalPath).map((a) => a.name.normalize()),\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  const {\n    savingAssetProps,\n    assetNamesInSameFolder,\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\n  const dupFile = savingAssetsInSameFolder.find(\n    (f) => f.sha === sha && (!folder.entryRelative || equal(f.folder, folder)),\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\n    fileName = formatFileName(\n      getPendingFileName({ draft, item, defaultLocaleSlug }),\n      replace\n        ? {}\n        : {\n            assetNamesInSameFolder: [\n              ...assetNamesInSameFolder,\n              ...savingAssetsInSameFolder.map((f) => f.name.normalize()),\n            ],\n          },\n    );\n\n    // A replacing file overwrites the existing asset whose name only differs in case, e.g.\n    // `Photo.jpg` and `photo.jpg`, rather than being added next to it, as the two would clash on a\n    // case-insensitive file system\n    const replacedName = replace\n      ? assetNamesInSameFolder.find((name) => name.toLowerCase() === fileName.toLowerCase())\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 { 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 { isNestedCollection } from '$lib/services/contents/collection/nested';\nimport { isArrayFileCollection } from '$lib/services/contents/collection/predicates';\nimport { addAlias } from '$lib/services/contents/draft/save/aliases';\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 { getCanonicalSlug, getFillSlugOptions } from '$lib/services/contents/draft/slugs';\nimport { 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';\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 * } 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 nested collection, where an entry is identified by its\n * path within the collection folder rather than by a bare slug. Linking the localized files by the\n * slug alone would take two entries with the same slug in different folders for one entry once\n * they’re read back from the repository, so it’s the default locale’s sub path 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 || !isNestedCollection(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 field = getField({ ...getFieldArgs, valueMap: content, keyPath });\n\n  const replaceBlobArgs = {\n    draft,\n    defaultLocaleSlug,\n    changes,\n    savingAssets,\n    locale,\n    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      if (file) {\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/**\n * Normalize a field value for saving: remove an undefined value, trim a string, and replace the\n * 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  // Remove leading & trailing whitespace\n  content[keyPath] = value.trim();\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, then\n * normalize each field value.\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\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\n  const {\n    collection,\n    collectionName,\n    collectionFile,\n    fileName,\n    isIndexFile,\n    currentLocales,\n    currentValues,\n    files,\n  } = 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  /** @type {GetFieldArgs} */\n  const getFieldArgs = { collectionName, fileName, keyPath: '', valueMap: {}, isIndexFile };\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        const content = { ...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 * 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 * @returns {EntryFilePlan} Planned change.\n */\nexport const planSingleFileChange = ({ draft, savingEntry }) => {\n  const { collection, isNew, originalEntry, collectionFile } = draft;\n\n  const {\n    _i18n: { defaultLocale },\n  } = collectionFile ?? /** @type {InternalEntryCollection} */ (collection);\n\n  const { slug, path } = savingEntry.locales[defaultLocale];\n  const previousPath = 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 * @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 }) => {\n  const { isNew, originalLocales, currentLocales, originalEntry } = draft;\n  const { slug, path } = savingEntry.locales[locale] ?? {};\n  const previousPath = 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 * @returns {Promise<{ savingEntry: Entry, savingAssets: Asset[], changes: FileChange[] }>} Saving\n * entry, assets and file changes.\n */\nexport const createSavingEntryData = async ({ draft, slugs }) => {\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  const subPath = getSubPath({\n    collection: entryCollection,\n    path: localizedEntryMap[defaultLocale].path,\n    fallback: defaultLocaleSlug,\n  });\n\n  // In a nested collection, an entry is identified by its path within the collection folder rather\n  // than by a file name, so that’s also the slug the entry gets when it’s read back from the\n  // repository. Use it here as well, or the entry saved in this session would differ from the same\n  // entry after a reload.\n  const nested = isNestedCollection(collection);\n\n  /** @type {Entry} */\n  const 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  await callEventHooks({\n    type: 'preSave',\n    entry: savingEntry,\n    collection,\n    collectionFile,\n    isNew: draft.isNew,\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 })\n          : planMultiFileChange({ draft, savingEntry, locale }),\n    })),\n  );\n\n  return { savingEntry, savingAssets, changes };\n};\n","import { getArrayItemTarget } from '$lib/services/contents/draft/save/changes';\nimport { buildEntryFileChanges } from '$lib/services/contents/draft/save/file-changes';\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 * } 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        const { slug, path } = entry.locales[config._i18n.defaultLocale];\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 { 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 { _ } 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 { isEntryReadonly } from '$lib/services/contents/entry/readonly';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\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 * Matches the index suffix of a multi-value field’s item key path, e.g. `.1` in `tags.1`.\n */\nexport const ITEM_INDEX_SUFFIX_REGEX = /\\.\\d+$/;\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: fieldConfig.label || fieldConfig.name,\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 perEntryChanges = await Promise.all(\n    targets.map(({ entry, collection, collectionFile }) =>\n      buildEntryUpdateChanges({\n        collection,\n        collectionFile,\n        entry,\n        draft: createSyntheticDraft({\n          collection,\n          collectionFile,\n          isIndexFile: isCollectionIndexFile(collection, entry),\n        }),\n        cacheDB: db,\n      }),\n    ),\n  );\n\n  return {\n    changes: perEntryChanges.flat(),\n    savingEntries: targets.map(({ entry }) => entry),\n  };\n};\n","import { getAssetPublicURL } from '$lib/services/assets/info';\nimport { getMediaFieldSource } from '$lib/services/assets/media-field';\nimport {\n  getAssetReferences,\n  getComparableAssetURL,\n  MARKDOWN_IMAGE_REGEX,\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  ITEM_INDEX_SUFFIX_REGEX,\n} from '$lib/services/contents/entry/cascade';\nimport { createSyntheticDraft } from '$lib/services/contents/entry/changes';\nimport { isFieldMultiple } from '$lib/services/contents/entry/fields';\nimport { MEDIA_FIELD_TYPES } from '$lib/services/contents/fields';\n\n/**\n * @import {\n * Asset,\n * AssetReference,\n * CascadeDeleteBlocker,\n * CascadeDeletePlan,\n * CascadeTarget,\n * Entry,\n * FlattenedEntryContent,\n * } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\n * @import { AssetReferenceTarget } from '$lib/services/assets/references';\n */\n\n/**\n * Get what the references to the given assets are matched by: the public path of an asset that has\n * one, in the form it’s stored in a field value — without the site’s base URL — or else the asset\n * itself, as in an entry-relative folder, which a value refers to when it resolves to the asset.\n * The asset is matched without being loaded, unlike by its blob 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 = getAssetPublicURL(asset, { allowSpecial: true, pathOnly: true });\n\n    if (url === undefined) {\n      targets.push({ asset });\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 * Remove the images pointing at the deleted assets from a Markdown string.\n * @param {object} args Arguments.\n * @param {string} args.value Markdown.\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 an image points at when its source 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 * @returns {string} Markdown without the images.\n */\nexport const removeMarkdownImages = ({\n  value,\n  urls,\n  paths = new Set(),\n  entry,\n  collectionName,\n  fileName,\n}) => {\n  const matches = [...value.matchAll(MARKDOWN_IMAGE_REGEX)];\n\n  const stale = matches.map(([, src]) => {\n    if (urls.has(src)) {\n      return true;\n    }\n\n    if (!paths.size) {\n      return false;\n    }\n\n    // Resolve the image’s path the way the editor does to display it, without loading the asset\n    const path = getMediaFieldSource({ entry, collectionName, fileName, value: src })?.asset?.path;\n\n    return path !== undefined && paths.has(path);\n  });\n\n  // Cut from the end, so the positions of the earlier matches stay valid\n  return matches.reduceRight(\n    (text, { index, 0: markup }, i) => (stale[i] ? cutMarkup(text, index, markup.length) : text),\n    value,\n  );\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.\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, keyPath, fieldConfig }) => {\n    const { widget: fieldType = 'string' } = fieldConfig;\n\n    if (!MEDIA_FIELD_TYPES.includes(fieldType)) {\n      // The reference is an image embedded in a Markdown or rich text field\n      updatedContent[keyPath] = removeMarkdownImages({\n        value: content[keyPath],\n        urls,\n        paths,\n        entry,\n        collectionName: collection.name,\n        fileName: collectionFile?.name,\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 { 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 { getEntryFoldersByPath } from '$lib/services/contents/folders';\n\n/**\n * @import {\n * ArrayItemTarget,\n * Entry,\n * FileChange,\n * InternalEntryCollection,\n * RepositoryFileInfo,\n * RepositoryFileMetadata,\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 */\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  /** @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} */ (\n        slots.find(({ from }) => from === arrayItem.index)\n      );\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\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        }),\n      };\n\n      return { collection, path, slots, change };\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 }) => {\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    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 { 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 } 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\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) => !arrayFileEntries.includes(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\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 suspendChecksWhile(async () => {\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, options)),\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          await cacheAssetBlob(savedAsset, file);\n        }\n\n        return savedAsset;\n      }),\n    );\n\n    await updateCache({ changes: combinedChanges, commit });\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\n    // The stores now reflect this commit, so it’s the head to compare the branch with from here on\n    if (fetchLastCommit) {\n      repositoryHead.current = commit.sha;\n    }\n\n    return { commit, savedEntries, savedAssets };\n  });\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 { _ } from '@sveltia/i18n';\nimport { getPathInfo } from '@sveltia/utils/file';\n\nimport { assetUpdatesToast, refreshFocusedAssets } from '$lib/services/assets/data';\nimport { getAssetFoldersByPath, globalAssetFolder } from '$lib/services/assets/folders';\nimport { getAssetBlob, getAssetPublicURL } from '$lib/services/assets/info';\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 {\n  getIndexFile,\n  isCollectionIndexFile,\n} from '$lib/services/contents/collection/entries/index-file';\nimport { getCollectionFilesByEntry } from '$lib/services/contents/collection/files';\nimport { createSavingEntryData } from '$lib/services/contents/draft/save/changes';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { getAssociatedCollections } from '$lib/services/contents/entry/collections';\nimport { getReadonlyEntryLabel, isEntryReadonly } from '$lib/services/contents/entry/readonly';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { encodeFilePath } 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    getAssociatedCollections(entry).map(async (collection) => {\n      const collectionName = collection.name;\n      const isIndexFile = isCollectionIndexFile(collection, entry);\n      const indexFile = isIndexFile ? getIndexFile(collection) : undefined;\n      const collectionFiles = getCollectionFilesByEntry(collection, entry);\n      const addDataProps = { indexFile, savingEntries, changes };\n      /** @type {Partial<EntryDraft>} */\n      const draftProps = { ...draftBaseProps, collection, collectionName, isIndexFile };\n\n      if (collectionFiles.length) {\n        await Promise.all(\n          collectionFiles.map((collectionFile) =>\n            addSavingEntryData({\n              ...addDataProps,\n              draftProps: { ...draftProps, collectionFile, fileName: collectionFile.name },\n            }),\n          ),\n        );\n      } else {\n        await addSavingEntryData({ ...addDataProps, draftProps });\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 * Rewrite the references to the given assets in the entries that use them, so these point at the\n * assets’ new paths. The entries are searched once for all the assets, however many there are.\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, keyed by\n * entry ID. An entry using several of the moved assets is copied once and has every reference\n * replaced in that copy, so it’s saved once with all of them; a copy per asset would each hold a\n * single replacement and overwrite the others. The caller collects the changes from the copies.\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  /** @type {AssetReferenceTarget[]} */\n  const targets = movingAssets.map(({ asset }) => {\n    // An asset without a public URL, as in an entry-relative folder, is matched by the asset its\n    // references resolve to, which works whether or not the asset has been loaded\n    const url = getAssetPublicURL(asset);\n\n    return url ? { url } : { asset };\n  });\n\n  if (!targets.length) {\n    return;\n  }\n\n  // Find the entries first, without replacing anything, so the originals are left alone until the\n  // change is saved\n  const usedEntries = await getEntriesByAssets(targets);\n  /** @type {AssetReferenceTarget[]} */\n  const replacingTargets = [];\n  /** @type {Set<Entry>} */\n  const updatingEntries = new Set();\n\n  movingAssets.forEach(({ asset, path: newPath }, index) => {\n    if (!usedEntries[index].length) {\n      return;\n    }\n\n    // The new URL is worked out the same way as the current one, so that the public folder, the\n    // `encode_file_path` option and template tags are all dealt with alike. A move stays within the\n    // asset’s folder, so the folder still applies\n    const newName = newPath.slice(newPath.lastIndexOf('/') + 1);\n\n    const newURL =\n      getAssetPublicURL(\n        { ...asset, path: newPath, name: newName },\n        { pathOnly: true, allowSpecial: true },\n      ) ??\n      // A rename can be applied to a reference relative to the entry holding it\n      (asset.folder.entryRelative &&\n      newPath.slice(0, -newName.length) === asset.path.slice(0, -asset.name.length)\n        ? getRenamedReference(asset.name, newName)\n        : getFallbackURL({ _globalAssetFolder, newPath, asset }));\n\n    replacingTargets.push({ ...targets[index], newURL });\n    usedEntries[index].forEach((entry) => updatingEntries.add(entry));\n  });\n\n  if (!replacingTargets.length) {\n    return;\n  }\n\n  // A read-only entry can’t be rewritten, and leaving it pointing at a file that’s no longer there\n  // would break it, so the move is refused\n  const readonlyEntries = [...updatingEntries].filter((entry) => isEntryReadonly(entry));\n\n  if (readonlyEntries.length) {\n    throw new Error(\n      _('cannot_move_referenced_asset', {\n        values: {\n          entries: readonlyEntries.map((entry) => getReadonlyEntryLabel(entry)).join(', '),\n        },\n      }),\n    );\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 * 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 }) => {\n      const newPath = path;\n      const newName = getPathInfo(newPath).basename;\n      const blob = asset.file ?? (await getAssetBlob(asset));\n\n      savingAssets.push({ ...asset, path: newPath, name: newName });\n\n      changes.push({\n        action: 'move',\n        path: newPath,\n        previousPath: asset.path,\n        previousSha: asset.sha,\n        // Read the bytes up front. A blob backed by the file system points at the file about to be\n        // moved away, and reading it afterwards — to write the copy or to hash it — fails because\n        // there’s nothing at that path anymore\n        data: new File([await blob.arrayBuffer()], newName, { type: blob.type }),\n      });\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","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 { 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 * Get the assets below a folder, at any depth. These are what a rename moves along and a deletion\n * removes, and what the deletion dialog 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  publishedAssets.current.filter(({ path }) => path.startsWith(`${dirPath}/`));\n\n/**\n * Get the Git config files below a folder, at any depth: the `.gitkeep` files that keep the empty\n * folders, and the odd `.gitignore`. Not being assets, these have to be moved and deleted along\n * with the folder separately.\n * @param {string} dirPath Folder path.\n * @returns {BaseConfigListItem[]} Files.\n */\nconst getSubfolderConfigFiles = (dirPath) =>\n  gitConfigFiles.current.filter(({ path }) => path.startsWith(`${dirPath}/`));\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  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 { Alert, ConfirmationDialog, Toast } 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 { 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  let deletionFailed = $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 = async () => {\n    /* v8 ignore next 3 -- the dialog is only open for a folder */\n    if (!subfolder) {\n      return;\n    }\n\n    try {\n      await deleteSubfolder(subfolder.path);\n    } catch (/** @type {any} */ ex) {\n      deletionFailed = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    }\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\n<Toast bind:show={deletionFailed}>\n  <Alert status=\"error\">{_('deleting_folder_failed')}</Alert>\n</Toast>\n","import { getAssetBlobURL, getAssetPublicURL } from '$lib/services/assets/info';\nimport { isMediaKind } from '$lib/services/assets/kinds';\nimport { 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';\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.\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  const metaData = await getMediaMetadataOnce(asset);\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    repoBlobURL: blobBaseURL ? `${blobBaseURL}/${path}` : undefined,\n  };\n};\n\n/**\n * Get the URL an asset is referenced by in the entries: its public path, or its blob URL if it has\n * no public path, as with an asset in an entry-relative folder.\n * @param {Asset} asset Asset.\n * @returns {Promise<string | undefined>} URL, or `undefined` if the asset can’t be located.\n */\nconst getAssetReferenceURL = async (asset) =>\n  getAssetPublicURL(asset, { allowSpecial: true, pathOnly: true }) ??\n  (await getAssetBlobURL(asset));\n\n/**\n * Get the list of entries using the given asset.\n * @param {Asset} asset Asset.\n * @returns {Promise<Entry[]>} List of entries using the asset.\n */\nexport const getAssetUsedEntries = async (asset) => {\n  const url = await getAssetReferenceURL(asset);\n\n  if (!url) {\n    return [];\n  }\n\n  return getEntriesByAssetURL(url);\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\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 {\n    /* eslint-disable prefer-const */\n    assets = [],\n    useButton = true,\n    /* eslint-enable prefer-const */\n  } = $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  /**\n   * Assets the details were last requested for. The menu stays mounted while the focus moves from\n   * one asset to another, so a slow lookup for an asset focused earlier must not overwrite the\n   * details of the one focused now.\n   * @type {Asset[] | undefined}\n   */\n  let requestedAssets;\n\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  $effect(() => {\n    const _assets = assets;\n\n    requestedAssets = _assets;\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    (async () => {\n      try {\n        const [detailList, blob] = await 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        if (requestedAssets !== _assets) {\n          return;\n        }\n\n        assetsDetailList = detailList;\n        assetBlob = blob;\n        canCopyData = !!blob && canCopyFileData(blob.type);\n      } catch (/** @type {any} */ 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  });\n</script>\n\n<CopyMenu {items} count={assets.length} {useButton} />\n","<!--\n  @component Edit options menu for a repository asset: Edit, Rename, 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 { defaultAssetDetails, getAssetDetails } from '$lib/services/assets/details';\n  import { assetsLocked, hasReadonlyAsset } from '$lib/services/assets/folders';\n  import { canEditAsset } from '$lib/services/assets/kinds';\n  import { editingAsset, renamingAsset, uploadingAssets } from '$lib/services/assets/state';\n  import { showUploadAssetsDialog } from '$lib/services/assets/view';\n  import { backend } from '$lib/services/backends';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   * @import { Asset, AssetDetails } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {Asset} [asset] Selected asset.\n   * @property {Snippet} [extraItems] Slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    asset,\n    extraItems = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {AssetDetails} */\n  let details = $state({ ...defaultAssetDetails });\n\n  const { publicURL, repoBlobURL } = $derived(details);\n\n  /**\n   * Asset the details were last requested for. The menu stays mounted while the focus moves from\n   * one asset to another, so a slow lookup for an asset focused earlier must not overwrite the\n   * details of the one focused now.\n   * @type {Asset | undefined}\n   */\n  let requestedAsset;\n\n  /**\n   * Update the properties above.\n   */\n  const updateProps = async () => {\n    const _asset = asset;\n\n    requestedAsset = _asset;\n    // Drop the previous asset’s links, so they’re not offered while this one’s are being retrieved\n    // or once that fails\n    details = { ...defaultAssetDetails };\n\n    try {\n      const _details = _asset ? await getAssetDetails(_asset) : { ...defaultAssetDetails };\n\n      if (requestedAsset === _asset) {\n        details = _details;\n      }\n    } catch (/** @type {any} */ ex) {\n      // The file couldn’t be downloaded, so the public URL is unknown\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    }\n  };\n\n  $effect(() => {\n    void [asset];\n    updateProps();\n  });\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 || (!!asset && hasReadonlyAsset([asset]))}\n  canEdit={!!asset && canEditAsset(asset)}\n  canRename={!!asset}\n  canReplace={!!asset}\n  onEdit={() => {\n    editingAsset.current = asset;\n  }}\n  onRename={() => {\n    renamingAsset.current = asset;\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    {#if prefs.devModeEnabled}\n      <MenuItem\n        disabled={!backend.current?.repository || !repoBlobURL}\n        label={backend.current?.repository?.label\n          ? _('view_on_x', { values: { service: backend.current.repository.label } })\n          : _('view_in_repository')}\n        onclick={() => {\n          openNewTab(`${repoBlobURL}?plain=1`);\n        }}\n      />\n    {/if}\n  {/snippet}\n</EditOptionsMenu>\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    /* eslint-disable prefer-const */\n    coordinates,\n    class: className = '',\n    mapElement = $bindable(),\n    onReady = undefined,\n    ...rest\n    /* eslint-enable prefer-const */\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","<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 {\n    defaultAssetDetails,\n    getAssetDetails,\n    getAssetUsedEntries,\n  } from '$lib/services/assets/details';\n  import { isMediaKind } from '$lib/services/assets/kinds';\n  import { formatDate } from '$lib/services/utils/date';\n\n  /**\n   * @import { Asset, AssetDetails } 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 {\n    /* eslint-disable prefer-const */\n    asset,\n    showPreview = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {AssetDetails} */\n  let details = $state({ ...defaultAssetDetails });\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);\n  const canPreview = $derived(isMediaKind(kind) || path.endsWith('.pdf'));\n\n  /**\n   * Asset the details were last requested for. The panel stays mounted while the focus moves from\n   * one asset to another, so a slow lookup for an asset focused earlier must not overwrite the\n   * details of the one focused now.\n   * @type {Asset | undefined}\n   */\n  let requestedAsset;\n\n  /**\n   * Update the properties above.\n   */\n  const updateProps = async () => {\n    const _asset = asset;\n\n    requestedAsset = _asset;\n    // Don’t leave the previous asset’s details on show while this one’s are being retrieved. The\n    // used entries are being looked up as well\n    details = { ...defaultAssetDetails, usedEntries: undefined };\n\n    try {\n      const _details = _asset ? await getAssetDetails(_asset) : { ...defaultAssetDetails };\n\n      if (requestedAsset !== _asset) {\n        return;\n      }\n\n      details = _details;\n      // A late result lands on the object replaced since, so it needs no check\n      details.usedEntries = _asset ? await getAssetUsedEntries(_asset) : [];\n    } catch (/** @type {any} */ ex) {\n      // The file couldn’t be downloaded, so only the basic info is shown\n      // eslint-disable-next-line no-console\n      console.error(ex);\n\n      if (requestedAsset === _asset) {\n        // Stop showing the used entries as being loaded\n        details.usedEntries = [];\n      }\n    }\n  };\n\n  $effect(() => {\n    void [asset];\n    updateProps();\n  });\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>{commitAuthor.name || commitAuthor.login || commitAuthor.email}</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 { EmptyState } from '@sveltia/ui';\n  import { isTextFileType } from '@sveltia/utils/file';\n\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/internal/copy-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 TextPreview from '$lib/components/assets/list/text-preview.svelte';\n  import AssetPreview from '$lib/components/assets/shared/asset-preview.svelte';\n  import NotFound from '$lib/components/global/not-found.svelte';\n  import { encodeRoutePath, goBack } from '$lib/services/app/navigation';\n  import { planAssetDeletion } from '$lib/services/assets/data/cascade';\n  import { deleteAssets } from '$lib/services/assets/data/delete';\n  import {\n    assetsLocked,\n    hasReadonlyAsset,\n    selectedAssetFolder,\n  } from '$lib/services/assets/folders';\n  import { getAssetBlob } from '$lib/services/assets/info';\n  import { isMediaKind } 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\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   * @type {{ asset: Asset, blob: Blob } | undefined}\n   */\n  let loaded = $state.raw();\n\n  const asset = $derived(overlaidAsset.current);\n  const blob = $derived(loaded?.asset === asset ? /** @type {Blob} */ (loaded?.blob) : undefined);\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    encodeRoutePath(\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(Object.values(assetGroups.current).flat(1), (a) => a.path === asset?.path),\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  $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        const _blob = await getAssetBlob(current);\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    <!--\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\n      can’t push to the branch can do\n    -->\n    <DeleteAssetsButton\n      {assets}\n      disabled={assetsLocked.current || hasReadonlyAsset(assets)}\n      deleteAssets={(_assets) => {\n        // Don’t wait for the commit; the list is updated optimistically\n        deleteAssets(_assets);\n      }}\n      planDeletion={planAssetDeletion}\n      buttonDescription={_('delete_assets', { values: { count: 1 } })}\n      dialogDescription={_('confirm_deleting_this_asset')}\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 if kind && isMediaKind(kind)}\n      <AssetPreview\n        {kind}\n        {asset}\n        blurBackground={['image', 'video'].includes(kind)}\n        checkerboard={kind === 'image'}\n        alt={kind === 'image' ? name : undefined}\n        controls={['audio', 'video'].includes(kind)}\n      />\n    {:else if blob?.type === 'application/pdf'}\n      <iframe src={blobURL} title={name} sandbox=\"allow-scripts\"></iframe>\n    {:else if blob?.type && isTextFileType(blob.type)}\n      {#await asset.text ?? blob.text() then text}\n        <TextPreview {text} {name} />\n      {/await}\n    {:else}\n      <EmptyState>\n        <span role=\"alert\">{_('preview_unavailable')}</span>\n      </EmptyState>\n    {/if}\n  {/snippet}\n  {#snippet info()}\n    {#if asset}\n      <InfoPanel {asset} />\n    {/if}\n  {/snippet}\n</DetailsOverlay>\n","import { getAssetsByDirName } 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 { skipCIConfigured, skipCIEnabled } 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 } from '$lib/services/utils/file';\n\n/**\n * @import { Asset, CommitAction, CommitOptions, UploadingAssets } 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  const assetNamesInSameFolder = assetsInSameFolder.map((a) => a.name.normalize());\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.\n    const replacedAsset =\n      originalAssets?.[index] ??\n      (replaceDuplicates\n        ? assetsInSameFolder.find(\n            (a) => a.name.normalize().toLowerCase() === file.name.normalize().toLowerCase(),\n          )\n        : undefined);\n\n    const fileName =\n      replacedAsset?.name ??\n      formatFileName(file.name, { slugificationEnabled, assetNamesInSameFolder });\n\n    if (!assetNamesInSameFolder.includes(fileName)) {\n      assetNamesInSameFolder.push(fileName);\n    }\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 */\nexport const updateStores = ({ count }) => {\n  refreshFocusedAssets((asset) => asset.path);\n\n  assetUpdatesToast.current = {\n    ...UPDATE_TOAST_DEFAULT_STATE,\n    saved: true,\n    published: skipCIConfigured.current && !skipCIEnabled.current,\n    count,\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 { files, folder } = uploadingAssets;\n  const savingFileList = createFileList(uploadingAssets);\n\n  assertOutsideCmsFolders(savingFileList.map(({ path }) => path));\n\n  const savingAssets = savingFileList.map(\n    ({ name, path, file }) =>\n      /** @type {Asset} */ ({\n        name,\n        path,\n        size: file.size,\n        kind: getAssetKind(name),\n        folder,\n      }),\n  );\n\n  await saveChanges({\n    changes: savingFileList.map(({ action, path, file }) => ({ action, path, data: file })),\n    savingAssets,\n    options,\n  });\n\n  updateStores({ count: files.length });\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Dialog, Switch, TextArea } from '@sveltia/ui';\n\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\n  /**\n   * Initialize the state.\n   */\n  const initState = async () => {\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.\n   */\n  const saveAsset = async () => {\n    /* v8 ignore next 10 -- the dialog is only shown once the asset is loaded */\n    if (asset && blob && typeof currentValue === 'string') {\n      await saveAssets(\n        {\n          folder: asset.folder,\n          files: [new File([currentValue], asset.name, { type: blob.type })],\n          originalAssets: [asset],\n        },\n        { commitType: 'uploadMedia' },\n      );\n    }\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) {\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    resetState();\n  }}\n>\n  <div role=\"none\" class=\"wrapper\" class:wrap>\n    <TextArea dir=\"auto\" bind:value={currentValue} flex />\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","<!--\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  import { Alert, Toast } from '@sveltia/ui';\n\n  import SubfolderNameDialog from '$lib/components/assets/list/subfolder-name-dialog.svelte';\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 {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    dirPath,\n    takenNames,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  // Committing to a remote repository takes a few seconds, and the dialog is gone by then, so the\n  // folder would otherwise be created with nothing on screen to say it’s under way\n  let creating = $state(false);\n  let creationFailed = $state(false);\n\n  /**\n   * Create the folder.\n   * @param {string} name Folder name.\n   */\n  const create = async (name) => {\n    creating = true;\n\n    try {\n      await createSubfolder(createPath([dirPath, name]));\n    } catch (/** @type {any} */ ex) {\n      creationFailed = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      creating = false;\n    }\n  };\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    create(name);\n  }}\n/>\n\n<!-- `duration={0}` keeps this up until the commit settles, however long it takes -->\n<Toast show={creating} duration={0}>\n  <Alert status=\"info\">{_('creating_folder')}</Alert>\n</Toast>\n\n<Toast bind:show={creationFailed}>\n  <Alert status=\"error\">{_('creating_folder_failed')}</Alert>\n</Toast>\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  /** Names already taken in the directory, by a subfolder or a file. */\n  const takenNames = $derived(\n    getTakenNames({\n      subfolders: listedSubfolders.current,\n      fileNames: listedAssets.current.map(({ name }) => name),\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 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/internal/copy-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 { encodeRoutePath, goBack, goto } from '$lib/services/app/navigation';\n  import { planAssetDeletion } from '$lib/services/assets/data/cascade';\n  import { deleteAssets } from '$lib/services/assets/data/delete';\n  import {\n    assetsLocked,\n    canCreateAsset,\n    hasReadonlyAsset,\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 } from '$lib/services/config/readonly';\n  import { env } from '$lib/services/user/env.svelte';\n  import { createPath } from '$lib/services/utils/file';\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\n  const readonly = $derived(!!folder?.readonly || !!lockedBranch.current);\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 = encodeRoutePath(\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 ? encodeRoutePath(`/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    <!--\n        Deleting a file from the media library commits straight to the configured branch rather\n        than going through review, so it’s not something an Open Authoring contributor or a user\n        who can’t push to the branch can do\n      -->\n    <DeleteAssetsButton\n      {assets}\n      disabled={assetsLocked.current || hasReadonlyAsset(assets)}\n      deleteAssets={(_assets) => {\n        // Don’t wait for the commit; the list is updated optimistically\n        deleteAssets(_assets);\n      }}\n      planDeletion={planAssetDeletion}\n      buttonDescription={_('delete_selected_assets', { values: { count: assets.length } })}\n      dialogDescription={_(\n        assets.length > 1 && assets.length === listedAssets.current.length\n          ? 'confirm_deleting_all_assets'\n          : 'confirm_deleting_selected_assets',\n        { values: { count: assets.length } },\n      )}\n    />\n    <EditOptionsButton {asset} />\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 { _ } from '@sveltia/i18n';\n  import { getPathInfo } from '@sveltia/utils/file';\n\n  import RenameDialog from '$lib/components/assets/list/rename-dialog.svelte';\n  import { encodeRoutePath, goto, parseLocation } from '$lib/services/app/navigation';\n  import { getAssetsByDirName } from '$lib/services/assets';\n  import { moveAssets } from '$lib/services/assets/data/move';\n  import { getAssetUsedEntries } from '$lib/services/assets/details';\n  import { getAssetFolderHistoryState } from '$lib/services/assets/navigation';\n  import { renamingAsset } from '$lib/services/assets/state';\n  import { getReadonlyEntryLabel, isEntryReadonly } from '$lib/services/contents/entry/readonly';\n  import { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\n  import { watchAsync } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { Entry } from '$lib/types/private';\n   */\n\n  let open = $state(false);\n  /** @type {Entry[]} */\n  let usedEntries = $state([]);\n\n  const asset = $derived(renamingAsset.current);\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 readonlyEntries = $derived(usedEntries.filter((entry) => isEntryReadonly(entry)));\n  const blockedMessage = $derived(\n    readonlyEntries.length\n      ? _('cannot_move_referenced_asset', {\n          values: {\n            entries: readonlyEntries.map((entry) => getReadonlyEntryLabel(entry)).join(', '),\n          },\n        })\n      : undefined,\n  );\n  const { dirname = '', basename = '' } = $derived(getPathInfo(asset?.path ?? ''));\n  const otherNames = $derived(\n    asset\n      ? getAssetsByDirName(dirname)\n          .map((a) => a.name)\n          .filter((n) => n !== asset.name)\n      : [],\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    const newPath = `${dirname}/${newName}`;\n\n    await moveAssets('rename', [{ asset, path: newPath }]);\n\n    if (parseLocation().path === `/assets/${oldPath}`) {\n      await goto(encodeRoutePath(`/assets/${newPath}`), {\n        replaceState: true,\n        notifyChange: false,\n        // Keep the folder the asset was opened from, e.g. All Assets\n        state: getAssetFolderHistoryState(),\n      });\n    }\n  };\n\n  // Another asset can be renamed before the entries using this one are found, which `watchAsync`\n  // takes care of\n  watchAsync(\n    () => (asset ? getAssetUsedEntries(asset) : undefined),\n    (entries) => {\n      usedEntries = entries;\n      open = true;\n    },\n  );\n</script>\n\n<RenameDialog\n  bind:open\n  name={basename}\n  {otherNames}\n  usedEntryCount={usedEntries.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  import { Alert, Toast } from '@sveltia/ui';\n\n  import SubfolderNameDialog from '$lib/components/assets/list/subfolder-name-dialog.svelte';\n  import { getSubfolderAssets, renameSubfolder } from '$lib/services/assets/data/subfolder';\n  import { getTakenNames, renamingSubfolder } 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  // Committing to a remote repository takes a few seconds, and the dialog is gone by then, so the\n  // folder would otherwise be renamed with nothing on screen to say it’s under way\n  let renaming = $state(false);\n  let renamingFailed = $state(false);\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  /** Names taken by the siblings of the folder, which it can’t take over. */\n  const takenNames = $derived(\n    getTakenNames({\n      subfolders: listedSubfolders.current,\n      fileNames: listedAssets.current.map(({ name }) => name),\n      exclude: currentName,\n    }),\n  );\n\n  /**\n   * Rename the folder.\n   * @param {string} newName New folder name.\n   */\n  const rename = async (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    renaming = true;\n\n    try {\n      await renameSubfolder({\n        dirPath: path,\n        newDirPath: createPath([getDirName(path), newName]),\n      });\n    } catch (/** @type {any} */ ex) {\n      renamingFailed = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      renaming = false;\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\n<!-- `duration={0}` keeps this up until the commit settles, however long it takes -->\n<Toast show={renaming} duration={0}>\n  <Alert status=\"info\">{_('renaming_folder')}</Alert>\n</Toast>\n\n<Toast bind:show={renamingFailed}>\n  <Alert status=\"error\">{_('renaming_folder_failed')}</Alert>\n</Toast>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { SearchBar } from '@sveltia/ui';\n  import { untrack } from 'svelte';\n\n  import { goBack, goto, parseLocation } from '$lib/services/app/navigation';\n  import { searchMode, searchTerms } from '$lib/services/search';\n\n  /**\n   * @typedef {object} Props\n   * @property {(event: MouseEvent) => void} [onclick] `click` event handler.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    onclick = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Navigate to the search results page if search terms are given, or go back the previous page.\n   * @param {string} terms New search terms.\n   */\n  const navigate = (terms) => {\n    const hadTerms = !!searchTerms.current;\n    const { path } = parseLocation();\n    const searching = path.startsWith('/search/');\n\n    searchTerms.current = terms;\n\n    if (terms) {\n      // Encode the terms, or a `?` or `#` would cut them short in the URL, and a stray `%` would\n      // make the path impossible to decode\n      goto(`/search/${encodeURIComponent(terms)}`, { replaceState: searching });\n    } else if (hadTerms && searching) {\n      goBack('/collections');\n    }\n  };\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<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        navigate(/** @type {HTMLInputElement} */ (target).value.trim());\n      }}\n      onClear={() => {\n        navigate('');\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 { encodeRoutePath, goto } from '$lib/services/app/navigation';\n  import { getAssetsByFolder } from '$lib/services/assets';\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 {\n    allAssetFolders,\n    canCreateAsset,\n    selectedAssetFolder,\n  } 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 { getCollection, getCollectionIndex } from '$lib/services/contents/collection';\n  import {\n    getCollectionFile,\n    getCollectionFileIndex,\n  } from '$lib/services/contents/collection/files';\n  import { env } from '$lib/services/user/env.svelte';\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 {\n    /* eslint-disable prefer-const */\n    isSearchPage = false,\n    /* eslint-enable prefer-const */\n  } = $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  const folders = $derived([\n    // All Assets, Global Assets, then collection-level, file-level folders, sorted by appearance\n    // order in the config\n    ...allAssetFolders.current\n      .filter(\n        ({ typedKeyPath, isAssetCollection }) =>\n          !isAssetCollection &&\n          // Exclude field-level folders\n          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    // All asset collection folders, sorted by appearance order in the config\n    ...allAssetFolders.current.filter(({ isAssetCollection }) => isAssetCollection),\n  ]);\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 ariaLabel={_('asset_folder_list')} aria-controls=\"assets-container\">\n    {#if folders.length}\n      <OptionGroup label={_('asset_location.repository')}>\n        {#each folders as folder, index ([folder.collectionName, folder.fileName, folder.internalPath].join(':'))}\n          {#await sleep() then}\n            {@const { collectionName, fileName, internalPath } = folder}\n            {@const collection = collectionName ? getCollection(collectionName) : undefined}\n            {@const collectionFile =\n              collection && fileName ? getCollectionFile(collection, fileName) : undefined}\n            <!-- Can’t upload assets if collection assets are saved at entry-relative paths, or the\n            folder is read-only -->\n            {@const uploadDisabled = !canCreateAsset(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(encodeRoutePath(`/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(encodeRoutePath(`/assets/${internalPath}`), {\n                    transitionType: 'backwards',\n                    state: { folder },\n                  });\n                }\n              }}\n              ondragover={(event) => {\n                event.preventDefault();\n\n                if (uploadDisabled) {\n                  return;\n                }\n\n                if (internalPath === undefined || selected) {\n                  /** @type {DataTransfer} */ (event.dataTransfer).dropEffect = 'none';\n                } else {\n                  /** @type {DataTransfer} */ (event.dataTransfer).dropEffect = 'move';\n                  /** @type {HTMLElement} */ (event.target).classList.add('dragover');\n                }\n              }}\n              ondragleave={(event) => {\n                event.preventDefault();\n\n                if (uploadDisabled) {\n                  return;\n                }\n\n                /** @type {HTMLElement} */ (event.target).classList.remove('dragover');\n              }}\n              ondragend={(event) => {\n                event.preventDefault();\n\n                if (uploadDisabled) {\n                  return;\n                }\n\n                /** @type {HTMLElement} */ (event.target).classList.remove('dragover');\n              }}\n              ondrop={(event) => {\n                event.preventDefault();\n\n                if (uploadDisabled) {\n                  return;\n                }\n\n                /** @type {HTMLElement} */ (event.target).classList.remove('dragover');\n                // @todo Move the assets while updating entries using the files, after showing a\n                // confirmation dialog.\n              }}\n            >\n              {#snippet startIcon()}\n                <Icon name={folder.icon || collectionFile?.icon || collection?.icon || 'folder'} />\n              {/snippet}\n              {#snippet endIcon()}\n                {#key allAssets.current}\n                  {#await sleep() then}\n                    {@const count = (\n                      internalPath !== undefined ? getAssetsByFolder(folder) : allAssets.current\n                    ).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          >\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","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  (await getUISettingsDB()?.get(key))?.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH;\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  await db.set(key, { ...(await db.get(key)), sidebarWidth: width });\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    /* eslint-disable prefer-const */\n    class: className = '',\n    uiSettingsKey = undefined,\n    primarySidebar = undefined,\n    main = undefined,\n    ...rest\n    /* eslint-enable prefer-const */\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 { 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 { encodeRoutePath, goto } from '$lib/services/app/navigation';\n  import { getFolderLabelByCollection } from '$lib/services/assets/view';\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 {\n    /* eslint-disable prefer-const */\n    asset,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const { path, name, folder, kind } = $derived(asset);\n</script>\n\n<GridRow\n  onclick={() => {\n    goto(encodeRoutePath(`/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","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","<script>\n  import { _ } from '@sveltia/i18n';\n  import { EmptyState, Group, InfiniteScroll } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n\n  import ListingGrid from '$lib/components/common/listing-grid.svelte';\n  import AssetResultItem from '$lib/components/search/asset-result-item.svelte';\n  import { announcedPageStatus } from '$lib/services/app/navigation';\n  import { searchTerms } from '$lib/services/search';\n  import { assetSearchResults } from '$lib/services/search/assets';\n\n  /**\n   * @import { Asset } from '$lib/types/private';\n   */\n\n  $effect(() => {\n    announcedPageStatus.current = _('viewing_asset_search_results', {\n      values: {\n        terms: searchTerms.current,\n        count: assetSearchResults.current.length,\n      },\n    });\n  });\n</script>\n\n<Group aria-labelledby=\"search-results-assets\">\n  <!-- <h3 role=\"none\" id=\"search-results-assets\">{_('assets')}</h3> -->\n  <div role=\"none\">\n    {#if assetSearchResults.current.length}\n      <ListingGrid\n        viewType=\"list\"\n        aria-label={_('assets')}\n        aria-rowcount={assetSearchResults.current.length}\n      >\n        {#key searchTerms.current}\n          <InfiniteScroll items={assetSearchResults.current} itemKey=\"path\">\n            {#snippet renderItem(/** @type {Asset} */ asset)}\n              {#await sleep() then}\n                <AssetResultItem {asset} />\n              {/await}\n            {/snippet}\n          </InfiniteScroll>\n        {/key}\n      </ListingGrid>\n    {:else if searchTerms.current}\n      <EmptyState>\n        <span role=\"none\">{_('no_files_found')}</span>\n      </EmptyState>\n    {/if}\n  </div>\n</Group>\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’s object URL is released when\n  the entry changes or the thumbnail is removed, so a long list doesn’t keep every thumbnail it has\n  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\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 {\n    /* eslint-disable prefer-const */\n    collection,\n    entry,\n    variant,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {string | undefined} */\n  let src = $state();\n\n  $effect(() =>\n    loadEntryThumbnail(collection, entry, (url) => {\n      src = url;\n    }),\n  );\n</script>\n\n{#if src}\n  <Image {src} {variant} cover />\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 { encodeRoutePath, 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 { 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 {\n    /* eslint-disable prefer-const */\n    result,\n    /* eslint-enable prefer-const */\n  } = $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(\n        encodeRoutePath(\n          `/collections/${collection.name}/entries/${collectionFile?.name || subPath}`,\n        ),\n        {\n          state: { highlight: { locale, keyPath } },\n          transitionType: 'forwards',\n        },\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","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 { 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  const summary = getEntrySummary(collections[0], entry, {\n    useTemplate: true,\n    allowMarkdown: true,\n  });\n\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 { 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 { EmptyState, Group, InfiniteScroll } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n\n  import ListingGrid from '$lib/components/common/listing-grid.svelte';\n  import EntryResultItem from '$lib/components/search/entry-result-item.svelte';\n  import { announcedPageStatus } from '$lib/services/app/navigation';\n  import { searchTerms } from '$lib/services/search';\n  import { entrySearchResults } from '$lib/services/search/entries';\n\n  /**\n   * @import { EntrySearchResult } from '$lib/types/private';\n   */\n\n  $effect(() => {\n    announcedPageStatus.current = _('viewing_entry_search_results', {\n      values: {\n        terms: searchTerms.current,\n        count: entrySearchResults.current.length,\n      },\n    });\n  });\n</script>\n\n<Group aria-labelledby=\"search-results-entries\">\n  <!-- <h3 role=\"none\" id=\"search-results-entries\">{_('entries')}</h3> -->\n  <div role=\"none\">\n    {#if entrySearchResults.current.length}\n      <ListingGrid\n        viewType=\"list\"\n        aria-label={_('entries')}\n        aria-rowcount={entrySearchResults.current.length}\n      >\n        {#key searchTerms.current}\n          <InfiniteScroll items={entrySearchResults.current} itemKey=\"id\">\n            {#snippet renderItem(/** @type {EntrySearchResult} */ result)}\n              {#await sleep() then}\n                <EntryResultItem {result} />\n              {/await}\n            {/snippet}\n          </InfiniteScroll>\n        {/key}\n      </ListingGrid>\n    {:else if searchTerms.current}\n      <EmptyState>\n        <span role=\"none\">{_('no_entries_found')}</span>\n      </EmptyState>\n    {/if}\n  </div>\n</Group>\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Toolbar } from '@sveltia/ui';\n\n  import AssetResults from '$lib/components/search/asset-results.svelte';\n  import EntryResults from '$lib/components/search/entry-results.svelte';\n  import { searchMode } from '$lib/services/search';\n  import { env } from '$lib/services/user/env.svelte';\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      <EntryResults />\n    {/if}\n    {#if searchMode.current === 'assets'}\n      <AssetResults />\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 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 { assetGroups, listedAssets, showAssetOverlay } 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<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 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          <SecondarySidebar asset={focusedAsset.current}>\n            {#snippet children(/** @type {Asset} */ asset)}\n              <InfoPanel {asset} showPreview={true} />\n            {/snippet}\n            {#snippet fallback()}\n              <FolderInfoPanel />\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<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    dialogOpen,\n    FRAME_SRC_PARAMS,\n    getLibraryOptions,\n  } from '$lib/services/integrations/media-libraries/cloud/cloudinary';\n\n  let src = $state('');\n  let mlId = $state('');\n\n  onMount(() => {\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{#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 result of an asset operation. These live outside the Asset Library, because\n  an asset can be saved from anywhere the upload dialog reaches — dropping a file on the collection\n  assets sidebar, say — and the result should be reported wherever the user happens to be.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Toast } from '@sveltia/ui';\n\n  import { 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","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, ConfirmationDialog, Radio, RadioGroup, Toast } 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 { 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  // Committing to a remote repository takes a few seconds, and the confirmation dialog is gone by\n  // then, so the upload would otherwise happen with nothing on screen to say it’s under way\n  let uploading = $state(false);\n  let uploadFailed = $state(false);\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={async () => {\n    uploading = true;\n\n    try {\n      await saveAssets(\n        originalAsset\n          ? { files, folder, originalAssets }\n          : { files, folder, subfolderPath, replaceDuplicates: replaceFiles },\n        { commitType: 'uploadMedia' },\n      );\n    } catch (/** @type {any} */ ex) {\n      uploadFailed = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      uploading = false;\n      // Clear the selection whatever happened, so a failed upload doesn’t leave the store holding\n      // files that no dialog is showing any more\n      uploadingAssets.current = { folder: undefined, files: [] };\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<!-- `duration={0}` keeps this up until the upload settles, however long the commit takes -->\n<Toast show={uploading} duration={0}>\n  <Alert status=\"info\">{_('uploading_files_progress')}</Alert>\n</Toast>\n\n<Toast bind:show={uploadFailed}>\n  <Alert status=\"error\">{_('uploading_files_failed')}</Alert>\n</Toast>\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 mime from 'mime';\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\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 { _ } from '@sveltia/i18n';\n  import { stringify } from 'yaml';\n\n  import PageContainer from '$lib/components/common/page-container.svelte';\n  import { rawCmsConfig } from '$lib/services/config';\n</script>\n\n<PageContainer aria-label={_('site_configuration_editor')}>\n  {#snippet main()}\n    <div role=\"blockquote\" aria-label={_('cms_config')}>\n      <pre>{stringify(rawCmsConfig)}</pre>\n    </div>\n  {/snippet}\n</PageContainer>\n\n<style>\n  div {\n    flex: auto;\n    overflow: auto;\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 * @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 { resolveCollectionAndFile } from '$lib/services/contents/collection/files';\nimport { isAutoDuplicationEnabled } from '$lib/services/contents/draft';\nimport { revalidateField } from '$lib/services/contents/draft/validate/fields';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getLocalizedRelationValue } from '$lib/services/contents/fields/relation/helpers/locale';\n\n/**\n * @import { EntryDraft, FlattenedEntryContent, GetFieldArgs } from '$lib/types/private';\n * @import { Field, FieldKeyPath, LocaleCode } from '$lib/types/public';\n */\n\nconst PATH_MATCH_REGEX = /(?<path>.+?)\\.[^.]*$/;\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 createProxy}. Reading it in a reactive\n * context makes that context depend on the whole map at the cost of a single dependency, which is\n * how the shared value map snapshot is kept fresh without every reader walking all the 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 * 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 (!/^\\d+$/.test(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’s value is duplicated from the default locale to the other locales. That\n * is the case when the field has the `duplicate` i18n strategy, or, if the field has no `i18n`\n * option of its own, when the nearest ancestor that has one, such as the List or Object field it\n * belongs to, has the `duplicate` strategy. A duplicated List or Object field then holds the same\n * items and values in every locale, the way `normalizeContentMap()` copies it when an entry is\n * loaded, while a subfield 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) => getInheritedI18nOption(args) === 'duplicate';\n\n/**\n * Copy the default locale value to other locales if the field’s i18n strategy is `duplicate`.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {GetFieldArgs} args.getFieldArgs Arguments for the `getField` function.\n * @param {Field} args.fieldConfig Field configuration.\n * @param {LocaleCode} args.sourceLanguage Source locale.\n * @param {any} args.value Value to copy to other locales.\n */\nexport const copyDefaultLocaleValue = ({\n  draft,\n  getFieldArgs,\n  fieldConfig,\n  sourceLanguage,\n  value,\n}) => {\n  const { keyPath } = getFieldArgs;\n\n  Object.entries(draft.currentValues).forEach(([targetLanguage, content]) => {\n    // Don’t duplicate the value if the parent object doesn’t exist\n    if (keyPath.includes('.')) {\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      if (\n        !getField({ ...getFieldArgs, keyPath: parentKeyPath }) &&\n        !Object.keys(content).some((_keyPath) => _keyPath.startsWith(`${parentKeyPath}.`))\n      ) {\n        return;\n      }\n    }\n\n    // Keep the source `value` intact, as it’s used for the remaining target locales\n    const localizedValue = getLocalizedRelationValue({\n      fieldConfig,\n      value,\n      sourceLocale: sourceLanguage,\n      targetLocale: targetLanguage,\n    });\n\n    if (targetLanguage !== sourceLanguage && content[keyPath] !== localizedValue) {\n      content[keyPath] = localizedValue;\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`.\n *\n * The values live in a deeply reactive `$state` object behind the proxy, so a component reading a\n * single value only depends on that value. The proxy also counts its writes; see\n * {@link getValueMapVersion}.\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 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 auto-duplication should be performed for the given field.\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\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    /** @type {GetFieldArgs} */\n    const getFieldArgs = { collectionName, fileName, keyPath, valueMap, isIndexFile };\n    const fieldConfig = getField({ ...getFieldArgs });\n\n    return { valueMap, getFieldArgs, fieldConfig };\n  };\n\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  return new Proxy(/** @type {any} */ (values), {\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    get: (obj, key) => (key === VERSION_KEY ? version : 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      if (obj[keyPath] !== value) {\n        obj[keyPath] = value;\n        keys.add(keyPath);\n        version += 1;\n      }\n\n      // Skip the rest in some cases\n      if ([canonicalSlugKey].includes(keyPath)) {\n        return true;\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 });\n\n      if (!fieldConfig) {\n        return true;\n      }\n\n      // Copy value to other locales\n      if (shouldAutoDuplicate(fieldConfig, getFieldArgs)) {\n        copyDefaultLocaleValue({ draft, getFieldArgs, fieldConfig, sourceLanguage, value });\n      }\n\n      return true;\n    },\n    // eslint-disable-next-line jsdoc/require-jsdoc\n    deleteProperty: (obj, /** @type {FieldKeyPath} */ keyPath) => {\n      if (keyPath in obj) {\n        delete obj[keyPath];\n        keys.delete(keyPath);\n        version += 1;\n      }\n\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      if (!fieldConfig) {\n        return true;\n      }\n\n      // Remove the property from other locales\n      if (shouldAutoDuplicate(fieldConfig, getFieldArgs)) {\n        Object.entries(draft.currentValues).forEach(([targetLanguage, content]) => {\n          if (targetLanguage !== sourceLanguage && keyPath in content) {\n            delete content[keyPath];\n          }\n        });\n      }\n\n      return true;\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';\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 {\n    default: defaultValue,\n    output_code_only: outputCodeOnly = false,\n    keys: outputKeys = { code: 'code', lang: 'lang' },\n  } = /** @type {CodeField} */ (fieldConfig);\n\n  const value = dynamicValue !== undefined ? dynamicValue : defaultValue;\n\n  if (outputCodeOnly) {\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 }) => {\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);\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 { generateUUID } from '@sveltia/utils/crypto';\n\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  return replaceTemplateTags(value, (_match, placeholder) => {\n    const { value: tag, transformations } = parseTransformations(placeholder);\n    const val = replaceTemplateTag(tag, context);\n\n    if (transformations.length) {\n      return applyTransformations({ value: val, transformations, locale });\n    }\n\n    return val;\n  });\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 { isObject } from '@sveltia/utils/object';\n\nimport { isFieldRequired } from '$lib/services/contents/entry/fields';\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}.${key}`, val]),\n  );\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';\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.\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`.\n * @param {Field[]} args.fields Subfields of the item.\n * @param {GetDefaultValueMapFuncArgs} args.funcArgs Arguments given to the field’s function.\n */\nconst 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 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 '')\n    value = dynamicValue\n      .split(/,\\s*/)\n      .map((val) => val.trim())\n      .filter((val) => val !== '');\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","/**\n * @import { FieldKeyPath, NumberField } from '$lib/types/public';\n * @import { GetDefaultValueMapFuncArgs } from '$lib/types/private';\n */\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 { default: defaultValue, value_type: valueType = 'int' } = /** @type {NumberField} */ (\n    fieldConfig\n  );\n\n  const value = dynamicValue ?? defaultValue;\n  const isString = typeof value === 'string';\n\n  if (value === undefined) {\n    if (valueType === 'int' || valueType === 'float') {\n      return { [keyPath]: null };\n    }\n\n    return { [keyPath]: '' };\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  if (['int', 'int/string'].includes(valueType)) {\n    const parsedValue = isString ? Number.parseInt(value, 10) : value;\n\n    if (!Number.isInteger(parsedValue)) {\n      return {};\n    }\n\n    return { [keyPath]: valueType === 'int' ? parsedValue : String(parsedValue) };\n  }\n\n  if (['float', 'float/string'].includes(valueType)) {\n    const parsedValue = isString ? Number.parseFloat(value) : value;\n\n    if (!Number.isFinite(parsedValue)) {\n      return {};\n    }\n\n    return { [keyPath]: valueType === 'float' ? parsedValue : String(parsedValue) };\n  }\n\n  return {};\n};\n","import { isObject } from '@sveltia/utils/object';\nimport { flatten } from 'flat';\n\nimport { isFieldRequired } from '$lib/services/contents/entry/fields';\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 * Object fields do not support dynamic values.\n * @returns {Record<FieldKeyPath, any>} Default value map.\n */\nexport const getDefaultValueMap = ({\n  fieldConfig,\n  keyPath,\n  locale,\n  defaultLocale,\n  populateDefault,\n}) => {\n  const { default: defaultValue } = /** @type {ObjectField} */ (fieldConfig);\n  const { fields: subFields } = /** @type {ObjectFieldWithSubFields} */ (fieldConfig);\n  const { types } = /** @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(flatten(defaultValue)).forEach(([key, val]) => {\n      content[`${keyPath}.${key}`] = val;\n    });\n\n    return content;\n  }\n\n  if (!required || 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 without object-level default values and without types,\n  // populate default values from subfields if they exist and have defaults\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 { 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 * 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  let value = '';\n\n  if (dynamicValue !== undefined) {\n    try {\n      // Sanitize the given value to prevent XSS attacks as the preview may not be sanitized\n      value = stripTags(dynamicValue);\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      value = dynamicValue.replace(/<[^>]*>/g, '');\n    }\n  } else {\n    value = defaultValue || '';\n  }\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 [firstOption] = /** @type {SelectField} */ (config).options ?? [];\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.split(/,\\s*/).map((val) => val.trim())\n      : Array.isArray(defaultValue)\n        ? defaultValue.map(getOptionValue)\n        : getOptionValue(defaultValue);\n\n  const isArray = Array.isArray(value) && !!value.length;\n\n  if (!multiple) {\n    if (dynamicValue !== undefined) {\n      // For single select with dynamicValue, take the first item from split\n      const splitValue = dynamicValue.split(/,\\s*/).map((val) => val.trim());\n\n      return { [keyPath]: splitValue[0] || '' };\n    }\n\n    return {\n      [keyPath]: value !== undefined ? value : getEmptyOptionValue(getOptionValue(firstOption)),\n    };\n  }\n\n  if (isArray) {\n    return Object.fromEntries(value.map((val, index) => [`${keyPath}.${index}`, val]));\n  }\n\n  return { [keyPath]: [] };\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 { GET_DEFAULT_VALUE_MAP_FUNCTIONS } from '$lib/services/contents/fields/defaults';\nimport { isFieldI18nDisabled } from '$lib/services/contents/i18n/fields';\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` property.\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,\n  locale,\n  defaultLocale,\n  dynamicValues,\n}) => {\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    keyPath in dynamicValues && !/\\.\\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    Object.assign(\n      content,\n      getDefaultValue({\n        fieldConfig,\n        keyPath,\n        locale,\n        defaultLocale,\n        dynamicValue,\n        populateDefault: populateDefaultValue,\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\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 { suspendAutoDuplication } from '$lib/services/contents/draft';\nimport { createProxy, isDuplicatedField } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { getDefaultValues } from '$lib/services/contents/draft/defaults';\nimport { 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 {\n  isFieldI18nDisabled,\n  isFieldLocalized,\n  isFieldTranslatable,\n} from '$lib/services/contents/i18n/fields';\n\n/**\n * @import { EntryDraft, FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n * @import { Field, FieldKeyPath, HiddenField } 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` i18n strategy holds the same value in every locale, so an update has\n * to reach all of them; any other field is written to the 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  /**\n   * Check if the field is nested in a duplicated List or Object field.\n   * @param {EntryDraft} _draft Entry draft.\n   * @param {FieldKeyPath} _keyPath Key path of the field.\n   * @returns {boolean} Result.\n   */\n  const isNestedInDuplicatedField = (_draft, _keyPath) => {\n    const getFieldArgs = {\n      collectionName: _draft.collectionName,\n      fileName: _draft.fileName,\n      isIndexFile: _draft.isIndexFile,\n      keyPath: _keyPath,\n      valueMap: valueStore?.[locale],\n    };\n\n    // Look up the configuration rather than relying on the given `i18n`, which the caller may have\n    // defaulted to `false` for a field without the option, which would hide the ancestor’s strategy\n    return isDuplicatedField({\n      fieldConfig: getField(getFieldArgs) ?? /** @type {Field} */ ({ i18n }),\n      getFieldArgs,\n    });\n  };\n\n  const duplicated =\n    i18n === 'duplicate' ||\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    (!!draft &&\n      !!keyPath &&\n      valueStore === draft.currentValues &&\n      isNestedInDuplicatedField(draft, keyPath));\n\n  suspendAutoDuplication(() => {\n    Object.entries(valueStore ?? {}).forEach(([_locale, valueMap]) => {\n      if (_locale === locale || duplicated) {\n        callback(valueMap, _locale);\n      }\n    });\n  });\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.\n * @returns {FlattenedEntryContent} Updated content.\n */\nexport const copyDefaultLocaleValues = ({ draft, content, targetLanguage, keyPathPrefix }) => {\n  const { collectionName, fileName, collection, collectionFile, currentValues, isIndexFile } =\n    draft;\n\n  const { defaultLocale } = (collectionFile ?? collection)._i18n;\n  /** @type {FlattenedEntryContent} */\n  const defaultLocaleContent = toRaw(currentValues[defaultLocale]);\n  const newContent = { ...toRaw(content), ...defaultLocaleContent };\n  const getFieldArgs = { collectionName, fileName, valueMap: newContent, isIndexFile };\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` strategy, so it has to be kept rather than removed as 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.\n    if (TEXT_FIELD_TYPES.includes(fieldType) && isFieldTranslatable(i18n)) {\n      newContent[keyPath] = content[keyPath] ?? '';\n    }\n\n    // Support special case for the Hidden field with `default` value set to `{{locale}}`: if the\n    // field value is `{{locale}}`, replace it with the target locale\n    if (fieldType === 'hidden' && isFieldTranslatable(i18n)) {\n      const { default: defaultValue } = /** @type {HiddenField} */ (field);\n\n      if (defaultValue === '{{locale}}') {\n        newContent[keyPath] = 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  if (keyPathPrefix !== undefined) {\n    return Object.fromEntries(\n      Object.entries(newContent).filter(([keyPath]) => keyPath.startsWith(`${keyPathPrefix}.`)),\n    );\n  }\n\n  return 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 { flatten } from 'flat';\n\nimport { 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';\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 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 * 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: boolean[] }) => void } args.manipulate A\n * function to manipulate the list, which takes one object argument containing the value list, file\n * list and view state list. The typical usage is `list.splice()`.\n */\nexport const updateListField = ({\n  draft,\n  locale,\n  valueStoreKey = 'currentValues',\n  keyPath,\n  manipulate,\n}) => {\n  const { collection, collectionFile } = draft;\n  const { defaultLocale } = (collectionFile ?? collection)._i18n;\n  const [valueList, valueListRemainder] = getItemList(draft[valueStoreKey][locale], keyPath);\n\n  const [expanderStateList, expanderStateListRemainder] =\n    // Manipulation should only happen once with the default locale\n    locale === defaultLocale ? getItemList(draft.expanderStates._, keyPath) : [[], []];\n\n  manipulate({ valueList, expanderStateList });\n\n  suspendAutoDuplication(() => {\n    updateObject(draft[valueStoreKey][locale], {\n      ...flatten({ [keyPath]: valueList }),\n      ...valueListRemainder,\n    });\n\n    if (locale === defaultLocale) {\n      updateObject(draft.expanderStates._, {\n        ...flatten({ [keyPath]: expanderStateList }),\n        ...expanderStateListRemainder,\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 * @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 {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: { valueList: any[], expanderStateList: boolean[] }) => void } args.manipulate A\n * function to manipulate the list. See {@link updateListField}.\n */\nexport const updateListFieldForLocales = ({\n  draft,\n  locale,\n  i18n,\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  forEachTargetLocale(\n    { valueStore: draft[valueStoreKey], locale, i18n, draft, keyPath },\n    (_valueMap, _locale) => {\n      updateListField({\n        draft,\n        locale: _locale,\n        valueStoreKey,\n        keyPath,\n        manipulate:\n          !fieldConfig || _locale === locale\n            ? manipulate\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 });\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 */\nexport const addMultiValueItems = ({\n  draft,\n  locale,\n  valueStoreKey = 'currentValues',\n  keyPath,\n  newValues,\n  replaceIndex,\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.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 { 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 { getBlobRegex } from '@sveltia/utils/file';\nimport { toRaw } from '@sveltia/utils/object';\nimport { IndexedDB } from '@sveltia/utils/storage';\n\nimport { createDisplayBlobURL } from '$lib/services/assets/info';\nimport { backend } from '$lib/services/backends';\nimport { cmsConfigVersion } from '$lib/services/config';\nimport { isDraftReadonly } from '$lib/services/config/readonly';\nimport { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\nimport { isDraftModified, suspendAutoDuplication } 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';\n\n/**\n * @import {\n * AssetFolderInfo,\n * EntryDraft,\n * EntryDraftBackup,\n * LocaleContentMap,\n * LocaleSlugMap,\n * LocaleStateMap,\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/**\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.\n * @param {EntryDraft} draft Draft.\n * @returns {string} Entry slug. An empty string for a new entry.\n */\nexport const getBackupSlug = ({ fileName, originalEntry }) => fileName ?? originalEntry?.slug ?? '';\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 (\n    !(prefs.useDraftBackup ?? true) ||\n    !draft.interacted ||\n    isDraftReadonly(draft) ||\n    isArrayItemDraft(draft)\n  ) {\n    return;\n  }\n\n  const {\n    collectionName,\n    currentLocales = {},\n    currentSlugs = {},\n    currentValues = {},\n    files,\n    pendingEntries = [],\n  } = draft;\n\n  const slug = getBackupSlug(draft);\n\n  if (isDraftModified(draft)) {\n    // The draft is a `$state` proxy, which IndexedDB can’t clone, so every part of the backup has\n    // to be copied to a plain object. `File` objects are cloneable as they are\n    /** @type {EntryDraftBackup} */\n    const backup = {\n      timestamp: new Date(),\n      cmsConfigVersion: /** @type {string} */ (cmsConfigVersion.current),\n      collectionName,\n      slug,\n      currentLocales: /** @type {LocaleStateMap} */ (toRaw(currentLocales)),\n      currentSlugs: /** @type {LocaleSlugMap} */ (toRaw(currentSlugs)),\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      // The entries hold `File` objects among their changes, so a JSON round trip won’t do\n      pendingEntries: getSnapshot(pendingEntries),\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 {EntryDraftBackup} 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 * Restore a draft backup to the given entry draft.\n * @param {object} args Arguments.\n * @param {EntryDraftBackup} args.backup Backup to restore.\n * @param {EntryDraft} args.draft Entry draft to restore the backup to.\n */\nexport const restoreBackup = async ({ backup, draft }) => {\n  const { currentLocales, currentSlugs, currentValues, files, pendingEntries = [] } = backup;\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    // 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};\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  // 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 getBackup(collectionName, slug);\n\n  if (!backup) {\n    return;\n  }\n\n  const { timestamp } = backup;\n  const { promise, resolve } = Promise.withResolvers();\n\n  restoreDialogState.current = { show: true, timestamp, resolve };\n\n  // The promise will be resolved once the Restore or Discard button is clicked on the dialog\n  /** @type {boolean | undefined} */\n  const 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\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 getBackup(draft.collectionName, getBackupSlug(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  const { databaseName } = backend.current?.repository ?? {};\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 * 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  globalThis.clearTimeout(backupTimeout);\n\n  if (draft && backupDB) {\n    backupTimeout = globalThis.setTimeout(() => {\n      saveBackup(draft);\n    }, 500);\n  }\n};\n","<script>\n  import { _, locale as appLocale } from '@sveltia/i18n';\n  import { Alert, ConfirmationDialog, Toast } from '@sveltia/ui';\n\n  import { backupToastState, restoreDialogState } from '$lib/services/contents/draft/backup';\n  import { showContentOverlay } from '$lib/services/contents/editor';\n\n  const now = $derived(new Date());\n  const { resolve, timestamp } = $derived(restoreDialogState.current);\n  const sameYear = $derived(now.getUTCFullYear() === timestamp?.getUTCFullYear());\n  const sameMonth = $derived(sameYear && now.getUTCMonth() === timestamp?.getUTCMonth());\n  const sameDay = $derived(sameMonth && now.getUTCDate() === timestamp?.getUTCDate());\n  const datetime = $derived(\n    timestamp?.toLocaleString(appLocale.current, {\n      year: sameYear ? undefined : 'numeric',\n      month: sameDay ? undefined : 'short',\n      day: sameDay ? undefined : 'numeric',\n      hour: 'numeric',\n      minute: 'numeric',\n    }),\n  );\n\n  $effect(() => {\n    if (!showContentOverlay.current && restoreDialogState.current.show) {\n      // Close the dialog when the Content Editor is closed\n      restoreDialogState.current.show = false;\n      resolve?.();\n    }\n  });\n</script>\n\n<ConfirmationDialog\n  bind:open={restoreDialogState.current.show}\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 { getContext, setContext } from 'svelte';\n\nimport { isDraftModified } from '$lib/services/contents/draft';\n\n/**\n * @import { EntryDraft } 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/**\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(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 * 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 * 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 = 4000,\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  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 = 4000,\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      ...extraBody,\n    },\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 = 4000,\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 new Error('The response from the Messages API was cut off at the token limit.');\n  }\n\n  // The response can begin with `thinking` blocks and split the answer into several text blocks\n  /** @type {string[]} */\n  const texts = Array.isArray(data.content)\n    ? data.content\n        .filter(\n          (/** @type {unknown} */ block) =>\n            isObject(block) && block.type === 'text' && typeof block.text === 'string',\n        )\n        .map((/** @type {{ text: string }} */ { text }) => text)\n    : [];\n\n  if (!texts.length) {\n    throw new Error('Invalid response format from Messages API.');\n  }\n\n  return texts.join('').trim();\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 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 * Shared utilities for translation services.\n */\n\nimport { getLocaleLabel } from '$lib/services/contents/i18n';\n\n/**\n * @import {\n * AiCompletionOptions,\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 * Check if the given source and target languages are supported.\n * @param {LanguagePair} languages Language pair.\n * @returns {Promise<boolean>} True if both source and target languages are supported.\n */\nexport const availability = async ({ sourceLanguage, targetLanguage }) =>\n  !!normalizeLanguage(sourceLanguage) && !!normalizeLanguage(targetLanguage);\n\n/**\n * Resolve and validate source and target language names from locale codes.\n * @param {string} sourceLanguage Source locale code.\n * @param {string} targetLanguage Target locale code.\n * @returns {[string, string]} Tuple of [sourceLanguageName, targetLanguageName].\n * @throws {Error} When source or target locale is not supported.\n */\nexport const resolveLanguageNames = (sourceLanguage, targetLanguage) => {\n  const sourceLangName = normalizeLanguage(sourceLanguage);\n  const targetLangName = normalizeLanguage(targetLanguage);\n\n  if (!sourceLangName) {\n    throw new Error('Source locale is not supported.');\n  }\n\n  if (!targetLangName) {\n    throw new Error('Target locale is not supported.');\n  }\n\n  return [sourceLangName, targetLangName];\n};\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 {object} args.ai The service’s AI module.\n * @param {string} args.ai.apiLabel Label for the service used in error messages.\n * @param {string} args.ai.developerURL URL of the service’s developer site.\n * @param {string} args.ai.apiKeyURL URL of the page to create an API key.\n * @param {RegExp} args.ai.apiKeyPattern Pattern of a valid API key.\n * @param {(options: AiCompletionOptions) => Promise<string>} args.ai.complete AI completion\n * function.\n * @param {string} args.serviceId Service ID.\n * @param {string} args.serviceLabel Service label.\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: { apiLabel, developerURL, apiKeyURL, apiKeyPattern, complete },\n  serviceId,\n  serviceLabel,\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  serviceId: 'anthropic',\n  serviceLabel: 'Anthropic Claude',\n  model: 'claude-haiku-5-5',\n  extraOptions: { reasoning: 'none' },\n});\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 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","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  serviceId: 'deepseek',\n  serviceLabel: 'DeepSeek',\n  model: 'deepseek-flash',\n  extraOptions: { reasoning: 'none' },\n});\n","import { postJSON } from '$lib/services/integrations/ai/api';\n\n/**\n * @import { LanguagePair, 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.\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\n  const script = scriptTag\n    ? `${scriptTag[0].toUpperCase()}${scriptTag.slice(1).toLowerCase()}`\n    : undefined;\n\n  const region = regionTag?.toUpperCase();\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' || (!script && ['TW', 'HK', 'MO'].includes(region ?? ''))) {\n      return 'zh-TW';\n    }\n\n    if (script === 'Hans' || (!script && ['CN', 'SG'].includes(region ?? ''))) {\n      return 'zh-CN';\n    }\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.\n * @param {LanguagePair} languages Language pair.\n * @returns {Promise<boolean>} True if both source and target languages are supported.\n */\nexport const availability = async ({ sourceLanguage, targetLanguage }) =>\n  !!normalizeLanguage(sourceLanguage) && !!normalizeLanguage(targetLanguage);\n\n/**\n * Translate the given text with Google Cloud Translation API using the basic model and HTML format.\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 = normalizeLanguage(sourceLanguage) ?? '';\n  targetLanguage = normalizeLanguage(targetLanguage) ?? '';\n\n  if (!sourceLanguage) {\n    throw new Error('Source locale is not supported.');\n  }\n\n  if (!targetLanguage) {\n    throw new Error('Target locale is not supported.');\n  }\n\n  // Cloud Translation API v2 endpoint\n  const url = 'https://translation.googleapis.com/language/translate/v2';\n\n  const requestBody = {\n    q: texts,\n    source: sourceLanguage,\n    target: targetLanguage,\n    format: 'html',\n  };\n\n  const { data } = /** @type {{ data: { translations: { translatedText: string }[] } }} */ (\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  return data.translations.map((t) => t.translatedText.replace(/&#39;/g, \"'\"));\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","/**\n * Generic Google Gemini API client.\n * @see https://ai.google.dev/api/generate-content\n */\n\nimport { postJSON } from '$lib/services/integrations/ai/api';\n\n/**\n * @import { AiCompletionOptions } from '$lib/types/private';\n */\n\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\nexport const apiKeyPattern = /^AIza[a-zA-Z0-9_-]{35}$/;\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 = 4000,\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  if (!Array.isArray(data.candidates) || !data.candidates[0]?.content?.parts?.[0]) {\n    throw new Error('Invalid response format from Gemini API.');\n  }\n\n  return data.candidates[0].content.parts[0].text.trim();\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  serviceId: 'google-ai',\n  serviceLabel: 'Google Gemini',\n  model: 'gemini-3.5-flash-lite',\n  extraOptions: { responseFormat: 'application/json' },\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 apiLabel = 'Mistral AI API';\nexport const developerURL = 'https://docs.mistral.ai/';\nexport const apiKeyURL = 'https://console.mistral.ai/home?profile_dialog=api-keys';\n// Anchored, and a Google key (`AIza…`) excluded, so a key for another service entered while this\n// one is selected isn’t accepted and sent to the wrong API\nexport const apiKeyPattern = /^(?!AIza)[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","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  serviceId: 'mistral',\n  serviceLabel: 'Mistral',\n  model: 'mistral-small-latest',\n  extraOptions: { reasoning: 'none' },\n});\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 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 { 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 * 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/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  serviceId: 'openai',\n  serviceLabel: 'OpenAI GPT',\n  model: 'gpt-6-luna',\n});\n","import { parse } from 'marked';\n\nimport { loadModule } from '$lib/services/app/dependencies';\nimport { getInheritedI18nOption } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { copyFromLocaleToast, translatorApiKeyDialogState } from '$lib/services/contents/editor';\nimport { 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 { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\nimport { translator } from '$lib/services/integrations/translators';\nimport { prefs } from '$lib/services/user/prefs.svelte';\nimport { escapeHTML } from '$lib/services/utils/string';\n\n/**\n * @import { EntryDraft, InternalLocaleCode, LocaleContentMap } from '$lib/types/private';\n * @import { Field, FieldKeyPath, ListField, RichTextField } from '$lib/types/public';\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 * Turndown service instance, created on first use.\n * @type {Promise<import('turndown')> | undefined}\n */\nlet turndownServicePromise;\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 = async () => {\n  turndownServicePromise ??= (async () => {\n    /** @type {{ default: typeof import('turndown') }} */\n    let module;\n\n    try {\n      module = await loadModule('turndown', 'lib/turndown.browser.es.js');\n    } catch (error) {\n      // Let a later call try again, e.g. once the network is back\n      turndownServicePromise = undefined;\n      throw error;\n    }\n\n    const { default: TurndownService } = module;\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\n  return turndownServicePromise;\n};\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 * 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 { collectionName, fileName, currentValues, isIndexFile } = draft;\n  const { sourceLanguage, targetLanguage, keyPath = '', translate = false } = options;\n  const valueMap = currentValues[sourceLanguage];\n  const getFieldArgs = { collectionName, fileName, valueMap, isIndexFile };\n\n  return Object.fromEntries(\n    Object.entries(valueMap)\n      .map(([_keyPath, value]) => {\n        const targetLocaleValue = currentValues[targetLanguage][_keyPath];\n        const field = getField({ ...getFieldArgs, keyPath: _keyPath });\n        const fieldType = field?.widget ?? 'string';\n\n        if (\n          (keyPath && !isKeyPathWithin(_keyPath, keyPath)) ||\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. An item of a List field without subfields has no configuration\n          // of its own, so it takes the option of the List field\n          !isFieldTranslatable(\n            getInheritedI18nOption({\n              fieldConfig: field ?? /** @type {Field} */ ({}),\n              getFieldArgs: { ...getFieldArgs, keyPath: _keyPath },\n            }),\n          ) ||\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\n          (!keyPath && translate && !!targetLocaleValue)\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 */\nexport const translateFields = async ({ currentValues, options, copingFieldMap }) => {\n  const { serviceId } = translator.current;\n  const { sourceLanguage, targetLanguage } = options;\n  const count = Object.keys(copingFieldMap).length;\n  let apiKey = prefs.apiKeys?.[serviceId];\n\n  if (!apiKey) {\n    const { promise, resolve } = Promise.withResolvers();\n\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 and DeepL with HTML tag handling. A Markdown value is converted to HTML for it, a\n    // plain text value is escaped, so that its special characters are read as text, and an HTML\n    // 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    Object.entries(copingFieldMap).forEach(([_keyPath, { format }], index) => {\n      const value = translatedValues[index];\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, sourceLanguage });\n  } catch (ex) {\n    // @todo Show a detailed error message.\n    updateToast('error', 'translation.error', { count, sourceLanguage });\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.\n * @param {object} args Arguments.\n * @param {EntryDraft} args.draft Entry draft.\n * @param {CopyOptions} args.options Copy options.\n */\nexport const copyFromLocale = async ({ draft, options }) => {\n  const { sourceLanguage, translate = false } = options;\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    await translateFields({ currentValues, options, copingFieldMap });\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    otherLocales,\n    keyPath = '',\n    translate = false,\n    submenu = false,\n    /* eslint-enable prefer-const */\n  } = $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 6 -- 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      });\n    }\n  };\n</script>\n\n{#snippet localeItems()}\n  {#each otherLocales as otherLocale (otherLocale)}\n    {@const localeLabel = getLocaleLabel(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 {\n    /* eslint-disable prefer-const */\n    children = undefined,\n    ...rest\n    /* eslint-enable prefer-const */\n  } = $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      @media (hover: hover) {\n        &:not(:hover) > 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 {\n    /* eslint-disable prefer-const */\n    scope,\n    available,\n    separator = true,\n    onSelect,\n    /* eslint-enable prefer-const */\n  } = $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 } 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 {\n    /* eslint-disable prefer-const */\n    size = 'medium',\n    locale,\n    otherLocales,\n    keyPath = '',\n    /* eslint-enable prefer-const */\n  } = $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  /**\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 6 -- 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      });\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    <!-- @todo Replace `title` with a native tooltip -->\n    <Button\n      variant=\"ghost\"\n      {size}\n      iconic\n      popupPosition=\"bottom-right\"\n      aria-label={label}\n      title={label}\n      {disabled}\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    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","<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 {\n    /* eslint-disable prefer-const */\n    id = undefined,\n    live = 'polite',\n    children,\n    /* eslint-enable prefer-const */\n  } = $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","<!--\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    /* eslint-disable prefer-const */\n    fieldId,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\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 {\n    /* eslint-disable prefer-const */\n    currentValue = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n{#if typeof currentValue === 'boolean'}\n  <p>\n    {_(`boolean.${currentValue}`)}\n  </p>\n{/if}\n","import { untrack } from 'svelte';\n\nimport { getValueMapVersion } from '$lib/services/contents/draft/create/proxy.svelte';\n\n/**\n * @import {\n * DraftValueStoreKey,\n * EntryDraft,\n * FlattenedEntryContent,\n * InternalLocaleCode,\n * } from '$lib/types/private';\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","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","<!--\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  import { getContext, tick } from 'svelte';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { trackPendingFieldUpdate } from '$lib/services/contents/editor/pending';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorContext, 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 {FieldEditorContext} */\n  const { valueStoreKey = 'currentValues' } = getContext('field-editor') ?? {};\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\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(getValueMapSnapshot(entryDraft.current, locale, valueStoreKey));\n  const codeKeyPath = $derived(`${keyPath}.${outputKeys.code}`);\n  const langKeyPath = $derived(`${keyPath}.${outputKeys.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        lang = '';\n      } else if (lang !== _lang) {\n        lang = _lang;\n      }\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    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    /** @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    if (!Object.keys(updates).length) {\n      return;\n    }\n\n    const valueStore = draft[valueStoreKey][locale];\n\n    // This runs from an effect, so defer the write to the draft like `<FieldEditor>` does: a write\n    // made while an effect is running makes Svelte walk the derived graph below the value map\n    // without memoizing, which takes exponentially longer with each level of nesting\n    queueMicrotask(() => {\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  $effect(() => {\n    if (!pending) {\n      return undefined;\n    }\n\n    /** @type {PromiseWithResolvers<void>} */\n    const { promise, resolve } = Promise.withResolvers();\n\n    trackPendingFieldUpdate(promise);\n\n    // Settle once the value has reached the draft, which `setCurrentValue()` writes in a microtask,\n    // or when the editor goes away\n    return async () => {\n      await tick();\n      resolve();\n    };\n  });\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 { getValueMapSnapshot } 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 {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    fieldConfig,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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(getValueMapSnapshot(entryDraft.current, locale));\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  @todo Replace the native `<input>` with a custom component.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, 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    /* eslint-disable prefer-const */\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\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   * 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      return;\n    }\n\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  /**\n   * Update {@link currentValue} based on {@link inputValue} and {@link inputAlphaValue}.\n   */\n  const setCurrentValue = () => {\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  <input\n    id=\"{id}-picker\"\n    type=\"color\"\n    bind:value={inputValue}\n    disabled={readonly}\n    aria-invalid={invalid}\n    aria-readonly={readonly}\n    aria-required={required}\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\n  input {\n    font-family: var(--sui-textbox-font-family);\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 {\n    /* eslint-disable prefer-const */\n    fieldConfig,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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    /* eslint-disable prefer-const */\n    fieldId,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\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","<!--\n  @component\n  Implement the preview for a Compute field.\n-->\n<script>\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\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 | number | undefined} currentValue Field value.\n   */\n\n  /** @type {FieldPreviewProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<p lang={getCanonicalLocale(locale)} dir={getDirection(locale)}>{currentValue}</p>\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 {\n    /* eslint-disable prefer-const */\n    path,\n    caption,\n    children = undefined,\n    /* eslint-enable prefer-const */\n  } = $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 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 {\n    /* eslint-disable prefer-const */\n    rootLabel,\n    path,\n    onNavigate = undefined,\n    /* eslint-enable prefer-const */\n  } = $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 {\n    /* eslint-disable prefer-const */\n    value,\n    ariaLabel,\n    selected,\n    viewType = 'grid',\n    multiple,\n    onChange,\n    children,\n    /* eslint-enable prefer-const */\n  } = $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","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Listbox } from '@sveltia/ui';\n\n  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [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 {string} [ariaLabel] Accessible name of the list. Defaults to “Available Images”.\n   * @property {(detail: { value: string }) => void} [onChange] Custom `change` event handler.\n   * @property {Snippet} [children] Slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    viewType = 'grid',\n    gridId = undefined,\n    multiple = false,\n    ariaLabel = undefined,\n    onChange = undefined,\n    children = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div role=\"none\" class=\"wrapper\">\n  <Listbox\n    id={gridId}\n    class={viewType}\n    {multiple}\n    ariaLabel={ariaLabel ?? _('assets_dialog.available_images')}\n    onChange={(event) => {\n      onChange?.(event.detail);\n    }}\n  >\n    {@render children?.()}\n  </Listbox>\n</div>\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  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    /* eslint-disable prefer-const */\n    subfolders,\n    viewType = 'grid',\n    onOpen = undefined,\n    multiple = false,\n    selectedPaths = [],\n    onSelect = undefined,\n    /* eslint-enable prefer-const */\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","import { locale as appLocale } from '@sveltia/i18n';\n\nimport { fetchPages } from '$lib/services/integrations/media-libraries/paging';\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`.\n * @param {string} locale Locale code.\n * @returns {string | undefined} Language and script, or `undefined` if the locale code is invalid.\n */\nconst getLanguageScript = (locale) => {\n  try {\n    const { language, script } = new Intl.Locale(locale).maximize();\n\n    return `${language}-${script}`;\n  } catch {\n    return undefined;\n  }\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","import {\n  fetchJSON,\n  fetchPagedResults,\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 {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: `<a href=\"${url}\">Photo by ${photographer} on Pexels</a>`,\n  }));\n\n/**\n * Fetch curated pictures.\n * @param {MediaLibraryFetchOptions} options Options.\n * @returns {Promise<ExternalAsset[]>} Assets.\n * @see https://www.pexels.com/api/documentation/\n * @todo Support video files.\n */\nexport const list = async ({ apiKey }) => {\n  const headers = { Authorization: apiKey };\n  const params = new URLSearchParams(SEARCH_PARAMS);\n  /** @type {FetchResult[]} */\n  const results = (await fetchJSON(`${ENDPOINT}/curated?${params}`, { headers })).photos;\n\n  return parseResults(results);\n};\n\n/**\n * Search images or fetch curated pictures if no query is given.\n * @param {string} query Search query.\n * @param {MediaLibraryFetchOptions} options Options.\n * @returns {Promise<ExternalAsset[]>} Assets.\n * @see https://www.pexels.com/api/documentation/\n * @todo Support video files.\n */\nexport const search = async (query, { apiKey }) => {\n  const headers = { Authorization: apiKey };\n\n  const params = new URLSearchParams({\n    ...SEARCH_PARAMS,\n    query,\n    locale: getLocale(),\n  });\n\n  /**\n   * Fetch a page of search results.\n   * @param {number} page Page number.\n   * @returns {Promise<{ photos: FetchResult[], next_page?: string }>} Response.\n   */\n  const fetchPage = (page) => {\n    params.set('page', String(page));\n\n    return fetchJSON(`${ENDPOINT}/search?${params}`, { headers });\n  };\n\n  /**\n   * Extract the results from a page.\n   * @param {{ photos: FetchResult[], next_page?: string }} response Response.\n   * @returns {{ results: FetchResult[], hasMore: boolean }} Results and whether another page\n   * follows.\n   */\n  const parsePage = ({ photos, next_page: nextPage }) => ({ results: photos, hasMore: !!nextPage });\n  const results = await fetchPagedResults({ maxPages: 2, fetchPage, parsePage });\n\n  return parseResults(results);\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 {\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 {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: /** @type {string} */ (previewURL.split('/').pop()).replace('_150.', '_1280.'),\n      kind: 'image',\n      credit: `<a href=\"${pageURL}\">Photo by ${user} on Pixabay</a>`,\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.\n * @param {MediaLibraryFetchOptions} options Options.\n * @returns {Promise<ExternalAsset[]>} Assets.\n * @see https://pixabay.com/api/docs/\n * @todo Support video files.\n */\nexport const list = async ({ apiKey }) => {\n  const params = new URLSearchParams({\n    ...SEARCH_PARAMS,\n    key: apiKey,\n    lang: getLocale(),\n    editors_choice: String(true),\n  });\n\n  /** @type {FetchResult[]} */\n  const results = (await fetchJSON(`${ENDPOINT}/?${params}`)).hits;\n\n  return parseResults(results);\n};\n\n/**\n * Search images or fetch curated pictures if no query is given.\n * @param {string} query Search query.\n * @param {MediaLibraryFetchOptions} options Options.\n * @returns {Promise<ExternalAsset[]>} Assets.\n * @see https://pixabay.com/api/docs/\n * @todo Support video files.\n */\nexport const search = async (query, { apiKey }) => {\n  const params = new URLSearchParams({\n    ...SEARCH_PARAMS,\n    key: apiKey,\n    lang: getLocale(),\n    q: query,\n  });\n\n  /** @type {FetchResult[]} */\n  const results = (await fetchJSON(`${ENDPOINT}/?${params}`)).hits;\n\n  return parseResults(results);\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 {\n  fetchJSON,\n  fetchPagedResults,\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 */\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    }) => ({\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:\n        `Photo by <a href=\"https://unsplash.com/@${username}?${CREDIT_LINK_PARAMS}\">${name}</a> on ` +\n        `<a href=\"https://unsplash.com/?${CREDIT_LINK_PARAMS}\">Unsplash</a>`,\n    }),\n  );\n\n/**\n * Fetch curated pictures.\n * @param {MediaLibraryFetchOptions} options Options.\n * @returns {Promise<ExternalAsset[]>} Assets.\n * @see https://unsplash.com/documentation\n * @todo Support video files.\n */\nexport const list = async ({ apiKey }) => {\n  const headers = { Authorization: `Client-ID ${apiKey}` };\n  const params = new URLSearchParams(SEARCH_PARAMS);\n  /** @type {FetchResult[]} */\n  const results = await fetchJSON(`${ENDPOINT}/photos?${params}`, { headers });\n\n  return parseResults(results);\n};\n\n/**\n * Search images or fetch curated pictures if no query is given.\n * @param {string} query Search query.\n * @param {MediaLibraryFetchOptions} options Options.\n * @returns {Promise<ExternalAsset[]>} Assets.\n * @see https://unsplash.com/documentation\n * @todo Support video files.\n */\nexport const search = async (query, { apiKey }) => {\n  const headers = { Authorization: `Client-ID ${apiKey}` };\n  const params = new URLSearchParams({ ...SEARCH_PARAMS, query, lang: getLocale() });\n\n  /**\n   * Fetch a page of search results.\n   * @param {number} page Page number.\n   * @returns {Promise<{ results: FetchResult[], total_pages: number }>} Response.\n   */\n  const fetchPage = (page) => {\n    params.set('page', String(page));\n\n    return fetchJSON(`${ENDPOINT}/search/photos?${params}`, { headers });\n  };\n\n  /**\n   * Extract the results from a page.\n   * @param {{ results: FetchResult[], total_pages: number }} response Response.\n   * @param {number} page Page number.\n   * @returns {{ results: FetchResult[], hasMore: boolean }} Results and whether another page\n   * follows.\n   */\n  const parsePage = ({ results, total_pages: totalPages }, page) => ({\n    results,\n    hasMore: page < totalPages,\n  });\n\n  const results = await fetchPagedResults({ maxPages: 5, fetchPage, parsePage });\n\n  return parseResults(results);\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};\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","import { getFolderPublicPath } from '$lib/services/assets/info';\nimport { canBrowseSubfolders, getRelativePath } from '$lib/services/assets/subfolders';\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 * 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 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  @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 { Alert, EmptyState, InfiniteScroll, Toast } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\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 SubfolderStrip from '$lib/components/assets/browser/subfolder-strip.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 { getSelectionWithResource } from '$lib/services/assets/browser/select-assets-dialog.svelte';\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 { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import {\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 {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    /* eslint-disable prefer-const */\n    kind,\n    fieldConfig = undefined,\n    multiple = false,\n    searchTerms = '',\n    serviceProps,\n    gridId = undefined,\n    selectedResources = $bindable([]),\n    /* eslint-enable prefer-const */\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  } = $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  let newFolderDialogOpen = $state(false);\n  let folderCreationFailed = $state(false);\n  /** @type {string | undefined} */\n  let error = $state();\n  /** @type {{ show: boolean, status: 'info' | 'error', length: number }} */\n  let uploadingToast = $state({ show: false, status: 'info', length: 0 });\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   * ID of the latest {@link getAssets} request. A request made earlier, e.g. a search for the terms\n   * typed before, can come back after a later one, and its result must not replace the latest one.\n   */\n  let latestRequestId = 0;\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    latestRequestId += 1;\n\n    const requestId = latestRequestId;\n\n    listedAssets = null;\n    error = undefined;\n\n    try {\n      /** @type {ExternalAsset[]} */\n      let assets;\n      /** @type {string[] | undefined} */\n      let emptyFolders;\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        ({ assets, folders: emptyFolders } = await browse(listFetchOptions));\n      } else {\n        assets = (await list?.(listFetchOptions)) ?? [];\n      }\n\n      if (requestId !== latestRequestId) {\n        return;\n      }\n\n      listedAssets = assets;\n\n      if (emptyFolders) {\n        folders = emptyFolders;\n      }\n    } catch (ex) {\n      if (requestId !== latestRequestId) {\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   * Handle `Drop` event to upload files.\n   * @param {File[]} files Dropped files.\n   */\n  export const uploadFiles = async (files) => {\n    if (!upload) {\n      return;\n    }\n\n    const prepared = await prepareExternalUploads(files, allMediaLibraryOptions);\n\n    files = prepared.validFiles;\n    rejectedFilesAlert?.report(prepared);\n\n    if (!files.length) {\n      return;\n    }\n\n    uploadingToast = { show: true, status: 'info', length: files.length };\n\n    try {\n      // The files go to the folder being browsed, or the one the search started from\n      const uploaded = await upload(files, { ...listFetchOptions, dirPath });\n      const resources = await Promise.all(uploaded.map((asset) => getResource(asset)));\n\n      selectedResources = resources.filter((r) => !!r).slice(0, multiple ? undefined : 1);\n      listedAssets = mergeUploadedExternalAssets(uploaded, listedAssets ?? []);\n    } catch {\n      uploadingToast = { show: true, status: 'error', length: files.length };\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 = async (name) => {\n    const path = dirPath ? `${dirPath}/${name}` : name;\n\n    try {\n      await /** @type {NonNullable<typeof createFolder>} */ (createFolder)(path, listFetchOptions);\n      folders = [...folders, path];\n    } catch (ex) {\n      folderCreationFailed = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\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   * 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        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    <div role=\"none\" class=\"grid-wrapper\">\n      {#if subfolders.length}\n        <SubfolderStrip\n          {subfolders}\n          {viewType}\n          onOpen={({ path }) => {\n            dirPath = path;\n          }}\n        />\n      {/if}\n      <SimpleImageGrid {viewType} {gridId} {multiple}>\n        <InfiniteScroll items={panelAssets} itemKey=\"id\">\n          {#snippet renderItem(/** @type {ExternalAsset} */ asset)}\n            {#await sleep() then}\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            {/await}\n          {/snippet}\n        </InfiniteScroll>\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<Toast bind:show={uploadingToast.show}>\n  <Alert status={uploadingToast.status}>\n    {#if uploadingToast.status === 'info'}\n      {_('uploading_files_progress')}\n    {/if}\n    {#if uploadingToast.status === 'error'}\n      {_('uploading_files_failed')}\n    {/if}\n  </Alert>\n</Toast>\n\n<RejectedFilesAlertDialog bind:this={rejectedFilesAlert} {maxSize} />\n\n<Toast bind:show={folderCreationFailed}>\n  <Alert status=\"error\">{_('creating_folder_failed')}</Alert>\n</Toast>\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, InfiniteScroll } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\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 SubfolderStrip from '$lib/components/assets/browser/subfolder-strip.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    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\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    {#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 filteredItems.length}\n      <SimpleImageGrid\n        {multiple}\n        {gridId}\n        {viewType}\n        ariaLabel={_(`assets_dialog.available_${kind === 'image' ? 'images' : 'files'}`)}\n      >\n        <InfiniteScroll items={filteredItems} itemKey=\"key\">\n          {#snippet renderItem(/** @type {{ asset: Asset, relPath: string, key: string }} */ item)}\n            {#await sleep() then}\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\n                  kind={assetKind}\n                  {asset}\n                  alt={relPath}\n                  variant=\"tile\"\n                  {checkerboard}\n                />\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            {/await}\n          {/snippet}\n        </InfiniteScroll>\n      </SimpleImageGrid>\n    {/if}\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 {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    /* eslint-disable prefer-const */\n    multiple = false,\n    kind = undefined,\n    selectFolder = 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    /* eslint-enable prefer-const */\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<DropZone bind:this={dropZone} disabled={selectFolder} {multiple} {accept} {onDrop}>\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","import { getDuplicateFiles } from '$lib/services/assets';\n\n/**\n * @import { Asset } from '$lib/types/private';\n */\n\n/**\n * @typedef {object} DuplicatesState\n * @property {number} count Number of duplicate files.\n * @property {string} name Name of the first duplicate file.\n * @property {boolean} showDialog Whether to show the duplicates dialog.\n * @property {(value: boolean | undefined) => void} resolve Function to resolve the promise.\n */\n\n/** @type {DuplicatesState} */\nconst DEFAULT_STATE = {\n  count: 0,\n  name: '',\n  showDialog: false,\n  // eslint-disable-next-line jsdoc/require-jsdoc\n  resolve: () => {},\n};\n\n/** @type {DuplicatesState} */\nexport const duplicates = $state({ ...DEFAULT_STATE });\n\n/**\n * Check for duplicate files and ask the user if they want to replace them.\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  const { promise, resolve } = Promise.withResolvers();\n\n  Object.assign(duplicates, {\n    count,\n    name: dupFiles[0].name,\n    showDialog: true,\n    resolve,\n  });\n\n  const replace = await promise;\n\n  // Reset state\n  Object.assign(duplicates, { ...DEFAULT_STATE });\n\n  return replace;\n};\n","import { isURL } from '@sveltia/utils/string';\nimport equal from 'fast-deep-equal';\n\nimport { fillInternalPathTemplate } from '$lib/services/assets';\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 { getEntryFolderPath } from '$lib/services/contents/entry/paths';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { createPath, getDirName } from '$lib/services/utils/file';\nimport { decodeURISafely } from '$lib/services/utils/url';\n\n/**\n * @import {\n * Asset,\n * AssetFolderInfo,\n * AssetLibraryFolderMap,\n * Entry,\n * EntryDraft,\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} Default asset library folder.\n */\nexport const getDefaultAssetFolder = (folderMap) =>\n  // There is always at least one enabled folder in the map, so this will never be undefined\n  /** @type {AssetFolderInfo} */ (Object.values(folderMap).find(({ enabled }) => enabled)?.folder);\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 * @returns {string | undefined} Target folder path.\n */\nexport const getTargetFolderPath = ({ entry, folder }) => {\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 }) ??\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  if (entry) {\n    return createPath([getEntryFolderPath(entry), subPath]);\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  if (!value) {\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 and kind.\n * @param {object} args Arguments.\n * @param {'image' | undefined} args.kind Asset kind.\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 {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  folder,\n  folderPath,\n  unsavedAssets,\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    savedAssets: allAssets.current.filter(isInSelectedFolder),\n    unsavedAssets: unsavedAssets.filter(isInSelectedFolder),\n    slugificationEnabled,\n  });\n\n  return (\n    [...resolved.unsavedAssets, ...resolved.savedAssets]\n      .filter((asset) => !kind || kind === asset.kind)\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 { 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 { getEntryAssetFolderPath } from '$lib/services/contents/draft/save/assets';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { createPath, getGitHash } from '$lib/services/utils/file';\nimport { LINK_SANITIZE_OPTIONS } from '$lib/services/utils/string';\n\n/**\n * @import { Asset, AssetFolderInfo, EntryDraft, SelectedResource } 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 */\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 * @returns {Promise<string | undefined>} Blob URL.\n */\nexport const getExistingBlobURL = async ({ draft, file, folder, subfolderPath = '' }) => {\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      ) {\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 * @returns {Asset[]} Filtered saved assets.\n */\nconst getSavedAssetsForEntry = (draft, folder) => {\n  const savedAssets = allAssets.current;\n\n  if (!folder?.entryRelative) {\n    return savedAssets;\n  }\n\n  const { originalEntry, defaultLocale, collection } = draft;\n  const entryFilePath = originalEntry?.locales[defaultLocale]?.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 * 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 * @returns {Promise<ProcessResourceResult>} Result of processing the resource.\n */\nexport const processResource = async ({ draft, resource, libraryConfig }) => {\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 });\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      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      const sha = await getGitHash(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\n      const existingAsset = [\n        ...getSavedAssetsForEntry(draft, folder),\n        ...(await getUnsavedAssets({ draft })),\n      ].find((a) => a.sha === sha && equal(a.folder, folder));\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      });\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","<script>\n  import { _ } from '@sveltia/i18n';\n  import {\n    Button,\n    Dialog,\n    EmptyState,\n    FilePicker,\n    Icon,\n    Listbox,\n    Option,\n    OptionGroup,\n    SearchBar,\n    Select,\n    TextInput,\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 CreateSubfolderDialog from '$lib/components/assets/list/create-subfolder-dialog.svelte';\n  import ViewSwitcher from '$lib/components/common/page-toolbar/view-switcher.svelte';\n  import {\n    getFirstDefaultLibraryName,\n    getInsertedResources,\n    getPickedFolderPublicPaths,\n    getStockAssetProviderEntries,\n    isFolderOffered,\n    sortServicesByName,\n  } from '$lib/services/assets/browser/select-assets-dialog.svelte';\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 {\n    getTargetFolderPath,\n    hasSameAsset,\n    listAssets,\n  } from '$lib/services/contents/fields/file/helpers';\n  import {\n    convertFileItemToAsset,\n    getUnsavedAssets,\n  } from '$lib/services/contents/fields/file/process';\n  import { getMediaLibraryOptions } from '$lib/services/integrations/media-libraries';\n  import {\n    activated as cloudinaryActivated,\n    dialogOpen as cloudinaryDialogOpen,\n  } from '$lib/services/integrations/media-libraries/cloud/cloudinary';\n  import { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\n  import { allStockAssetProviders } from '$lib/services/integrations/media-libraries/stock';\n  import { normalize } from '$lib/services/search/util';\n  import { env } from '$lib/services/user/env.svelte';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n  import { createPath, getDirName, getGitHash } from '$lib/services/utils/file';\n  import { SUPPORTED_IMAGE_TYPES } from '$lib/services/utils/media/image';\n  import { watchAsync } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import {\n   * Asset,\n   * AssetLibraryFolderMap,\n   * AssetLibraryFolderMapKey,\n   * AssetSubfolder,\n   * EntryDraft,\n   * MediaLibraryAssetKind,\n   * MediaLibraryService,\n   * SelectAssetsView,\n   * SelectedResource,\n   * } from '$lib/types/private';\n   * @import { MediaField, StockAssetProviderName } from '$lib/types/public';\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 {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    /* eslint-disable prefer-const */\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    fieldConfig,\n    assetLibraryFolderMap,\n    enabledCloudServiceEntries,\n    onSelect = undefined,\n    onClose = undefined,\n    pendingFiles = $bindable([]),\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const elementIdPrefix = $props.id();\n\n  let enteredURL = $state('');\n  let rawSearchTerms = $state('');\n  let libraryName = $state('default-global');\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 {Asset[]} */\n  let unsavedAssets = $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\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 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  const targetFolderPath = $derived(\n    getTargetFolderPath({ entry: draft?.originalEntry, folder: selectedFolder }),\n  );\n  const slugificationEnabled = $derived(\n    getDefaultMediaLibraryOptions({ fieldConfig }).config.slugify_filename,\n  );\n  const listedAssets = $derived(\n    listAssets({\n      kind,\n      folder: selectedFolder,\n      folderPath: targetFolderPath,\n      unsavedAssets,\n      slugificationEnabled,\n    }),\n  );\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   * 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  /** Names already taken in the browsed directory, which a new folder can’t be given. */\n  const takenNames = $derived(\n    getTakenNames({ subfolders, fileNames: panelAssets.map(({ name }) => name) }),\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 enabledStockAssetProviderEntries = $derived(\n    getStockAssetProviderEntries({ fieldConfig, selectFolder, isDefaultLibraryEnabled }),\n  );\n  const isEnabledMediaService = $derived(\n    enabledStockAssetProviderEntries.some(\n      ([serviceId, { authType }]) =>\n        serviceId === libraryName && (authType === 'none' || !!prefs.apiKeys?.[libraryName]),\n    ),\n  );\n  const enabledExternalServiceEntries = $derived(\n    [...cloudServiceEntries, ...enabledStockAssetProviderEntries].sort(sortServicesByName),\n  );\n  const isCloudLibrary = $derived(\n    cloudServiceEntries.map(([serviceId]) => serviceId).includes(libraryName),\n  );\n  const isStockLibrary = $derived(\n    enabledStockAssetProviderEntries\n      .map(([serviceId]) => serviceId)\n      .includes(/** @type {any} */ (libraryName)),\n  );\n  const Selector = $derived(env.isSmallScreen ? Select : Listbox);\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 })) {\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 folder the CMS itself is served from are read-only\n    if (browsingCmsFolder) {\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    unsavedAssets = [];\n    selectedResources = [];\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    onSelect?.(getInsertedResources({ resources: selectedResources, targetFolderPath }));\n  };\n\n  $effect.pre(() => {\n    const firstDefaultLibraryName = getFirstDefaultLibraryName({\n      assetLibraryFolderMap,\n      isDefaultLibraryEnabled,\n      selectFolder,\n    });\n\n    if (firstDefaultLibraryName) {\n      // Select the first enabled folder\n      libraryName = firstDefaultLibraryName;\n    } else if (untrack(() => pendingFiles.length)) {\n      // Select the first cloud storage service, which can take the files to be uploaded\n      libraryName = cloudServiceEntries[0]?.[0] ?? enabledExternalServiceEntries[0]?.[0];\n    } else {\n      // Select the first available external service, if any. There can be none when a folder is\n      // to be selected but the field has no folder that can be browsed\n      libraryName = enabledExternalServiceEntries[0]?.[0] ?? '';\n    }\n  });\n\n  // A read started for an earlier state of the draft can be answered after a later one, which\n  // `watchAsync` takes care of\n  watchAsync(\n    async () => {\n      // Somehow we need to snapshot `droppedAssets` here to make Svelte aware of its changes\n      void $state.snapshot(droppedAssets);\n\n      return [\n        // The draft’s files are read synchronously, so their changes are tracked as well\n        ...(draft?.files ? await getUnsavedAssets({ draft, targetFolderPath }) : []),\n        ...Object.values(droppedAssets),\n      ];\n    },\n    (assets) => {\n      unsavedAssets = assets;\n    },\n  );\n\n  $effect(() => {\n    if (!showContentOverlay.current) {\n      open = false;\n    }\n  });\n\n  // Upload pending files (e.g. dropped on the file editor) to the cloud service panel once mounted\n  $effect(() => {\n    if (externalAssetsPanel && isCloudLibrary && pendingFiles.length) {\n      externalAssetsPanel.uploadFiles(pendingFiles);\n      pendingFiles = [];\n    }\n  });\n</script>\n\n{#snippet newFolderButton(/** @type {() => void} */ onclick, disabled = false)}\n  <Button variant=\"ghost\" iconic {disabled} aria-label={_('new_folder')} {onclick}>\n    {#snippet startIcon()}\n      <Icon name=\"create_new_folder\" />\n    {/snippet}\n  </Button>\n{/snippet}\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{#snippet headerItems()}\n  {#if isDefaultLibrary || (isCloudLibrary && libraryName !== 'cloudinary') || (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    {@render newFolderButton(\n      () => {\n        showNewFolderDialog = true;\n      },\n      assetsLocked.current || !!selectedFolder?.readonly || browsingCmsFolder,\n    )}\n  {:else if isCloudLibrary && externalAssetsPanel?.canCreateFolder()}\n    <!-- A folder on a cloud storage service is created by the service, not committed -->\n    {@render newFolderButton(() => {\n      externalAssetsPanel?.showNewFolderDialog();\n    })}\n  {/if}\n  {#if !selectFolder && (isDefaultLibrary || (isCloudLibrary && libraryName !== 'cloudinary'))}\n    <Button\n      variant=\"primary\"\n      label={_('upload')}\n      disabled={browsingCmsFolder}\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      <Selector\n        class=\"tabs\"\n        ariaLabel={_('assets_dialog.locations')}\n        aria-controls=\"{elementIdPrefix}-content-pane\"\n        filterThreshold={-1}\n        onChange={(event) => {\n          libraryName = event.detail.name;\n          subfolderPath = '';\n          selectedSubfolderPaths = [];\n          selectedResources = [];\n        }}\n      >\n        {#if isDefaultLibraryEnabled}\n          <OptionGroup label={_('asset_location.repository')}>\n            {#each Object.entries(assetLibraryFolderMap) as [id, entry] (id)}\n              {#if isFolderOffered(entry, selectFolder)}\n                {@const { folder } = entry}\n                {@const name = `default-${id}`}\n                {@render locationOption({\n                  name,\n                  label: 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 enabledStockAssetProviderEntries.length}\n          <OptionGroup label={_('asset_location.stock_photos')}>\n            {#each enabledStockAssetProviderEntries 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      {#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          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\">\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            oninput={() => {\n              const url = enteredURL.trim();\n\n              selectedResources = url ? [{ url }] : [];\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}\n          <ExternalAssetsPanel\n            {kind}\n            {fieldConfig}\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<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 { duplicates } from '$lib/services/contents/fields/file/duplicates.svelte';\n</script>\n\n<ConfirmationDialog\n  bind:open={duplicates.showDialog}\n  title={_('file_name_conflict_resolution')}\n  onCancel={() => duplicates.resolve(undefined)}\n>\n  {_('file_name_conflict_confirmation_with_name', {\n    values: { count: duplicates.count, name: duplicates.name },\n  })}\n  {#snippet footer()}\n    <Spacer flex />\n    <Button variant=\"primary\" onclick={() => duplicates.resolve(true)}>{_('replace')}</Button>\n    <Button variant=\"primary\" onclick={() => duplicates.resolve(false)}>{_('keep_both')}</Button>\n    <Button variant=\"secondary\" onclick={() => duplicates.resolve(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';\n\n/**\n * @import {\n * AssetFolderInfo,\n * AssetLibraryFolderMap,\n * EntryDraft,\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 */\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 * 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 * @returns {Promise<ProcessResourceResult[]>} Results, in the same order as the resources.\n */\nexport const processResources = ({ draft, resources, folder, libraryConfig }) =>\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 });\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});\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","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 * 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 */\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 */\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 * @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  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 },\n    libraryConfig,\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, 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({ value, entry, collectionName, fileName, componentName, typedKeyPath })\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 or cannot be decoded are reported\n * separately, so the caller can show them the way a File/Image field does.\n * @param {CustomFieldArgs & { inEditorComponent?: boolean, resources: SelectedResource[] }} args\n * Arguments, including the resources picked in the dialog and whether the field is rendered in a\n * rich text editor component.\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  inEditorComponent = false,\n  resources,\n}) => {\n  const { folder, libraryConfig } = getCustomFieldAssetOptions({\n    draft,\n    fieldConfig,\n    typedKeyPath,\n    componentName,\n  });\n\n  const results = await processResources({ draft, resources, folder, libraryConfig });\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              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 { 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   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    fieldConfig,\n    typedKeyPath,\n    componentName = undefined,\n    inEditorComponent = false,\n    /* eslint-enable prefer-const */\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        inEditorComponent,\n        resources,\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    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} />\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","import { forEachTargetLocale } from '$lib/services/contents/draft/update/locale';\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 * @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 * @returns {CustomFieldControl | undefined} Resolved control component or undefined.\n */\nexport const resolveControl = (ctrl) => {\n  if (isReactComponent(ctrl)) {\n    return ctrl;\n  }\n\n  if (typeof ctrl === 'string') {\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);\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 { isObject } from '@sveltia/utils/object';\n  import { createElement } from 'react';\n  import { getContext, onMount } 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 { immutableLoaded, loadImmutable } from '$lib/services/api/immutable';\n  import { getReactDom, loadReactDom, reactDomLoaded } from '$lib/services/api/react-dom';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { updateNonPrimitiveValue } 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 { buildControlProps, resolveControl } from '$lib/services/contents/fields/custom/editor';\n  import { addFileToDraft } from '$lib/services/contents/fields/custom/files';\n\n  /**\n   * @import { Root } from 'react-dom/client';\n   * @import { FieldEditorContext, 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  /** @type {FieldEditorContext} */\n  const {\n    valueStoreKey = 'currentValues',\n    fieldContext = undefined,\n    parentComponentNames = [],\n  } = getContext('field-editor') ?? {};\n  const inEditorComponent = fieldContext === 'rich-text-editor-component';\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    fieldId,\n    keyPath,\n    typedKeyPath,\n    fieldConfig,\n    currentValue,\n    required = true,\n    readonly = false,\n    invalid = false,\n    control,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {HTMLDivElement | undefined} */\n  let container = $state();\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 {Root | undefined}\n   */\n  let reactRoot;\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    if (Array.isArray(value) || isObject(value)) {\n      updateNonPrimitiveValue({ draft, valueStoreKey, locale, keyPath, i18n, value });\n    } else {\n      draft[valueStoreKey][locale][keyPath] = value;\n    }\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      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    componentInstance = instance;\n\n    if (instance) {\n      // Register the instance for validation when it’s available\n      registerCustomFieldInstance({ locale, keyPath, instance });\n    } else {\n      unregisterCustomFieldInstance(registration);\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 (!container || !resolvedControl || !immutableLoaded.current || !reactDomLoaded.current) {\n      return;\n    }\n\n    reactRoot ??= getReactDom().createRoot(container);\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    reactRoot.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    // The control is a React component receiving Immutable Maps. Both libraries are normally loaded\n    // by the time the editor opens, as `CMS.registerFieldType()` starts loading them, but wait for\n    // them in any case; the effect below renders the control once they’re there\n    /* v8 ignore next 4 -- the libraries are bundled with the tests, so loading can’t fail */\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      reactRoot?.unmount();\n      // Unregister the instance on unmount\n      unregisterCustomFieldInstance(registration);\n    };\n  });\n\n  $effect(() => {\n    registration = { locale, keyPath };\n\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 (immutableLoaded.current && reactDomLoaded.current && container && 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/>\n","import { getImmutable } from '$lib/services/api/immutable';\nimport { isReactComponent } from '$lib/services/api/react';\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 { CustomField, CustomFieldPreviewProps, FieldKeyPath } from '$lib/types/public';\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, fieldsMetaData, getAsset } = getPreviewData({ draft, locale });\n  // `getMetaData()` keys the metadata by the full key path, with any trailing list index removed\n  const metadataKey = keyPath.replace(/\\.\\d+$/, '');\n\n  /** @type {CustomFieldPreviewProps} */\n  return {\n    value: currentValue,\n    field: getFieldConfigMap(fieldConfig),\n    metadata: /** @type {MapOf<any>} */ (\n      fieldsMetaData.get(metadataKey) ?? 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()`.\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  import { onMount } from 'svelte';\n\n  import { assetURLUpdates } from '$lib/services/api/asset-proxy';\n  import { fieldStateContext } from '$lib/services/api/field-state';\n  import { immutableLoaded, loadImmutable } from '$lib/services/api/immutable';\n  import { getReactDom, loadReactDom, reactDomLoaded } from '$lib/services/api/react-dom';\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 { Root } from 'react-dom/client';\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.\n   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldPreviewProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    fieldConfig,\n    currentValue,\n    preview,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {HTMLDivElement | undefined} */\n  let container = $state();\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 {Root | undefined}\n   */\n  let reactRoot;\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 (!container || !immutableLoaded.current || !reactDomLoaded.current) {\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      reactRoot ??= getReactDom().createRoot(container);\n\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      reactRoot.render(\n        createElement(\n          fieldStateContext.Provider,\n          { value: { locale, keyPath } },\n          createElement(preview, props),\n        ),\n      );\n    }\n  };\n\n  onMount(() => {\n    // The preview is a React component receiving Immutable Maps. Both libraries are normally loaded\n    // by the time the editor opens, as `CMS.registerFieldType()` starts loading them, but wait for\n    // them in any case; the effect below renders the preview once they’re there\n    /* v8 ignore next 4 -- the libraries are bundled with the tests, so loading can’t fail */\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      reactRoot?.unmount();\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 (immutableLoaded.current && reactDomLoaded.current && container) {\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 */\n    width: 100%;\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    fieldConfig,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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))}\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  @todo Replace the native `<input>` with a custom component.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button } 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    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\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   * 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 });\n\n    // Avoid a cycle dependency & infinite loop\n    if (_inputValue !== undefined && _inputValue !== inputValue) {\n      inputValue = _inputValue;\n    }\n  };\n\n  /**\n   * Update {@link currentValue} based on {@link inputValue}.\n   */\n  const setCurrentValue = () => {\n    // A read-only field keeps its stored value as it is. The input drops the seconds with its\n    // default `step`, so writing it back would truncate a value like one set by `auto_now`\n    if (readonly) {\n      return;\n    }\n\n    const newValue = getCurrentValue({ inputValue, currentValue, fieldConfig, timeZone });\n\n    // Avoid a cycle dependency & infinite loop\n    if (shouldUpdateValue({ newValue, currentValue, fieldConfig })) {\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    <input\n      {...{ type, min, max, step }}\n      bind:value={inputValue}\n      {readonly}\n      aria-readonly={readonly}\n      aria-required={required}\n      aria-invalid={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))}\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  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    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\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 * 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 * Move the focus to a reorder control on the list item at the given index. Call it once an item has\n * been moved with one of its controls, so the control can be used repeatedly without having to find\n * it again.\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 = 'reorder' }) => {\n  /** @type {HTMLElement | null | undefined} */ (\n    listElement?.children[index]?.querySelector(`button[data-action=\"${action}\"]`)\n  )?.focus();\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  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<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, Spacer } from '@sveltia/ui';\n\n  import { env } from '$lib/services/user/env.svelte';\n  import { 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 {() => 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    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</script>\n\n{#if env.hasMouse}\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{:else}\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  <Spacer />\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\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, 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 * @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 } 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 field ID for accessibility.\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 {() => 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    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    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  });\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: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=\"{fieldId}-label\"\n        ariaErrormessage=\"{fieldId}-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    /* The dragged item is left as a faint placeholder marking the gap it would drop into. The\n      pointer already carries the browser’s own drag image of it, so showing it twice at full\n      strength would just be confusing. */\n\n    &.dragging {\n      opacity: 0.25;\n    }\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    width: 28px;\n    height: -moz-available;\n    height: -webkit-fill-available;\n    height: stretch;\n    background-color: var(--sui-secondary-border-color);\n  }\n</style>\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    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\n  } = $props();\n\n  const toast = $state({ show: false, message: '' });\n  const disabled = $derived(readonly || processing);\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      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 { 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 */\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 {() => 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 * @returns {DragSorter} Reactive state and event handlers.\n */\nexport const createDragSorter = ({ getItemCount, getListElement, onMove, settle = tick }) => {\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  const displayOrder = $derived.by(() => {\n    const itemCount = getItemCount();\n\n    return drag?.previewOrder.length === itemCount\n      ? drag.previewOrder\n      : [...Array(itemCount).keys()];\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  return {\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     * @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    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     * 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: item.element.getBoundingClientRect(),\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};\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 { _ } from '@sveltia/i18n';\n  import { ConfirmationDialog, TextArea } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import { flushSync, getContext } 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 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 { checkDuplicates } from '$lib/services/contents/fields/file/duplicates.svelte';\n  import { getTargetFolderPath, listAssets } from '$lib/services/contents/fields/file/helpers';\n  import { getUnsavedAssets } from '$lib/services/contents/fields/file/process';\n  import {\n    getMediaFieldAssetOptions,\n    getRejectedFileNames,\n    processResources,\n    toFieldValue,\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 { createDragSorter } from '$lib/services/utils/drag-sorting.svelte';\n  import { watchAsync } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import {\n   * Asset,\n   * FieldEditorContext,\n   * FieldEditorProps,\n   * SelectedResource,\n   * } from '$lib/types/private';\n   * @import { FileField, 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  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldEditorContext} */\n  const {\n    valueStoreKey = 'currentValues',\n    fieldContext = undefined,\n    parentComponentNames = [],\n  } = getContext('field-editor') ?? {};\n  const inEditorComponent = fieldContext === 'rich-text-editor-component';\n  const componentName = parentComponentNames.at(-1);\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\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 {Asset[]} */\n  let unsavedAssets = $state([]);\n  /** @type {HTMLElement | undefined} */\n  let itemList = $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  const targetFolderPath = $derived(\n    getTargetFolderPath({ entry: entryDraft.current?.originalEntry, folder: targetFolder }),\n  );\n  const listedAssets = $derived(\n    listAssets({\n      kind,\n      folder: targetFolder,\n      folderPath: targetFolderPath,\n      unsavedAssets,\n      slugificationEnabled: libraryConfig.slugify_filename,\n    }),\n  );\n  const multiple = $derived(isMultiple(fieldConfig));\n  /* v8 ignore start -- only read while the list of files is rendered */\n  const itemCount = $derived(Array.isArray(currentValue) ? currentValue.length : 0);\n  /* v8 ignore stop */\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  });\n  const enabledCloudServiceEntries = $derived(assetOptions.cloudServiceEntries);\n  /**\n   * Whether the default (internal) media library is available as a storage provider.\n   */\n  const isDefaultLibraryAvailable = $derived(assetOptions.enabled && !!targetFolder);\n  /**\n   * The total number of available media storage providers (default and/or cloud).\n   */\n  const totalProviders = $derived(\n    (isDefaultLibraryAvailable ? 1 : 0) + enabledCloudServiceEntries.length,\n  );\n  /**\n   * Disable the drop zone if there are no providers or multiple providers are available, to avoid\n   * confusion about where dropped files will be stored. A folder can’t be dropped at all.\n   */\n  const allowDrop = $derived(totalProviders === 1 && !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   * 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    // Save the current value so we can restore it 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      });\n\n      const values = resources.flatMap(({ value }) => value ?? []);\n      const hasValidResource = !!values.length;\n\n      if (multiple) {\n        addMultiValueItems({\n          draft,\n          locale,\n          valueStoreKey,\n          keyPath,\n          newValues: values,\n          replaceIndex: replaceMode ? replaceIndex : undefined,\n        });\n      } else if (hasValidResource) {\n        // A single-value field takes the last file, like it would if they were picked in turn\n        currentValue = toFieldValue(/** @type {string} */ (values.at(-1)), inEditorComponent);\n      }\n\n      const credits = resources.flatMap(({ credit }) => credit || []);\n\n      // Restore the previous value if no valid resources were processed, so that a failed\n      // upload/replace doesn’t leave an empty or invalid reference in the YAML\n      if (!hasValidResource && !multiple && previousValue !== undefined) {\n        currentValue = previousValue;\n      }\n\n      if (credits.length) {\n        photoCredit = credits.join('\\n');\n        showPhotoCreditDialog = true;\n      } else {\n        photoCredit = '';\n      }\n\n      rejectedFilesAlert?.report(getRejectedFileNames(resources));\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 (isDefaultLibraryAvailable) {\n      const replace = await checkDuplicates({ files, 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 = (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  };\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  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\n  // A read started for an earlier state of the draft can be answered after a later one, which\n  // `watchAsync` takes care of\n  watchAsync(\n    () => {\n      const draft = entryDraft.current;\n\n      // The editor is closed along with the draft, so this is only a race with the editor closing\n      /* v8 ignore next 3 */\n      if (!draft) {\n        return undefined;\n      }\n\n      // The draft’s files are read synchronously, so their changes are tracked as well\n      return getUnsavedAssets({ draft, targetFolderPath });\n    },\n    (assets) => {\n      unsavedAssets = assets;\n    },\n  );\n</script>\n\n{#snippet uploadButton()}\n  <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\n          role=\"none\"\n          class=\"item-list\"\n          bind:this={itemList}\n          ondragovercapture={sorter.onDragOver}\n          ondropcapture={sorter.onDrop}\n        >\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                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 uploadButton()}\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 ? resetSelection : undefined}\n      />\n    {/if}\n  {:else}\n    {@render uploadButton()}\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.\n  -->\n  <DropZone\n    bind:this={dropZone}\n    {multiple}\n    disabled={readonly || sorter.dragIndex !== undefined}\n    accept={acceptedTypes}\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  {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} />\n\n<ConfirmationDialog\n  bind:open={showPhotoCreditDialog}\n  title={_('assets_dialog.photo_credit.title')}\n  okLabel={_('copy')}\n  onOk={() => {\n    navigator.clipboard.writeText(photoCredit);\n  }}\n>\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={photoCredit}\n      onclick={(event) => {\n        /** @type {HTMLTextAreaElement} */ (event.target).focus();\n        /** @type {HTMLTextAreaElement} */ (event.target).select();\n      }}\n    />\n  </div>\n</ConfirmationDialog>\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 } 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   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    value,\n    fieldConfig,\n    typedKeyPath = undefined,\n    /* eslint-enable prefer-const */\n  } = $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            })\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 value.trim() && !value.startsWith('blob:')}\n  <p>{value}</p>\n{/if}\n\n<style>\n  /* Remove the padding to make the image full-width on small screens */\n  @media (width < 768px) {\n    :global([role='document'] section) > p:has(:global(img)) {\n      margin-inline: calc(var(--entry-preview-padding-inline) * -1);\n    }\n  }\n</style>\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 {\n    /* eslint-disable prefer-const */\n    typedKeyPath,\n    fieldConfig,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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} />\n    {/each}\n  {/if}\n{:else if typeof currentValue === 'string' && currentValue}\n  <FilePreviewItem value={currentValue} {fieldConfig} {typedKeyPath} />\n{/if}\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, Icon, Menu, MenuButton, MenuItem } from '@sveltia/ui';\n\n  /**\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 {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    /* eslint-disable prefer-const */\n    disabled = false,\n    fieldConfig,\n    items = [],\n    addItem = () => undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const { name: fieldName, label: labelPlural } = $derived(fieldConfig);\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(multiValueField?.label_singular ?? '');\n  const max = $derived(multiValueField?.max ?? Infinity);\n  const label = $derived(\n    _('add_x', { values: { name: labelSingular || labelPlural || fieldName } }),\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</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 { name, label: itemLabel } (name)}\n          <MenuItem label={itemLabel || name} onclick={() => addItem({ type: name })} />\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","import { 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 * 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 equal from 'fast-deep-equal';\n  import { getContext } 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 { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import {\n    getPairs,\n    savePairs,\n    validatePairs,\n  } from '$lib/services/contents/fields/key-value/helpers';\n  import { getDirection } from '$lib/services/contents/i18n';\n  import { 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 { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { FieldEditorContext, 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  /** @type {FieldEditorContext} */\n  const { valueStoreKey = 'currentValues' } = getContext('field-editor') ?? {};\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    fieldId,\n    fieldConfig,\n    readonly = false,\n    /* eslint-enable prefer-const */\n  } = $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  /** @type {('empty' | 'duplicate' | undefined)[]} */\n  let validations = $state([]);\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    // A pair whose key is still empty hasn’t been written to the draft — adding one removes the\n    // `null` placeholder from the draft, which is what runs this — so it doesn’t count as a change\n    const savedPairs = rows.values.filter(([key]) => key.trim());\n\n    if (!equal(savedPairs, 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    // A blank row isn’t stored, so the field holds nothing until a key is filled in\n    if (!updatedPairs.length && draft[valueStoreKey][locale][keyPath] !== null) {\n      const valueStore = draft[valueStoreKey][locale];\n      const _keyPath = keyPath;\n\n      // Enable validation. This runs from an effect, so the write is deferred like the one in\n      // `updateStore()`\n      queueMicrotask(() => {\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 = (index) => {\n    rows.remove(index);\n    edited.splice(index, 1);\n    ensureBlankRow();\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\n  /**\n   * Update the draft store whenever the {@link rows} is updated.\n   */\n  const updateStore = () => {\n    const draft = entryDraft.current;\n\n    validations = validatePairs({ pairs: rows.values, edited });\n\n    const keyedPairs = rows.values.filter(([key]) => key.trim());\n\n    if (!draft || validations.some(Boolean)) {\n      return;\n    }\n\n    if (keyedPairs.length) {\n      // Wait until every row has a key before saving\n      if (keyedPairs.length !== rows.values.length) {\n        return;\n      }\n    } else if (\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\n      // the default value of a required field is left alone, so opening an entry changes nothing\n      !getPairs({ draft, valueStoreKey, keyPath, locale }).some(([key]) => key.trim())\n    ) {\n      return;\n    }\n\n    const args = {\n      draft,\n      valueStoreKey,\n      fieldConfig,\n      keyPath,\n      locale,\n      pairs: $state.snapshot(keyedPairs),\n    };\n\n    // This runs from an effect, so defer the write to the draft like `<FieldEditor>` does: a write\n    // made while an effect is running makes Svelte walk the derived graph below the value map\n    // without memoizing, which takes exponentially longer with each level of nesting\n    queueMicrotask(() => {\n      savePairs(args);\n    });\n  };\n\n  watch(\n    () => [getValueMapSnapshot(entryDraft.current, locale, valueStoreKey)],\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\n      bind:this={tableBody}\n      ondragovercapture={sorter.onDragOver}\n      ondropcapture={sorter.onDrop}\n    >\n      {#each sorter.displayOrder as index (rows.ids[index])}\n        <tr\n          bind:this={rowElements[index]}\n          class:dragging={sorter.dragIndex === index}\n          draggable={sorter.grabbedIndex === index}\n          ondragstart={(event) => sorter.onDragStart(index, event, rows.values[index][0])}\n          ondragend={sorter.onDragEnd}\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                  onGrab={() => sorter.grab(index)}\n                  onRelease={sorter.release}\n                  onMove={(to, action) => sorter.move(index, to, action)}\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      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\n  tr {\n    /* The dragged row is left as a faint placeholder marking the gap it would drop into, like the\n      items of a List field */\n\n    &.dragging {\n      opacity: 0.25;\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 { getValueMapSnapshot } 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 {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    fieldConfig,\n    /* eslint-enable prefer-const */\n  } = $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(getValueMapSnapshot(entryDraft.current, locale), keyPath, { live: false }),\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","<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 {\n    /* eslint-disable prefer-const */\n    expanded = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<Icon name={expanded ? 'expand_more' : isRTL() ? 'chevron_left' : 'chevron_right'} />\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 { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import {\n   * FieldContext,\n   * InternalLocaleCode,\n   * MediaFieldSource,\n   * TypedFieldKeyPath,\n   * } from '$lib/types/private';\n   * @import { Field, FieldKeyPath } 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 {string} [summaryId] `id` of the summary, so the value can be labelled by it.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    subFields,\n    getSubFieldProps,\n    expanded,\n    unknownType,\n    getSummary,\n    getThumbnail,\n    summaryId = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n{#if unknownType}\n  <Alert status=\"warning\">{_('unknown_variable_type')}</Alert>\n{:else if expanded}\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 -->\n  {@const summary = getSummary()}\n  {@const thumbnail = getThumbnail()}\n  {#if 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      <TruncatedText lines={env.isSmallScreen ? 2 : 1}>\n        {summary}\n      </TruncatedText>\n    </div>\n  {/if}\n{/if}\n\n<style>\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 {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    /* eslint-disable prefer-const */\n    label = '',\n    controlId,\n    expanded = $bindable(),\n    expandable = true,\n    toggleExpanded,\n    centerContent = undefined,\n    endContent = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<div role=\"none\" class=\"header\">\n  <div role=\"none\" class=\"start\">\n    {#if expandable}\n      <Button\n        size=\"small\"\n        iconic={!label}\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        {#if label}\n          <span role=\"none\" class=\"type\">\n            {label}\n          </span>\n        {/if}\n      </Button>\n    {:else}\n      <span role=\"none\" class=\"type label\">\n        {label}\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      padding: var(--sui-button-small-padding);\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","import { sleep } from '@sveltia/utils/misc';\nimport { escapeRegExp } from '@sveltia/utils/string';\n\nimport { getField, LIST_KEY_PATH_REGEX } from '$lib/services/contents/entry/fields';\nimport { getOrCreate } from '$lib/services/utils/cache';\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 * Cache of pre-compiled regexes keyed by cleaned key path.\n * @type {Map<string, RegExp>}\n */\nconst expanderRegexCache = new Map();\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    const valueMap = draft.currentValues?.[locale] ?? {};\n    const cleanKey = key.replace(/#$/, '');\n\n    // Pre-compile and cache the regex — same key path is queried on every editor render.\n    const regex = getOrCreate(\n      expanderRegexCache,\n      cleanKey,\n      () => new RegExp(`^${escapeRegExp(cleanKey)}\\\\.[^\\\\.]+$`),\n    );\n\n    return !Object.entries(valueMap).some(([keyPath, value]) => regex.test(keyPath) && !!value);\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 = LIST_KEY_PATH_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 * @param {HTMLElement} pane Edit pane element.\n * @param {FieldKeyPath} keyPath Key path of the field.\n * @returns {HTMLElement | undefined} Field element.\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\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, until it’s rendered or no\n * 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 { 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 { unflattenKeys } from '$lib/services/utils/object';\n\n/**\n * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n * @import { Field, FieldKeyPath } from '$lib/types/public';\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 new\n * 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.\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 {string} args.typeKey Property name holding the variable type name.\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  subFields,\n  hasSingleSubField,\n  field,\n  type,\n  typeKey,\n  locale,\n  defaultLocale,\n}) => {\n  const newItem = (() => {\n    if (typeof dupIndex === 'number') {\n      return structuredClone(valueList[dupIndex]);\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    // A duplicated item is a new one, so it mustn’t keep the original position of its source, or a\n    // revert would treat it as the source item\n    delete newItem.__sc_item_original_key_path;\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 {\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 { isMultiple } from '$lib/services/integrations/media-libraries/multiple';\n\n/**\n * @import {\n * Entry,\n * EntryFileMap,\n * FlattenedEntryContent,\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 * @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}) => {\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  const fieldTypedKeyPath = [typedKeyPath, ...fieldNames].filter(Boolean).join('.');\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  });\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  @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 { Button, Menu, MenuButton, MenuItem, Spacer, VisibilityObserver } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import { getContext, onMount } from 'svelte';\n  import { flip } from 'svelte/animate';\n\n  import ExpandIcon from '$lib/components/common/expand-icon.svelte';\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 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 { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { updateListFieldForLocales } from '$lib/services/contents/draft/update/list';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { isExpanded, syncExpanderStates } from '$lib/services/contents/editor/fields';\n  import { getSubtree } from '$lib/services/contents/entry/subtree';\n  import {\n    formatSummary,\n    getListFieldInfo,\n    getListItemKey,\n    isSingleItemList,\n    tagListItems,\n  } from '$lib/services/contents/fields/list/helpers';\n  import {\n    createListItem,\n    getInitialListExpanderStates,\n  } from '$lib/services/contents/fields/list/items';\n  import {\n    resolveVariableType,\n    warnUnknownType,\n  } from '$lib/services/contents/fields/object/helpers';\n  import { getObjectThumbnail } from '$lib/services/contents/fields/object/thumbnail';\n  import { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\n  import { createDragSorter } from '$lib/services/utils/drag-sorting.svelte';\n\n  /**\n   * @import { FieldEditorContext, FieldEditorProps, MediaFieldSource } 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 {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  /** @type {FieldEditorContext} */\n  const { valueStoreKey = 'currentValues', parentComponentNames = [] } =\n    getContext('field-editor') ?? {};\n  const componentName = parentComponentNames.at(-1);\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldConfig,\n    required = true,\n    readonly = false,\n    summaryId,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const fieldId = $props.id();\n\n  const {\n    name: fieldName,\n    label,\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    collapsed,\n    summary,\n    thumbnail: thumbnailFieldName,\n    minimize_collapsed: minimizeCollapsed = false,\n    label_singular: labelSingular,\n    max = Infinity,\n    add_to_top: addToTop = false,\n  } = $derived(/** @type {ComplexListField} */ (fieldConfig));\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\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  // 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\n  const isLocked = $derived(readonly || (locale !== defaultLocale && i18n === 'duplicate'));\n  const valueMap = $derived(getValueMapSnapshot(entryDraft.current, locale, valueStoreKey));\n  const parentExpandedKeyPath = $derived(`${keyPath}#`);\n  /** @type {Record<string, any>[]} */\n  const items = $derived(getSubtree(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 [key, isExpanded(entryDraft.current, key)];\n    }),\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      allSubFields.some(({ i18n: subI18n }) => isFieldTranslatable(subI18n)),\n  );\n  const isAddDisabled = $derived(isLocked || !hasEditableSubFields);\n\n  /**\n   * @type {HTMLElement | undefined}\n   */\n  let itemList = $state();\n\n  /**\n   * Update the expander states of the list and its items.\n   * @param {Record<string, boolean>} stateMap Map of key path and state.\n   */\n  const updateExpanderStates = (stateMap) => {\n    // The controls are disabled once the draft is gone, so this is only a race with the editor\n    // closing\n    /* v8 ignore next 3 */\n    if (!entryDraft.current) {\n      return;\n    }\n\n    syncExpanderStates({ draft: entryDraft.current, stateMap });\n  };\n\n  /**\n   * Initialize the expander state.\n   */\n  const initializeExpanderState = () => {\n    const draft = entryDraft.current;\n\n    // The editor is mounted with a draft; this is only a race with the editor closing\n    /* v8 ignore next 3 */\n    if (!draft) {\n      return;\n    }\n\n    updateExpanderStates(\n      getInitialListExpanderStates({\n        draft,\n        keyPath,\n        itemCount: items.length,\n        locale,\n        collapsed,\n        minimizeCollapsed,\n      }),\n    );\n  };\n\n  /**\n   * Update the value for the List field with subfield(s).\n   * @param {(arg: { valueList: any[], expanderStateList: boolean[] }) => void} manipulate\n   * See {@link updateListFieldForLocales}.\n   */\n  const updateComplexList = (manipulate) => {\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    updateListFieldForLocales({ draft, locale, i18n, valueStoreKey, keyPath, manipulate });\n  };\n\n  /**\n   * Get the list item element at the specified index.\n   * @param {number} index Target index.\n   * @returns {HTMLElement | undefined} List item element.\n   */\n  const getItem = (index) => /** @type {HTMLElement} */ (itemList?.children[index]);\n\n  /**\n   * Add a new subfield to the list.\n   * @param {object} [args] Arguments.\n   * @param {number} [args.index] List index where a new item will be inserted.\n   * @param {number} [args.dupIndex] List index of an item to be duplicated.\n   * @param {string} [args.type] Variable type name. If the field doesn’t have variable types, it\n   * will be `undefined`.\n   */\n  const addItem = async ({ index = addToTop ? 0 : items.length, dupIndex, type } = {}) => {\n    const draft = entryDraft.current;\n\n    // The controls are disabled once the draft is gone, so this is only a race with the editor\n    // closing\n    /* v8 ignore next 3 */\n    if (!draft) {\n      return;\n    }\n\n    updateComplexList(({ valueList, expanderStateList }) => {\n      const { subFields } = resolveType(type);\n\n      const newItem = createListItem({\n        valueList,\n        keyPath,\n        dupIndex,\n        subFields,\n        hasSingleSubField,\n        field,\n        type,\n        typeKey,\n        locale,\n        defaultLocale: draft.defaultLocale,\n      });\n\n      valueList.splice(index, 0, newItem);\n      expanderStateList.splice(index, 0, true);\n    });\n\n    // Expand the parent if it is collapsed to show the newly added item\n    updateExpanderStates({ [parentExpandedKeyPath]: true });\n\n    await sleep(50);\n    // Move the placeholder into view\n    getItem(index)?.scrollIntoView();\n    // Wait until the placeholder is replaced with the actual content\n    await sleep(100);\n    // Scroll again for the sticky toolbar\n    itemList?.closest('.content')?.scrollBy({ top: -50, behavior: 'instant' });\n    // Move focus to the expander button\n    getItem(index)?.querySelector('button')?.focus();\n  };\n\n  /**\n   * Remove a subfield.\n   * @param {number} index Target index.\n   */\n  const removeItem = async (index) => {\n    updateComplexList(({ valueList, expanderStateList }) => {\n      if (!hasSingleSubField) {\n        // Track original key paths for existing items before they shift due to the removal\n        tagListItems(valueList, keyPath);\n      }\n\n      valueList.splice(index, 1);\n      expanderStateList.splice(index, 1);\n    });\n\n    await sleep(50);\n    (getItem(index) ?? itemList?.closest('[role=\"group\"]')?.querySelector('button'))?.focus();\n  };\n\n  /**\n   * Move a subfield 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    updateComplexList(({ valueList, expanderStateList }) => {\n      if (!hasSingleSubField) {\n        // Ensure the IDs are unique before reordering, so that the `each` block below keeps\n        // following each item rather than its position, and track original key paths for correct\n        // revert after reordering\n        tagListItems(valueList, keyPath, { assignIds: true });\n      }\n\n      valueList.splice(to, 0, ...valueList.splice(from, 1));\n      // The expander states are only manipulated with the default locale, so this list may be empty\n      expanderStateList.splice(to, 0, ...expanderStateList.splice(from, 1));\n    });\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     * Wait for the moved item to be rendered in its new position.\n     * @returns {Promise<void>} Promise.\n     */\n    settle: () => sleep(50),\n  });\n\n  /**\n   * Format the summary template.\n   * @param {number} index List index.\n   * @param {string} [summaryTemplate] Summary template, e.g. `{{fields.slug}}`.\n   * @returns {string} Formatted summary.\n   */\n  const _formatSummary = (index, summaryTemplate) =>\n    formatSummary({\n      collectionName,\n      fileName,\n      keyPath,\n      valueMap,\n      locale,\n      summaryTemplate,\n      hasSingleSubField,\n      index,\n      isIndexFile,\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    getObjectThumbnail({\n      thumbnailFieldName,\n      keyPath: `${keyPath}.${index}`,\n      typedKeyPath: type ? `${typedKeyPath}.*<${type}>` : `${typedKeyPath}.*`,\n      hasSingleSubField,\n      collectionName,\n      fileName,\n      componentName,\n      valueMap,\n      isIndexFile,\n      entry: entryDraft.current?.originalEntry,\n      files: entryDraft.current?.files,\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  onMount(() => {\n    initializeExpanderState();\n    warnUnknownTypes();\n  });\n</script>\n\n{#snippet addPositionItems(/** @type {number} */ insertIndex, /** @type {string} */ position)}\n  {#if hasVariableTypes}\n    <MenuItem label={_(`add_item_${position}`)}>\n      <!-- eslint-disable-next-line no-shadow -->\n      {#snippet items()}\n        {#each variableTypes as { name, label: itemLabel } (name)}\n          <MenuItem\n            label={itemLabel || name}\n            onclick={() => addItem({ index: insertIndex, type: name })}\n          />\n        {/each}\n      {/snippet}\n    </MenuItem>\n  {:else}\n    <MenuItem label={_(`add_item_${position}`)} onclick={() => addItem({ index: insertIndex })} />\n  {/if}\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  <div role=\"none\" class=\"toolbar top\" class:single={singleItem}>\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} {items} {addItem} />\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{/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  ondragovercapture={sorter.onDragOver}\n  ondropcapture={sorter.onDrop}\n>\n  {#each sorter.displayOrder as index (getListItemKey(items, 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      <VisibilityObserver>\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        <div\n          role=\"group\"\n          class=\"item\"\n          class:unknown-type={unknownType}\n          class:dragging={sorter.dragIndex === index}\n          draggable={sorter.grabbedIndex === index}\n          ondragstart={(event) => {\n            // A nested sortable list starts its own drag; the event just bubbles through here\n            if (event.target === event.currentTarget) {\n              sorter.onDragStart(index, event, _formatSummary(index, summaryTemplate));\n            }\n          }}\n          ondragend={(event) => {\n            if (event.target === event.currentTarget) {\n              sorter.onDragEnd();\n            }\n          }}\n        >\n          <ObjectHeader\n            label={hasVariableTypes ? typeConfig?.label || typeConfig?.name : ''}\n            controlId=\"list-{fieldId}-item-{index}-body\"\n            {expanded}\n            toggleExpanded={subFields.length\n              ? () => updateExpanderStates({ [itemKeyPath]: !expanded })\n              : undefined}\n          >\n            {#snippet centerContent()}\n              {#if allowReorder && !singleItem}\n                <ReorderControls\n                  {index}\n                  itemCount={items.length}\n                  disabled={isLocked || items.length < 2}\n                  icon=\"drag_handle\"\n                  onGrab={() => sorter.grab(index)}\n                  onRelease={sorter.release}\n                  onMove={(to, action) => sorter.move(index, to, action)}\n                />\n              {/if}\n            {/snippet}\n            {#snippet endContent()}\n              {#if allowAdd && !hasMaxItems}\n                <MenuButton\n                  variant=\"ghost\"\n                  size=\"small\"\n                  iconic\n                  popupPosition=\"bottom-right\"\n                  aria-label={_('list_item_options')}\n                  disabled={isAddDisabled}\n                >\n                  {#snippet popup()}\n                    <Menu ariaLabel={_('list_item_options')}>\n                      {#if allowDuplicate}\n                        <MenuItem\n                          label={_('duplicate')}\n                          disabled={unknownType}\n                          onclick={() => addItem({ index: index + 1, dupIndex: index })}\n                        />\n                      {/if}\n                      {@render addPositionItems(index, 'above')}\n                      {@render addPositionItems(index + 1, 'below')}\n                    </Menu>\n                  {/snippet}\n                </MenuButton>\n              {/if}\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            <ObjectBody\n              {locale}\n              {subFields}\n              getSubFieldProps={(subField) => ({\n                keyPath: hasSingleSubField ? itemKeyPath : `${itemKeyPath}.${subField.name}`,\n                typedKeyPath: hasVariableTypes\n                  ? `${typedKeyPath}.*<${type}>.${subField.name}`\n                  : `${typedKeyPath}.*.${subField.name}`,\n                context: hasSingleSubField ? 'single-subfield-list-field' : undefined,\n              })}\n              {expanded}\n              {unknownType}\n              getSummary={() => _formatSummary(index, summaryTemplate)}\n              getThumbnail={() => getThumbnail(index, type)}\n            />\n          </div>\n        </div>\n      </VisibilityObserver>\n    </div>\n  {/each}\n</div>\n{#if allowAdd && !addToTop && items.length && parentExpanded && !hasMaxItems}\n  <div role=\"none\" class=\"toolbar bottom add\">\n    <Spacer flex />\n    <AddItemButton disabled={isAddDisabled} {fieldConfig} {items} {addItem} />\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      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\n  .item-list {\n    display: flex;\n    flex-direction: column;\n    gap: 16px;\n\n    &.collapsed {\n      display: none;\n    }\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    &.unknown-type {\n      overflow: hidden;\n\n      :global(.alert) {\n        border-width: 0;\n        border-radius: 0;\n      }\n    }\n\n    /* The dragged item is left as a faint placeholder marking the gap it would drop into. The\n      pointer already carries the browser’s own drag image of it, so showing it twice at full\n      strength would just be confusing. */\n\n    &.dragging {\n      opacity: 0.25;\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 { getContext, 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 { isSingleItemList } from '$lib/services/contents/fields/list/helpers';\n  import { getDirection } from '$lib/services/contents/i18n';\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 { FieldEditorContext, 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  /** @type {FieldEditorContext} */\n  const { valueStoreKey = 'currentValues' } = getContext('field-editor') ?? {};\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    fieldId,\n    fieldConfig,\n    currentValue,\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\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  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  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      updateNonPrimitiveValue({ draft, valueStoreKey, locale, keyPath, i18n, value });\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    getInput(Math.min(index, rows.values.length - 1))?.focus();\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\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\n  role=\"none\"\n  class=\"item-list\"\n  bind:this={itemList}\n  ondragovercapture={sorter.onDragOver}\n  ondropcapture={sorter.onDrop}\n>\n  {#each sorter.displayOrder as index (rows.ids[index])}\n    <div\n      role=\"none\"\n      class=\"item\"\n      class:dragging={sorter.dragIndex === index}\n      draggable={sorter.grabbedIndex === index}\n      ondragstart={(event) => sorter.onDragStart(index, event, rows.values[index])}\n      ondragend={sorter.onDragEnd}\n      animate:flip={{ duration: 200 }}\n    >\n      {#if canEdit && !singleItem}\n        <ReorderControls\n          {index}\n          itemCount={rows.values.length}\n          disabled={!hasMultipleItems}\n          onGrab={() => sorter.grab(index)}\n          onRelease={sorter.release}\n          onMove={(to, action) => sorter.move(index, to, action)}\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 {fieldConfig} items={rows.values} addItem={() => addItem(rows.values.length)} />\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    /* The dragged row is left as a faint placeholder marking the gap it would drop into. The\n      pointer already carries the browser’s own drag image of it, so showing it twice at full\n      strength would just be confusing. */\n\n    &.dragging {\n      opacity: 0.25;\n    }\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 {\n    /* eslint-disable prefer-const */\n    fieldConfig: config,\n    ...rest\n    /* eslint-enable prefer-const */\n  } = $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  /**\n   * @import { Snippet } from 'svelte';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {string} [label] Subsection label.\n   * @property {Snippet} children Slot content.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    label,\n    children,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const sectionId = $props.id();\n  const headerId = `${sectionId}-header`;\n</script>\n\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    {@render children?.()}\n  </div>\n</div>\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    &:empty {\n      display: none;\n    }\n  }\n</style>\n","import { isDuplicatedField } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\nimport { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\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} 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. A rich text editor component’s subfield\n * isn’t part of 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 isDuplicated =\n    inOtherLocale &&\n    (inEditorComponent\n      ? i18n === 'duplicate'\n      : isDuplicatedField({\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 areKeysDuplicated = inOtherLocale && i18n === 'duplicate_keys';\n\n  return {\n    canTranslate,\n    isDuplicated,\n    areKeysDuplicated,\n    isShown:\n      inEditorComponent ||\n      locale === defaultLocale ||\n      canTranslate ||\n      isDuplicated ||\n      areKeysDuplicated,\n  };\n};\n","<script>\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 { getValueMapSnapshot } 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\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldConfig,\n    showLabel = true,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const { name: fieldName, widget: fieldType = 'string' } = $derived(fieldConfig);\n  const { label = '', preview = true } = $derived(/** @type {VisibleField} */ (fieldConfig));\n  const multiple = $derived(isFieldMultiple(fieldConfig));\n  const isList = $derived(fieldType === 'list' || multiple);\n  const valueMap = $derived(getValueMapSnapshot(entryDraft.current, locale));\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{#if 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>{label || fieldName}</h4>\n    {/if}\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  </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    :global([role='document']) {\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  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 Subsection from '$lib/components/contents/details/fields/object/subsection.svelte';\n  import FieldPreview from '$lib/components/contents/details/preview/field-preview.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getSubtree } from '$lib/services/contents/entry/subtree';\n  import { getListFieldInfo, getListItemKey } from '$lib/services/contents/fields/list/helpers';\n\n  /**\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import {\n   * ComplexListField,\n   * ListFieldWithSubField,\n   * ListFieldWithSubFields,\n   * ListFieldWithTypes,\n   * VariableFieldType,\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldConfig,\n    /* eslint-enable prefer-const */\n  } = $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  /** @type {Record<string, any>[]} */\n  const items = $derived(\n    getSubtree(getValueMapSnapshot(entryDraft.current, locale), keyPath) ?? [],\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  <VisibilityObserver>\n    {@const typeConfig = type ? types?.find(({ name }) => name === type) : undefined}\n    {#if hasVariableTypes && !typeConfig}\n      <!-- Unknown type: a warning is displayed in the editor -->\n    {:else}\n      {@const itemKeyPath = `${keyPath}.${index}`}\n      {@const label = typeConfig ? typeConfig.label || typeConfig.name : undefined}\n      {@const subFields = hasVariableTypes\n        ? /** @type {VariableFieldType} */ (typeConfig).fields\n        : singleSubFields}\n      <Subsection {label}>\n        {#each subFields as subField (subField.name)}\n          <VisibilityObserver>\n            <FieldPreview\n              keyPath={hasSingleSubField ? itemKeyPath : `${itemKeyPath}.${subField.name}`}\n              typedKeyPath={hasVariableTypes\n                ? `${typedKeyPath}.*<${type}>.${subField.name}`\n                : `${typedKeyPath}.*.${subField.name}`}\n              {locale}\n              fieldConfig={subField}\n            />\n          </VisibilityObserver>\n        {/each}\n      </Subsection>\n    {/if}\n  </VisibilityObserver>\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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 {\n    /* eslint-disable prefer-const */\n    fieldConfig: config,\n    ...rest\n    /* eslint-enable prefer-const */\n  } = $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","// cSpell:ignore Nominatim jsonv2\n\nimport { sendRequest } from '$lib/services/utils/networking';\n\n/**\n * A location found by the geocoding service.\n * @typedef {object} LocationSearchResult\n * @property {string} place_id Unique identifier of the search result.\n * @property {string} display_name Display name of the search result.\n * @property {string} lat Latitude of the search result.\n * @property {string} lon Longitude of the search result.\n * @see https://nominatim.org/release-docs/develop/api/Search/\n */\n\n/**\n * Endpoint of the Nominatim search API.\n */\nconst SEARCH_API_URL = 'https://nominatim.openstreetmap.org/search';\n\n/**\n * Search for locations matching the given query using the Nominatim API.\n * @param {string} query Free-form query, e.g. an address or a place name.\n * @returns {Promise<LocationSearchResult[]>} Matching locations. Empty if the query is blank or\n * the request has failed.\n * @see https://nominatim.org/release-docs/develop/api/Search/\n */\nexport const searchLocations = async (query) => {\n  const q = query.trim();\n\n  if (!q) {\n    return [];\n  }\n\n  const params = new URLSearchParams({ q, format: 'jsonv2' });\n\n  try {\n    return /** @type {LocationSearchResult[]} */ (await sendRequest(`${SEARCH_API_URL}?${params}`));\n  } catch {\n    return [];\n  }\n};\n","// cSpell:ignore lngs\n\nimport { isObject } from '@sveltia/utils/object';\n\nimport { toFixed } from '$lib/services/utils/number';\n\n/**\n * @import { GeoJSONStoreGeometries } from 'terra-draw';\n * @import { MapField } from '$lib/types/public';\n */\n\n/**\n * Parse a string as a GeoJSON geometry object of the given geometry type.\n * @param {string} value Stringified GeoJSON geometry object.\n * @param {MapField['type']} [geometryType] Expected geometry type. Default: `Point`.\n * @returns {GeoJSONStoreGeometries | undefined} Geometry object, or `undefined` if the value is not\n * valid JSON or not a geometry of the given type.\n */\nexport const parseGeoJSON = (value, geometryType = 'Point') => {\n  try {\n    const geometry = JSON.parse(value);\n\n    return isObject(geometry) &&\n      geometry.type === geometryType &&\n      Array.isArray(geometry.coordinates)\n      ? /** @type {GeoJSONStoreGeometries} */ (geometry)\n      : undefined;\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * Check whether a string is a valid GeoJSON geometry object for the given geometry type.\n * @param {string} value Stringified GeoJSON geometry object.\n * @param {MapField['type']} [geometryType] Expected geometry type. Default: `Point`.\n * @returns {boolean} Whether the value is valid.\n */\nexport const isValidGeoJSON = (value, geometryType) => !!parseGeoJSON(value, geometryType);\n\n/**\n * Round all coordinates in a GeoJSON geometry to the specified number of decimal places. Works for\n * Point (`[lng, lat]`), LineString (`[[lng, lat], ...]`), and Polygon (`[[[lng, lat], ...], ...]`)\n * coordinate structures.\n * @param {GeoJSONStoreGeometries['coordinates']} coordinates GeoJSON coordinates to round.\n * @param {number} decimals Number of decimal places.\n * @returns {GeoJSONStoreGeometries['coordinates']} Rounded coordinates.\n */\nexport const roundCoordinates = (coordinates, decimals) =>\n  /** @type {GeoJSONStoreGeometries['coordinates']} */ (\n    coordinates.map((coords) =>\n      Array.isArray(coords)\n        ? coords.map((c) =>\n            Array.isArray(c) ? c.map((cc) => toFixed(cc, decimals)) : toFixed(c, decimals),\n          )\n        : toFixed(coords, decimals),\n    )\n  );\n\n/**\n * Compute the Leaflet-style bounding box of a non-Point GeoJSON geometry as `[[minLat, minLng],\n * [maxLat, maxLng]]`. Returns `null` if the geometry is a Point or if any coordinate value is not a\n * number.\n * @param {GeoJSONStoreGeometries} geometry GeoJSON geometry object.\n * @returns {[[number, number], [number, number]] | null} Bounding box, or `null`.\n */\nexport const getGeometryBounds = (geometry) => {\n  if (geometry.type === 'Point') {\n    return null;\n  }\n\n  // Polygon coordinates are nested one level deeper (`[[[lng, lat], ...]]`), so flatten first.\n  const pairs = geometry.type === 'Polygon' ? geometry.coordinates.flat(1) : geometry.coordinates;\n\n  if (!pairs.every((c) => typeof c[0] === 'number' && typeof c[1] === 'number')) {\n    return null;\n  }\n\n  const lats = pairs.map((c) => c[1]);\n  const lngs = pairs.map((c) => c[0]);\n\n  return [\n    [Math.min(...lats), Math.min(...lngs)],\n    [Math.max(...lats), Math.max(...lngs)],\n  ];\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 } from 'svelte';\n\n  import LeafletMap from '$lib/components/common/leaflet-map.svelte';\n  import { loadModule } from '$lib/services/app/dependencies';\n  import { searchLocations } from '$lib/services/contents/fields/map/geocoding';\n  import {\n    getGeometryBounds,\n    isValidGeoJSON,\n    parseGeoJSON,\n    roundCoordinates,\n  } from '$lib/services/contents/fields/map/helpers';\n  import { toFixed } from '$lib/services/utils/number';\n  import { watch } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import Leaflet from 'leaflet';\n   * @import { GeoJSONStoreGeometries, TerraDraw } from 'terra-draw';\n   * @import { LocationSearchResult } from '$lib/services/contents/fields/map/geocoding';\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    /* eslint-disable prefer-const */\n    fieldConfig,\n    currentValue = $bindable(),\n    // required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const { decimals = 7, type: geometryType = 'Point', center, zoom } = $derived(fieldConfig);\n  const drawMode = $derived(geometryType.toLowerCase());\n\n  /** @type {HTMLElement | undefined} */\n  let mapElement = $state();\n  /** @type {TerraDraw | undefined} */\n  let draw = $state(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  /** @type {Leaflet.Map | undefined} */\n  let map = undefined;\n  /** Whether the component has been destroyed, possibly before the drawing tools are loaded. */\n  let destroyed = false;\n\n  /**\n   * Load the Terra Draw libraries and initialize the draw instance once the Leaflet map is ready.\n   * We don’t bundle the libraries because of the bundle size: a Map field may not be used often and\n   * multiple services/adapters may be supported in the future.\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: mapInstance }) => {\n    map = mapInstance;\n\n    /** @type {import('terra-draw')} */\n    const { TerraDraw, TerraDrawLineStringMode, TerraDrawPointMode, TerraDrawPolygonMode } =\n      await loadModule('terra-draw', 'dist/terra-draw.module.js');\n\n    /** @type {import('terra-draw-leaflet-adapter')} */\n    const { TerraDrawLeafletAdapter } = await loadModule(\n      'terra-draw-leaflet-adapter',\n      'dist/terra-draw-leaflet-adapter.module.js?module',\n    );\n\n    // The component may have been destroyed, and the map removed, while the libraries were loading\n    if (destroyed) {\n      return;\n    }\n\n    /** @type {Record<string, any>} */\n    const constructors = {\n      Point: TerraDrawPointMode,\n      LineString: TerraDrawLineStringMode,\n      Polygon: TerraDrawPolygonMode,\n    };\n\n    const _draw = new TerraDraw({\n      adapter: new TerraDrawLeafletAdapter({ lib: leaflet, map }),\n      modes: [new constructors[geometryType]()],\n    });\n\n    _draw.start();\n    _draw.setMode(drawMode);\n\n    _draw.on('change', (_ids, changeType) => {\n      // eslint-disable-next-line no-use-before-define\n      onDrawChange(changeType);\n    });\n\n    draw = _draw;\n\n    // The $effect 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. Leaflet uses\n    // `[latitude, longitude]` format for coordinates, while GeoJSON uses `[longitude, latitude]`.\n    // We need to reverse the order of the coordinates when setting the view of the map.\n    if (!currentValue || !isValidGeoJSON(currentValue, geometryType)) {\n      map.setView(center ? [center[1], center[0]] : [0, 0], zoom ?? 2);\n    }\n  };\n\n  /**\n   * Handle the change event of the Terra Draw instance. Update the input value based on the drawn\n   * feature. This function is called when a feature is created, modified, or deleted.\n   * @param {string} changeType Type of change that occurred in the draw instance.\n   */\n  const onDrawChange = (changeType) => {\n    /* v8 ignore next 3 -- the listener is added to the draw instance itself */\n    if (!draw) {\n      return;\n    }\n\n    const snapshot = draw.getSnapshot();\n    const feature = snapshot[snapshot.length - 1];\n\n    if (!feature || changeType !== (geometryType === 'Point' ? 'create' : 'delete')) {\n      return;\n    }\n\n    inputValue = JSON.stringify({\n      type: geometryType,\n      coordinates: roundCoordinates(feature.geometry.coordinates, decimals),\n    });\n\n    // Allow to have only one feature\n    if (snapshot.length > 1) {\n      draw.removeFeatures(\n        snapshot.filter((f) => f.id !== feature.id).map((f) => /** @type {string} */ (f.id)),\n      );\n    }\n  };\n\n  /**\n   * Fit the map view to the given geometry. For a Point, the map is centered on the coordinates at\n   * zoom level 15. For a LineString or Polygon, the map is fitted to the bounding box of all\n   * coordinate pairs.\n   * @param {GeoJSONStoreGeometries} geometry GeoJSON geometry object.\n   */\n  const fitMapToGeometry = (geometry) => {\n    if (geometry.type === 'Point') {\n      const [longitude, latitude] = geometry.coordinates;\n\n      if (typeof longitude === 'number' && typeof latitude === 'number') {\n        map?.setView([latitude, longitude], 15);\n      }\n    } else {\n      const bounds = getGeometryBounds(geometry);\n\n      if (bounds) {\n        map?.fitBounds(bounds);\n      }\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\n    const geometry = parseGeoJSON(currentValue ?? '', geometryType);\n    const newValue = geometry ? /** @type {string} */ (currentValue) : '';\n\n    if (inputValue === newValue) {\n      return;\n    }\n\n    inputValue = newValue;\n\n    draw.clear();\n\n    if (geometry) {\n      draw.addFeatures([{ type: 'Feature', geometry, properties: { mode: drawMode } }]);\n      fitMapToGeometry(geometry);\n    }\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   * Search for locations matching the query.\n   */\n  const searchLocation = async () => {\n    if (!searchQuery.trim()) {\n      return;\n    }\n\n    searching = true;\n    searchResults = await searchLocations(searchQuery);\n    searching = false;\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 = ({ latitude, longitude }) => {\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    latitude = toFixed(latitude, decimals);\n    longitude = toFixed(longitude, decimals);\n\n    map?.setView([latitude, longitude], 15);\n\n    if (geometryType !== 'Point') {\n      return;\n    }\n\n    /** @type {GeoJSONStoreGeometries} */\n    const feature = { type: 'Point', coordinates: [longitude, latitude] };\n\n    draw.clear();\n    draw.addFeatures([{ type: 'Feature', geometry: feature, properties: { mode: 'point' } }]);\n    inputValue = JSON.stringify(feature);\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 = () => {\n    if (!navigator.geolocation) {\n      showAlertDialog = true;\n      errorMessage = _('geolocation_unsupported');\n\n      return;\n    }\n\n    navigator.geolocation.getCurrentPosition(\n      ({ coords: { latitude, longitude } }) => {\n        setLocation({ latitude, longitude });\n      },\n      (error) => {\n        showAlertDialog = true;\n        errorMessage = _('geolocation_error_body');\n        // eslint-disable-next-line no-console\n        console.error('Error getting current location:', error);\n      },\n    );\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.\n   */\n  const clearValue = () => {\n    currentValue = '';\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  watch(\n    () => searchQuery,\n    () => {\n      searchLocation();\n    },\n  );\n</script>\n\n<div role=\"none\" class=\"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  <!-- @todo Replace `title` with a native tooltip -->\n  <Button\n    variant=\"tertiary\"\n    iconic\n    title={_('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 {\n    /* eslint-disable prefer-const */\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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 * @import { NumberField } from '$lib/types/public';\n */\n\n/**\n * Whether the field stores its value as a floating-point number rather than an integer.\n * @param {NumberField} fieldConfig Field configuration.\n * @returns {boolean} `true` if the `value_type` is `float` or `float/string`.\n */\nconst isFloatType = ({ value_type: valueType = 'int' }) =>\n  ['float', 'float/string'].includes(valueType);\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`.\n * @param {NumberField} fieldConfig Field configuration.\n * @returns {boolean} `true` if the stored value is a string.\n */\nconst isStringOutput = ({ value_type: valueType = 'int' }) => !['int', 'float'].includes(valueType);\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 * @returns {number | undefined} Number to be shown. `undefined` if there is no stored value, or it\n * is blank or can’t be parsed, which empties the input.\n */\nexport const getNumberInputValue = ({ currentValue, fieldConfig }) => {\n  if (typeof currentValue === 'number') {\n    return currentValue;\n  }\n\n  if (typeof currentValue !== 'string') {\n    return undefined;\n  }\n\n  const value = isFloatType(fieldConfig)\n    ? Number.parseFloat(currentValue)\n    : Number.parseInt(currentValue, 10);\n\n  return Number.isNaN(value) ? undefined : value;\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 | undefined} args.inputValue Value of the number input. `undefined` if the input\n * is empty.\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.\n */\nexport const getNumberFieldValue = ({ inputValue, fieldConfig }) => {\n  let value = NaN;\n\n  if (inputValue !== undefined) {\n    value = isFloatType(fieldConfig)\n      ? Number.parseFloat(String(inputValue))\n      : Number.parseInt(String(inputValue), 10);\n  }\n\n  if (isStringOutput(fieldConfig)) {\n    return Number.isNaN(value) ? '' : String(value);\n  }\n\n  return Number.isNaN(value) ? null : value;\n};\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  } 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    /* eslint-disable prefer-const */\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /** @type {number | undefined} */\n  let inputValue = $state();\n\n  const { min, max, step = 1 } = $derived(fieldConfig);\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    () => inputValue,\n    (input) => {\n      inputValue = input;\n    },\n    (value) => getNumberInputValue({ currentValue: value, fieldConfig }),\n    (input) => getNumberFieldValue({ inputValue: input, fieldConfig }),\n  );\n</script>\n\n<NumberInput\n  bind:value={inputValue}\n  {min}\n  {max}\n  {step}\n  {readonly}\n  {required}\n  {invalid}\n  aria-labelledby=\"{fieldId}-label\"\n  aria-errormessage=\"{fieldId}-error\"\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 { 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 {\n    /* eslint-disable prefer-const */\n    locale,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const canonicalLocale = $derived(getCanonicalLocale(locale));\n  const numberFormatter = $derived(Intl.NumberFormat(canonicalLocale));\n</script>\n\n{#if currentValue !== undefined && currentValue !== null && currentValue !== ''}\n  <p lang={canonicalLocale} dir={getDirection(locale)}>\n    {numberFormatter.format(Number(currentValue))}\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 { DraftValueStoreKey, EntryDraft, InternalLocaleCode } 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\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(\n        getDefaultValues({ fields: subFields, locale, defaultLocale: draft.defaultLocale }),\n      ).map(([_keyPath, value]) => [`${keyPath}.${_keyPath}`, value]),\n    );\n\n    const newValueMap =\n      locale === draft.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 */\nexport const removeObjectFields = ({\n  draft,\n  valueStoreKey = 'currentValues',\n  locale,\n  keyPath,\n  fieldConfig,\n}) => {\n  const { i18n = false } = fieldConfig;\n\n  forEachTargetLocale(\n    { valueStore: draft[valueStoreKey], locale, i18n, draft, keyPath },\n    (valueMap) => {\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        valueMap[_keyPath] = null;\n        delete valueMap[_keyPath];\n      });\n\n      // Enable validation\n      valueMap[keyPath] = null;\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 { getContext, onMount } 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 { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { addObjectFields, removeObjectFields } from '$lib/services/contents/draft/update/object';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\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    resolveVariableType,\n    warnUnknownType,\n  } from '$lib/services/contents/fields/object/helpers';\n  import { getObjectThumbnail } from '$lib/services/contents/fields/object/thumbnail';\n\n  /**\n   * @import {\n   * EntryDraft,\n   * FieldEditorContext,\n   * FieldEditorProps,\n   * MediaFieldSource,\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  /** @type {FieldEditorContext} */\n  const {\n    fieldContext,\n    valueStoreKey = 'currentValues',\n    parentComponentNames = [],\n  } = getContext('field-editor') ?? {};\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    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\n  } = $props();\n\n  const fieldId = $props.id();\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(getValueMapSnapshot(entryDraft.current, locale, valueStoreKey));\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  /* 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\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  };\n\n  /**\n   * Remove the object’s subfields from the entry draft.\n   */\n  const removeFields = () => {\n    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   * 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    getObjectThumbnail({\n      thumbnailFieldName,\n      keyPath,\n      typedKeyPath: type ? `${typedKeyPath}<${type}>` : typedKeyPath,\n      collectionName,\n      fileName,\n      componentName,\n      valueMap,\n      isIndexFile,\n      entry: entryDraft.current?.originalEntry,\n      files: entryDraft.current?.files,\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 disabled={readonly} {fieldConfig} addItem={addFields} />\n{/if}\n\n{#if !(!required || hasVariableTypes) || hasValues}\n  <div\n    role=\"group\"\n    class=\"wrapper\"\n    class:unknown-type={unknownType}\n    class:expanded={parentExpanded}\n    aria-labelledby={parentExpanded ? undefined : `object-${fieldId}-summary`}\n  >\n    {#if !hideHeader}\n      <ObjectHeader\n        label={hasVariableTypes ? typeConfig?.label || type : ''}\n        controlId=\"object-{fieldId}-item-list\"\n        expanded={parentExpanded}\n        toggleExpanded={subFields.length\n          ? () =>\n              syncExpanderStates({\n                draft: /** @type {EntryDraft} */ (entryDraft.current),\n                stateMap: { [parentExpandedKeyPath]: !parentExpanded },\n              })\n          : undefined}\n      >\n        {#snippet endContent()}\n          {#if hasVariableTypes}\n            <RemoveButton\n              disabled={readonly}\n              onclick={() => {\n                removeFields();\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:\n            hasVariableTypes && type\n              ? `${typedKeyPath}<${type}>.${subField.name}`\n              : `${typedKeyPath}.${subField.name}`,\n        })}\n        expanded={parentExpanded}\n        {unknownType}\n        getSummary={_formatSummary}\n        {getThumbnail}\n        summaryId=\"object-{fieldId}-summary\"\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    &.unknown-type {\n      overflow: hidden;\n\n      :global(.alert) {\n        border-width: 0;\n        border-radius: 0;\n      }\n    }\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 { VisibilityObserver } from '@sveltia/ui';\n\n  import Subsection from '$lib/components/contents/details/fields/object/subsection.svelte';\n  import FieldPreview from '$lib/components/contents/details/preview/field-preview.svelte';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getKeysByPrefix } from '$lib/services/contents/entry/key-paths';\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldConfig,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const { fields } = $derived(/** @type {ObjectFieldWithSubFields} */ (fieldConfig));\n  const { types, typeKey = 'type' } = $derived(/** @type {ObjectFieldWithTypes} */ (fieldConfig));\n  const valueMap = $derived(getValueMapSnapshot(entryDraft.current, locale));\n  // Ask the shared key path index rather than scanning the whole value map; see the same check in\n  // the Object field editor\n  const hasValues = $derived(\n    getKeysByPrefix(valueMap, `${keyPath}.`).some((_keyPath) => !!valueMap[_keyPath]),\n  );\n  const hasVariableTypes = $derived(Array.isArray(types));\n  const typeKeyPath = $derived(`${keyPath}.${typeKey}`);\n  const type = $derived(hasVariableTypes ? valueMap[typeKeyPath] : undefined);\n  const typeConfig = $derived(type ? types?.find(({ name }) => name === type) : undefined);\n  const label = $derived(typeConfig ? typeConfig.label || typeConfig.name : undefined);\n  /* v8 ignore start -- only read for a known type, which has its subfields */\n  const subFields = $derived((hasVariableTypes ? typeConfig?.fields : fields) ?? []);\n  /* v8 ignore stop */\n</script>\n\n{#if hasValues}\n  {#if hasVariableTypes && !typeConfig}\n    <!-- Unknown type: a warning is displayed in the editor -->\n  {:else}\n    <Subsection {label}>\n      {#each subFields as subField (subField.name)}\n        {@const subFieldKeyPath = `${keyPath}.${subField.name}`}\n        <VisibilityObserver>\n          <FieldPreview\n            keyPath={subFieldKeyPath}\n            typedKeyPath={hasVariableTypes && typeConfig?.name\n              ? `${typedKeyPath}<${typeConfig.name}>.${subField.name}`\n              : `${typedKeyPath}.${subField.name}`}\n            {locale}\n            fieldConfig={subField}\n          />\n        </VisibilityObserver>\n      {/each}\n    </Subsection>\n  {/if}\n{/if}\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 { 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 { getLocalizedRelationValue } from '$lib/services/contents/fields/relation/helpers/locale';\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 */\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/**\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 (keyPath in content && !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() : value;\n\n      if (normalized !== 'true' && normalized !== 'false') {\n        return false;\n      }\n\n      content[keyPath] = normalized === 'true';\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 * 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. A `multiple` Relation field stores each value\n    // under a numbered key path, so every copied key is localized the same way\n    content[key] = getLocalizedRelationValue({\n      fieldConfig: field,\n      value: defaultLocaleContent[key],\n      sourceLocale: defaultLocale,\n      targetLocale: locale,\n    });\n  });\n\n  return !!keys.length;\n};\n\n/**\n * Get the variable type configuration that matches the type name stored in the content.\n * @param {object} args Arguments.\n * @param {Field} args.field Field configuration with the `types` option.\n * @param {FlattenedEntryContent} args.content Flattened entry content.\n * @param {FieldKeyPath} args.keyPath Key path of the object or list item.\n * @returns {Field[] | undefined} Sub-fields of the matching type, if any.\n */\nconst getVariableTypeFields = ({ field, content, keyPath }) => {\n  const { types, typeKey = 'type' } = /** @type {FieldWithTypes} */ (field);\n\n  return types?.find(({ name }) => name === content[`${keyPath}.${typeKey}`])?.fields;\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 } = args;\n  const i18n = field.i18n ?? inheritedI18n;\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 (\n    locale !== defaultLocale &&\n    field.widget === 'keyvalue' &&\n    field.i18n === 'duplicate_keys' &&\n    defaultLocaleContent\n  ) {\n    syncDuplicateKeys({\n      valueStore: { [defaultLocale]: defaultLocaleContent, [locale]: content },\n      defaultLocale,\n      keyPath,\n    });\n\n    return;\n  }\n\n  const occupied = keyPath in content || 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` field mirrors the default locale, so take the value from there rather than\n    // filling in the configured default, which may not be what the default locale actually holds\n    if (\n      locale !== defaultLocale &&\n      field.i18n === 'duplicate' &&\n      defaultLocaleContent &&\n      copyFromDefaultLocale({\n        content,\n        defaultLocaleContent,\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  // 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 (locale !== defaultLocale && i18n === 'duplicate' && defaultLocaleContent) {\n      alignPairOrder({ content, referenceContent: defaultLocaleContent, 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 { fields: subFields } = /** @type {FieldWithSubFields} */ (field);\n    const fields = subFields ?? getVariableTypeFields({ field, content, keyPath });\n\n    fields?.forEach((subField) => {\n      normalizeField({\n        ...args,\n        field: subField,\n        keyPath: `${keyPath}.${subField.name}`,\n        inheritedI18n: i18n,\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 scalars only, so there is nothing to recurse into\n  if (!subField && !subFields && !types) {\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 fields = subFields ?? getVariableTypeFields({ field, content, keyPath: itemKeyPath });\n\n    fields?.forEach((itemField) => {\n      normalizeField({\n        ...args,\n        field: itemField,\n        keyPath: `${itemKeyPath}.${itemField.name}`,\n        inheritedI18n: i18n,\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 { 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 { isDuplicatedField } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getInitialValue } from '$lib/services/contents/fields/uuid/helpers';\nimport { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\n\n/**\n * @import {\n * FlattenedEntryContent,\n * GetFieldArgs,\n * InternalLocaleCode,\n * LocaleContentMap,\n * } from '$lib/types/private';\n * @import { UuidField } from '$lib/types/public';\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","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 } from '$lib/services/contents/collection/slug';\nimport { revokeDraftFileURLs, STATIC_DRAFT_KEYS } from '$lib/services/contents/draft';\nimport { 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/uuid';\nimport { getDefaultValues } from '$lib/services/contents/draft/defaults';\nimport { hasLocalizedSlugs } from '$lib/services/contents/draft/slugs';\nimport { resetCustomFieldValidation } from '$lib/services/contents/draft/validate/custom-fields';\nimport { createState } 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 * InternalCollection,\n * InternalCollectionFile,\n * InternalEntryCollection,\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 * 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 {\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    // 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({\n      contentMap: originalValues,\n      defaultLocale,\n      getFieldArgs: { collectionName, fileName, isIndexFile },\n    });\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      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      extraValues: extraValues ?? Object.fromEntries(allLocales.map((locale) => [locale, {}])),\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  }\n\n  return draft;\n};\n","import { _ } from '@sveltia/i18n';\n\nimport { slugify } from '$lib/services/common/slug';\nimport { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { getSharedEntryFileName } from '$lib/services/contents/collection/nested';\nimport { getSlugOptions } from '$lib/services/contents/collection/slug';\nimport { getEntryPaths } from '$lib/services/contents/entry/paths';\nimport { getRegex } from '$lib/services/utils/regex';\nimport { getUnpublishedEntriesByCollection } 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, doesn’t match the\n * collection’s `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. With Editorial Workflow, a\n * draft that has already renamed the entry leaves the published version behind under the old slug,\n * so that version has to be recognized as the same entry — otherwise reverting the slug looks like\n * a conflict. The unpublished entries are concatenated rather than swapped over their published\n * versions, because a draft that renamed an entry leaves the published file behind, so both slugs\n * are still in use.\n * @param {EntryDraft} draft Entry draft.\n * @returns {(Entry | UnpublishedEntry)[]} Entries.\n */\nexport const getOtherEntries = (draft) => {\n  // An entry in the Editorial Workflow has previous paths\n  const { 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    ...getEntriesByCollection(collectionName),\n    ...getUnpublishedEntriesByCollection(collectionName),\n  ].filter((entry) => !Object.values(entry.locales).some(({ path }) => ownPaths.has(path)));\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 slugs never count as taken.\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  const ownSlugs = new Set(Object.values(originalSlugs));\n\n  return Object.fromEntries(\n    locales.map((locale) => [\n      locale,\n      otherEntries\n        .flatMap((entry) =>\n          locale === '_'\n            ? Object.values(entry.locales).map(({ slug }) => slug)\n            : [entry.locales[locale]?.slug],\n        )\n        .filter((slug) => typeof slug === 'string' && !ownSlugs.has(slug)),\n    ]),\n  );\n};\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 {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 = ({ slug, required = true, pattern, takenSlugs = [], locale }) => {\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\n  if (/[/\\s]/.test(/** @type {string} */ (slug))) {\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  // 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          // 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","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  isNestedCollection,\n} from '$lib/services/contents/collection/nested';\nimport { getFolderName, getOwnFolderName } from '$lib/services/contents/collection/nested/i18n';\nimport { getSlugOptions } from '$lib/services/contents/collection/slug';\nimport { getSlugs, hasLocalizedSlugs } from '$lib/services/contents/draft/slugs';\nimport { getOtherEntries } from '$lib/services/contents/draft/validate/slugs';\nimport { createPath } from '$lib/services/utils/file';\nimport { getUnpublishedEntryByDraft, isPendingDeletion } from '$lib/services/workflow';\n\n/**\n * @import { EntryDraft, InternalEntryCollection, InternalLocaleCode } 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 * nested collection that doesn’t store every entry as an index file is identified by its path\n * within the collection folder, which can’t be renamed without relocating the entry. An entry\n * 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 (isNestedCollection(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. Date and time tags in the slug template are filled with the current date and\n * time, as they will be 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, string>} 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 getSlugPreviews = (draft, { templateOnly = false } = {}) => {\n  const { defaultLocaleSlug, localizedSlugs } = getSlugs({ draft, templateOnly });\n\n  if (!localizedSlugs) {\n    return { _: defaultLocaleSlug };\n  }\n\n  // Every enabled locale has a slug\n  return /** @type {Record<InternalLocaleCode, string>} */ (\n    Object.fromEntries(\n      Object.entries(localizedSlugs).filter(([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) => getFolderName(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 { getSlugPreviews } 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 {\n    /* eslint-disable prefer-const */\n    locale,\n    ariaLabelledby = undefined,\n    /* eslint-enable prefer-const */\n  } = $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 templateSlug = $derived.by(() => {\n    if (slugOptions.editorRequired) {\n      return '';\n    }\n\n    const previews = getSlugPreviews(/** @type {EntryDraft} */ (entryDraft.current), {\n      templateOnly: true,\n    });\n\n    return previews[locale] ?? previews._;\n  });\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   * 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  </FieldEditorGroup>\n{/if}\n","import { stripSlashes } from '@sveltia/utils/string';\n\nimport { getEntriesByCollection } 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 { getUnpublishedEntriesByCollection } 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 destination can only\n * be worked out ahead of the save when every entry in the collection shares one file name, which is\n * the case that matters: the path editor is then the only thing deciding it, so an overlooked\n * collision would quietly overwrite a page. With localized slugs, each locale has a destination of\n * its own, so every enabled locale is checked against the other entries’ files in that locale.\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 (!indexFileName || !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. 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    ...getEntriesByCollection(collection.name),\n    ...getUnpublishedEntriesByCollection(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   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    id,\n    thisPane,\n    thatPane = createRawState(null),\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const { allLocales } = $derived(getDraftI18nConfig(entryDraft.current));\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  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={_('switch_locale')}\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 = getLocaleLabel(locale) ?? locale}\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 thatPane.current?.mode === 'edit' && canPreview && entryEditorSettings.current?.showPreview}\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\n            const { locale } = /** @type {EntryEditorPane} */ (thatPane.current);\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 { generateUUID } from '@sveltia/utils/crypto';\nimport { escapeRegExp } from '@sveltia/utils/string';\n\nimport { FIELD_TAG_PREFIX_REGEX } from '$lib/services/common/template/constants';\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 { getFieldDisplayValue } from '$lib/services/contents/entry/values';\nimport { getListFormatter } from '$lib/services/contents/i18n';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { isNumeric } from '$lib/services/utils/number';\n\n/**\n * @import { FlattenedEntryContent, InternalLocaleCode } from '$lib/types/private';\n * @import { ComputeField, FieldKeyPath } from '$lib/types/public';\n */\n\n/**\n * Length argument of {@link generateUUID} for each UUID tag, keyed by tag name.\n * @type {Record<string, 'short' | 'shorter' | undefined>}\n */\nconst UUID_TAG_LENGTHS = {\n  uuid: undefined,\n  uuid_short: 'short',\n  uuid_shorter: 'shorter',\n};\n\n/**\n * Regular expression source matching the value each UUID tag generates, keyed by tag name.\n * @type {Record<string, string>}\n */\nconst UUID_TAG_PATTERNS = {\n  uuid: '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}',\n  uuid_short: '[0-9a-f]{12}',\n  uuid_shorter: '[0-9a-f]{8}',\n};\n\n/**\n * Placeholder standing in for a template tag while the template’s literal text is escaped for a\n * regular expression. It can’t appear in a template.\n */\nconst TAG_PLACEHOLDER = '\\0';\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 list index found in the given key path, which is the second-to-last segment, e.g. `2` for\n * `authors.2.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('.').splice(-2, 1);\n\n  return index && isNumeric(index) ? Number(index) : undefined;\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_TAG_PATTERNS, 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  /** @type {string[]} */\n  const tagNames = [];\n\n  const literals = replaceTemplateTags(valueTemplate, (_match, placeholder) => {\n    tagNames.push(parseTransformations(placeholder).value);\n\n    return TAG_PLACEHOLDER;\n  })\n    .split(TAG_PLACEHOLDER)\n    .map(escapeRegExp);\n\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_TAG_PATTERNS[tagName]})`)\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_TAG_LENGTHS[tagName]));\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 * 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 * @returns {string | number} Computed value.\n */\nexport const getComputedValue = ({\n  fieldConfig,\n  keyPath,\n  locale,\n  valueMap,\n  collectionName,\n  fileName,\n  isIndexFile = false,\n}) => {\n  const { value: valueTemplate = '' } = 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\n  if (valueTemplate === '{{index}}') {\n    return getListIndex(keyPath) ?? '';\n  }\n\n  const listFormatter = getListFormatter(locale);\n  const uuids = getUuids({ valueTemplate, keyPath, valueMap });\n  let uuidIndex = 0;\n\n  return replaceTemplateTags(valueTemplate, (_match, placeholder) => {\n    const { value: tagName, transformations } = parseTransformations(placeholder);\n\n    if (tagName === 'index') {\n      return String(getListIndex(keyPath) ?? '');\n    }\n\n    /** @type {string} */\n    let value;\n\n    if (isUuidTag(tagName)) {\n      value = uuids[uuidIndex];\n      uuidIndex += 1;\n    } else if (FIELD_TAG_PREFIX_REGEX.test(tagName)) {\n      const fieldValue = getFieldDisplayValue({\n        collectionName,\n        fileName,\n        valueMap,\n        keyPath: stripFieldTagPrefix(tagName),\n        locale,\n        isIndexFile,\n      });\n\n      value = Array.isArray(fieldValue) ? listFormatter.format(fieldValue) : String(fieldValue);\n    } else {\n      return '';\n    }\n\n    if (transformations.length) {\n      return applyTransformations({ value, transformations, locale });\n    }\n\n    return value;\n  });\n};\n","import { 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 { COMPONENT_NAME_PREFIX_REGEX } from '$lib/services/contents/fields/rich-text';\nimport { getComponentDef } from '$lib/services/contents/fields/rich-text/components/definitions';\nimport { isFieldLocalized } from '$lib/services/contents/i18n/fields';\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 * FieldWithSubFields,\n * FieldWithTypes,\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 * Get the sub-fields of an Object field or list item, resolving the variable type against the type\n * name stored in the content when the field has the `types` option.\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[]} Sub-fields, or an empty array if the field holds none.\n */\nconst getSubFields = (field, valueMap, keyPath) => {\n  const { fields } = /** @type {FieldWithSubFields} */ (field);\n\n  if (fields) {\n    return fields;\n  }\n\n  const { types, typeKey = 'type' } = /** @type {FieldWithTypes} */ (field);\n\n  return types?.find(({ name }) => name === valueMap[`${keyPath}.${typeKey}`])?.fields ?? [];\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  const cached = computeFieldCacheMap.get(field);\n\n  if (cached !== undefined) {\n    return cached;\n  }\n\n  const { widget: fieldType = 'string' } = field;\n  let result = false;\n\n  if (fieldType === 'compute') {\n    result = true;\n  } else if (fieldType === 'object' || fieldType === 'list') {\n    const { field: subField } = /** @type {ListFieldWithSubField} */ (field);\n    const { fields = [] } = /** @type {FieldWithSubFields} */ (field);\n    const { types = [] } = /** @type {FieldWithTypes} */ (field);\n\n    result = [subField, ...fields, ...types.flatMap(({ fields: typeFields = [] }) => typeFields)]\n      .filter(Boolean)\n      .some(containsComputeField);\n  }\n\n  computeFieldCacheMap.set(field, result);\n\n  return result;\n};\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    getSubFields(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    getSubFields(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.\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 || (i18nEnabled && isFieldLocalized(fieldConfig.i18n));\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.\n * @returns {boolean} Whether any value has changed.\n */\nconst updateLocaleComputedValues = ({ draft, valueStoreKey, locale, valueMap }) => {\n  const { collectionName, fileName, collection, collectionFile, fields, isIndexFile } = draft;\n  const { i18nEnabled, defaultLocale } = (collectionFile ?? collection)._i18n;\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  let changed = false;\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,\n      collectionName,\n      fileName,\n      isIndexFile,\n    });\n\n    if (valueMap[keyPath] !== value) {\n      valueMap[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, valueMap]) => {\n        if (!currentLocales[locale] || !Object.keys(valueMap).length) {\n          return;\n        }\n\n        if (updateLocaleComputedValues({ draft, valueStoreKey, locale, valueMap })) {\n          changed = true;\n        }\n      });\n    },\n  );\n\n  return changed;\n};\n","import { untrack } from 'svelte';\n\nimport { getValueMapVersion } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { updateComputedValues } from '$lib/services/contents/draft/update/compute';\n\n/**\n * @import { EntryDraft } from '$lib/types/private';\n */\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 * @param {EntryDraft} draft Entry draft.\n */\nexport const trackComputedValues = (draft) => {\n  // Depend on every field value at the cost of one dependency per locale, without walking the\n  // values: each value map proxy counts its writes\n  Object.values(draft.currentValues).forEach(getValueMapVersion);\n  // The extra values of rich text editor components are plain `$state` objects with no version,\n  // so they have to be read to be tracked. They are few, so the walk is cheap\n  Object.values(draft.extraValues).forEach((valueMap) => void $state.snapshot(valueMap));\n  void $state.snapshot(draft.currentLocales);\n\n  untrack(() => {\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 { mergeUnpublishedEntries, unpublishedEntries } 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}. The count matches the one shown next to the\n * collection in the sidebar, so Hugo’s special index file is left out as well — see\n * {@link countCollectionEntries}.\n * @param {string} collectionName Collection name.\n * @returns {number} Count.\n */\nexport const countQuotaEntries = (collectionName) =>\n  countCollectionEntries(\n    collectionName,\n    mergeUnpublishedEntries(\n      getEntriesByCollection(collectionName),\n      unpublishedEntries.current.filter(\n        ({ workflow }) => workflow.collectionName === collectionName,\n      ),\n    ),\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 */\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 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 || (field.widget === 'relation' && field.collection === collectionName);\n    }),\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 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 draft.pendingEntries\n    .filter((pendingEntry) => referenced.has(pendingEntry))\n    .map((pendingEntry) => getSnapshot(pendingEntry));\n};\n","import { getEntriesByCollection } from '$lib/services/contents/collection/entries';\nimport { getOrderFieldKey } from '$lib/services/contents/collection/entries/reorder/config';\n\n/**\n * @import { EntryDraft } from '$lib/types/private';\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. Doing this\n * at save time (rather than draft creation) makes the assignment race-safe even when a draft has\n * been backed up and restored after another entry took the previously computed value. Callers must\n * gate on `draft.isNew` and `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, collectionFile, currentValues } = draft;\n  const orderKey = getOrderFieldKey(collection);\n\n  if (!orderKey) {\n    return;\n  }\n\n  const { defaultLocale } = (collectionFile ?? collection)._i18n;\n\n  const maxOrder = getEntriesByCollection(collection.name).reduce((max, entry) => {\n    const value = Number(entry.locales[defaultLocale]?.content?.[orderKey]);\n\n    return Number.isFinite(value) && value > max ? value : max;\n  }, 0);\n\n  const nextOrder = maxOrder + offset + 1;\n\n  Object.values(currentValues).forEach((valueMap) => {\n    valueMap[orderKey] = nextOrder;\n  });\n};\n","import { unique } from '@sveltia/utils/array';\n\nimport { isReadonly } from '$lib/services/config/readonly';\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 { getReferencedPendingEntries } from '$lib/services/contents/draft/pending-entries';\nimport { createSavingEntryData } from '$lib/services/contents/draft/save/changes';\nimport { assignManualSortOrder } from '$lib/services/contents/draft/save/sort-order';\nimport { getCanonicalSlug, getFillSlugOptions, getSlugs } from '$lib/services/contents/draft/slugs';\nimport { updateListFieldForLocales } from '$lib/services/contents/draft/update/list';\nimport { getEntryOptions, getRefEntries } from '$lib/services/contents/fields/relation/helpers';\nimport { renameIfNeeded } from '$lib/services/utils/file';\nimport { isWorkflowDraft, isWorkflowEnabled } from '$lib/services/workflow';\n\n/**\n * @import {\n * DraftValueStoreKey,\n * Entry,\n * EntryDraft,\n * EntrySlugVariants,\n * InternalEntryCollection,\n * InternalLocaleCode,\n * PendingEntry,\n * } from '$lib/types/private';\n * @import { FieldKeyPath, RelationField } from '$lib/types/public';\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 */\nconst getPendingEntriesByCollection = (draft, collectionName) =>\n  draft.pendingEntries.filter((pendingEntry) => pendingEntry.collectionName === collectionName);\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 read-only collection.\n *\n * Nothing is offered while the entry being edited is saved through Editorial Workflow: the new\n * entry would go into the pull request along with it, but a pull request stands for a single entry\n * in the workflow, so the new one would be invisible until the pull request is published. Nor is\n * anything offered when the referenced collection itself is under the workflow, as the new entry\n * would be committed along with the entry being edited, skipping the review the collection asks\n * for.\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 */\nexport const getCreatableCollection = ({\n  fieldConfig: { collection: collectionName, file: fileName },\n  draft,\n}) => {\n  if (fileName || isWorkflowDraft(draft)) {\n    return undefined;\n  }\n\n  const collection = getCollection(collectionName);\n\n  if (\n    collection?._type !== 'entry' ||\n    collection.create === false ||\n    isReadonly({ collection }) ||\n    isWorkflowEnabled(collection)\n  ) {\n    return undefined;\n  }\n\n  return collection;\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\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()`\n  return countQuotaEntries(name) + getPendingEntriesByCollection(draft, name).length < 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.\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  const refEntryIds = new Set(refEntries.map(({ id }) => id));\n\n  return getPendingEntriesByCollection(draft, collectionName)\n    .map(({ entry }) => entry)\n    .filter(({ id }) => !refEntryIds.has(id));\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.\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 refEntries = getRefEntries(fieldConfig);\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 {EntryDraft} args.parentDraft Draft being edited, holding the pending entries.\n * @returns {EntrySlugVariants} Slugs.\n */\nexport const getPendingEntrySlugs = ({ draft, parentDraft }) => {\n  const slugs = getSlugs({ draft });\n  const { defaultLocaleSlug, localizedSlugs } = slugs;\n\n  const pendingSlugs = getPendingEntriesByCollection(parentDraft, draft.collectionName).map(\n    ({ entry }) => entry.slug,\n  );\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\n  const renamedSlug = renameIfNeeded(defaultLocaleSlug, [\n    ...pendingSlugs,\n    ...getEntriesByCollection(draft.collectionName).map(({ slug }) => slug),\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 a new entry into a pending entry of the draft being edited: the entry is\n * prepared for saving the same way any entry is, and the file changes are held on the parent draft\n * until that one is saved. The draft of the new entry has to be valid; the caller checks that, as\n * 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 { collectionName } = draft;\n\n  // Each entry added takes the next order, the same way an entry saved on its own would\n  assignManualSortOrder(draft, getPendingEntriesByCollection(parentDraft, collectionName).length);\n\n  const slugs = getPendingEntrySlugs({ draft, parentDraft });\n  const { savingEntry, changes, savingAssets } = await createSavingEntryData({ draft, slugs });\n  // The value can be localized, e.g. `{{locale}}/{{slug}}`, so collect it for every locale the\n  // parent entry has\n  const { pendingEntries } = parentDraft;\n\n  const values = unique(\n    Object.keys(parentDraft.currentValues).flatMap((locale) =>\n      getEntryOptions({ locale, fieldConfig, refEntry: savingEntry, pendingEntries }).map(\n        ({ value }) => value,\n      ),\n    ),\n  );\n\n  return { collectionName, entry: savingEntry, changes, savingAssets, values };\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 from the Relation fields of that entry with a nested\n * quick-add dialog, as long as the entry still refers to them. The ones the draft inherited from\n * the parent when it was started are already there.\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 parentIds = new Set(parentDraft.pendingEntries.map(({ entry }) => entry.id));\n\n  return getReferencedPendingEntries(draft).filter(({ entry }) => !parentIds.has(entry.id));\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    pendingEntries: draft.pendingEntries,\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  @component\n  Implement the dialog to create a new entry in the collection a Relation field refers to, without\n  leaving the entry being edited. The new entry is not saved on its own: it’s added to the parent\n  draft as a pending entry, selected in the field, and committed together with the parent entry.\n  @see https://github.com/sveltia/sveltia-cms/issues/493\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 EntryEditor from '$lib/components/contents/details/editor/entry-editor.svelte';\n  import SlugEditor from '$lib/components/contents/details/editor/slug-editor.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 { buildDraft } from '$lib/services/contents/draft/create';\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 { needsSlugInput } from '$lib/services/contents/editor/slug';\n  import {\n    createPendingEntry,\n    getNestedPendingEntries,\n  } from '$lib/services/contents/fields/relation/quick-add';\n  import { createRawState } from '$lib/services/utils/state.svelte';\n\n  /**\n   * @import { EntryDraft, EntryEditorPane, InternalEntryCollection, 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 an entry in.\n   * @property {RelationField} fieldConfig Configuration of the Relation field the entry is created\n   * from.\n   * @property {(pendingEntry: PendingEntry) => void} onAdd Called with the new entry once it’s\n   * been added to the parent draft.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    collection,\n    fieldConfig,\n    onAdd,\n    /* eslint-enable prefer-const */\n  } = $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  /**\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\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\n  /**\n   * Start a new draft for the dialog.\n   */\n  const startDraft = () => {\n    // Start at the root of the collection folder. The default is the folder being browsed, which\n    // belongs to the parent entry’s collection\n    const draft = buildDraft({ collection, initialPath: '' });\n\n    // The entries pending on the parent draft are offered to the Relation fields of the new entry\n    // as well, and a nested quick-add takes them into account when it names and counts entries\n    /* v8 ignore next -- the dialog is only opened from a field editor while the draft is there */\n    draft.pendingEntries = [...(parentDraft.current?.pendingEntries ?? [])];\n    entryDraft.current = draft;\n    pane.current = { mode: 'edit', locale: defaultLocale };\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    entryDraft.current = undefined;\n    pane.current = null;\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      // The entry is committed along with the parent, so it has to be complete. Wait for what was\n      // just typed and for custom validators to report, the same way a save does\n      if (!(await validateAndRevealErrors({ draft, enforceRequired: true }))) {\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      // The entries created from the new entry’s own Relation fields come along with it\n      parentDraft.current.pendingEntries.push(\n        ...getNestedPendingEntries({ draft, parentDraft: parentDraft.current }),\n        pendingEntry,\n      );\n      onAdd(pendingEntry);\n      added = true;\n      open = false;\n    } catch (ex) {\n      showErrorToast = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      adding = false;\n    }\n  };\n\n  $effect(() => {\n    if (open) {\n      untrack(() => startDraft());\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={_('create_entry_title', { values: { name } })}\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\">{_('relation_field.save_together_hint', { values: { name } })}</p>\n    {#if entryDraft.current && pane.current}\n      {@const { locale } = pane.current}\n      <div role=\"none\" id=\"{componentId}-body\" class=\"fields\">\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 needsSlugInput(entryDraft.current) && entryDraft.current.slugEditor[locale]}\n          {#key locale}\n            <SlugEditor {locale} />\n          {/key}\n        {/if}\n        <EntryEditor {locale} />\n      </div>\n    {/if}\n  </div>\n  {#snippet footer()}\n    <Spacer flex={true} />\n    <Button\n      variant=\"primary\"\n      label={_('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<Toast bind:show={showValidationToast}>\n  <Alert status=\"error\">\n    {_('entry_validation_errors', { values: { count: errorCount } })}\n  </Alert>\n</Toast>\n\n<Toast bind:show={showErrorToast}>\n  <Alert status=\"error\">\n    {_('relation_field.add_failed', { 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  import { getContext } from 'svelte';\n\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { updateListFieldForLocales } from '$lib/services/contents/draft/update/list';\n\n  /**\n   * @import { FieldEditorContext, 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  /** @type {FieldEditorContext} */\n  const { valueStoreKey = 'currentValues' } = getContext('field-editor') ?? {};\n\n  /** @type {SelectFieldSelectorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    fieldId,\n    fieldConfig,\n    currentValue,\n    required = true,\n    readonly = false,\n    invalid = false,\n    options,\n    /* eslint-enable prefer-const */\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    /* eslint-disable prefer-const */\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    options,\n    /* eslint-enable prefer-const */\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\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    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\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  const options = $derived(\n    fieldOptions.map(\n      (option) =>\n        /** @type {SelectFieldSelectorOption} */ (\n          isObject(option) ? option : { label: option, value: option }\n        ),\n    ),\n  );\n</script>\n\n{#key JSON.stringify(options)}\n  <Select\n    {locale}\n    {keyPath}\n    {fieldId}\n    {fieldConfig}\n    bind:currentValue\n    {readonly}\n    {required}\n    {invalid}\n    {options}\n  />\n{/key}\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 } from '@sveltia/ui';\n  import { getContext } from 'svelte';\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 { getCollectionLabel } from '$lib/services/contents/collection';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getOptions } from '$lib/services/contents/fields/relation/helpers';\n  import {\n    getCreatableCollection,\n    getRefEntriesWithPending,\n    hasCreationRoom,\n    selectPendingEntry,\n  } from '$lib/services/contents/fields/relation/quick-add';\n\n  /**\n   * @import { FieldEditorContext, FieldEditorProps } 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  /** @type {FieldEditorContext} */\n  const { valueStoreKey = 'currentValues' } = getContext('field-editor') ?? {};\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\n  } = $props();\n\n  let showQuickAddDialog = $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  const currentLocaleValues = $derived(entryDraft.current?.[valueStoreKey]?.[locale]);\n  const currentSlug = $derived(\n    entryDraft.current?.currentSlugs[locale] ?? entryDraft.current?.currentSlugs._,\n  );\n  /** @type {SelectField} */\n  const selectFieldConfig = $derived({\n    ...fieldConfig,\n    widget: 'select',\n    options: getOptions({\n      locale,\n      fieldConfig,\n      refEntries,\n      currentLocaleValues,\n      currentSlug,\n      // A label can refer to another pending entry through a Relation field of the entry\n      pendingEntries: entryDraft.current?.pendingEntries,\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  /* v8 ignore start -- only read while the button is rendered, which needs the collection */\n  // `appLocale.current` is a key, because `getCollectionLabel` can return a localized label\n  const creatableName = $derived(\n    creatableCollection && appLocale.current\n      ? getCollectionLabel(creatableCollection, { useSingular: true })\n      : '',\n  );\n  /* v8 ignore stop */\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 creatableCollection}\n    <div role=\"none\" class=\"actions\">\n      <Button\n        variant=\"tertiary\"\n        size=\"small\"\n        label={_('add_x', { values: { name: creatableName } })}\n        disabled={!canCreate}\n        aria-haspopup=\"dialog\"\n        onclick={() => {\n          showQuickAddDialog = true;\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name=\"add\" />\n        {/snippet}\n      </Button>\n    </div>\n    <QuickAddDialog\n      bind:open={showQuickAddDialog}\n      collection={creatableCollection}\n      {fieldConfig}\n      onAdd={(pendingEntry) => {\n        /* v8 ignore next -- the entry is only added while the draft is being edited */\n        if (entryDraft.current) {\n          selectPendingEntry({\n            draft: entryDraft.current,\n            locale,\n            keyPath,\n            valueStoreKey,\n            fieldConfig,\n            pendingEntry,\n          });\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  return /** @type {string[]} */ (values)\n    .filter((value) => value !== undefined)\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 { getRefEntriesWithPending } 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 {\n    /* eslint-disable prefer-const */\n    locale,\n    fieldConfig,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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: entryDraft.current?.pendingEntries,\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 { flatten } from 'flat';\n\nimport { replaceTemplateTags } from '$lib/services/common/template/tags';\nimport { stripFieldTagPrefix } from '$lib/services/common/template/utils';\nimport { applyTransformations, parseTransformations } from '$lib/services/common/transformations';\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 = flatten(values);\n\n  const result = replaceTemplateTags(template, (__, placeholder) => {\n    const { value: tag, transformations } = parseTransformations(placeholder);\n    const fieldName = stripFieldTagPrefix(tag);\n    let value = flatValues[fieldName];\n\n    if (value === undefined || value === null) {\n      return '';\n    }\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  // 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 { flatten } from 'flat';\n\nimport { getObjectThumbnail } from '$lib/services/contents/fields/object/thumbnail';\n\n/**\n * @import { Entry, EntryFileMap, 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 * @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: flatten(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';\nimport { flatten, unflatten } from 'flat';\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 { 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 * 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(flatten(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 ?? unflatten(getDefaultValues({ fields, locale, defaultLocale }))\n  );\n\n  _values.__sc_component_name = componentName;\n\n  /** @type {Record<string, any>} */\n  const normalizedValues = unflatten(\n    normalizeContent({\n      fields,\n      content: flatten(_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, untrack } 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 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 {\n    getEntryDraftByElement,\n    setEntryDraftContext,\n  } from '$lib/services/contents/draft/state.svelte';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\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 { validateComponentValues } from '$lib/services/contents/fields/rich-text/components/validate';\n  import {\n    deleteKeysByPrefix,\n    flattenWithPrefix,\n    getValuesByPrefix,\n    reconcileComponentValues,\n  } from '$lib/services/contents/fields/rich-text/components/values';\n  import { 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   * 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   * @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    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\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  /* 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   * 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  /**\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   * @type {RawEntryContent | undefined}\n   */\n  const currentValues = $derived.by(() => {\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\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).\n   */\n  const handleOk = () => {\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    });\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    window.requestAnimationFrame(() => {\n      // Get the draft state, locale and key path from the closest containers\n      entryDraft = getEntryDraftByElement(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      const draft = entryDraft?.current;\n\n      // Remove the values and validities from the draft when the component is unmounted\n      if (draft) {\n        deleteKeysByPrefix(draft[valueStoreKey][locale], keyPathPrefix);\n        deleteKeysByPrefix(draft.validities[locale], keyPathPrefix);\n      }\n    };\n  });\n\n  watch(\n    () => [values, locale, keyPath],\n    () => {\n      if (entryDraft?.current && locale && keyPath) {\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        if (!equal(values, currentValues)) {\n          Object.assign(\n            entryDraft.current[valueStoreKey][locale],\n            flattenWithPrefix(/** @type {Record<string, any>} */ (values), keyPathPrefix),\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  $effect(() => {\n    if (mode === 'dialog') return;\n\n    void [currentValues];\n\n    untrack(() => {\n      if (!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   * }}\n   */ { typedPrefix, observe },\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      />\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      if (event.key === 'Enter') {\n        event.preventDefault();\n        openDialog();\n      }\n\n      if (event.key === 'Backspace') {\n        event.preventDefault();\n        onChange(new CustomEvent('remove'));\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 role=\"none\" class=\"fields\">\n        {#if locale && keyPath}\n          {@render fieldEditors({ typedPrefix: keyPathPrefix, observe: false })}\n        {/if}\n      </div>\n      {#snippet footer()}\n        <Button\n          variant=\"secondary\"\n          label={_('remove')}\n          onclick={() => {\n            handleRemove();\n          }}\n        />\n        <Spacer flex={true} />\n        <Button\n          variant=\"primary\"\n          label={_(isNewComponent ? 'insert' : 'update')}\n          onclick={() => {\n            handleOk();\n          }}\n        />\n        <Button\n          variant=\"secondary\"\n          label={_('cancel')}\n          onclick={() => {\n            handleCancel();\n          }}\n        />\n      {/snippet}\n    </Dialog>\n  {/if}\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    onkeydowncapture={(event) => {\n      const { target } = event;\n\n      // A nested rich text editor handles its own keys, so leave the event alone when it comes\n      // from one: stopping it here would keep it from ever reaching the nested editor, which is\n      // below in the capture phase, and cancelling it would block typing there. The outer editor\n      // ignores the event once it bubbles up, as Lexical marks it as handled by the nested one\n      if (/** @type {HTMLElement} */ (target).closest('[contenteditable]') !== wrapper) {\n        return;\n      }\n\n      // Allow to select all in any `TextInput` within the component below using Ctrl+A. Svelte\n      // delegates `keydown` to the root, which the event never reaches once it’s stopped, so the\n      // block’s own handling has to happen here as well\n      event.stopPropagation();\n\n      if (\n        !(/** @type {HTMLElement} */ (target).matches('button, input, textarea')) &&\n        event.key !== 'Tab'\n      ) {\n        event.preventDefault();\n      }\n\n      if (event.target === wrapper && event.key === 'Backspace') {\n        onChange(new CustomEvent('remove'));\n      }\n    }}\n  >\n    <ObjectHeader\n      {label}\n      controlId=\"object-{fieldId}-item-list\"\n      expandable={hasFields}\n      bind:expanded\n    >\n      {#snippet endContent()}\n        <RemoveButton\n          onclick={() => {\n            onChange(new CustomEvent('remove'));\n          }}\n        />\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([data-component-name='image'], [data-component-name='linked-image']) {\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  .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","import { getImmutable, immutableLoaded } from '$lib/services/api/immutable';\nimport { supportsHTML } from '$lib/services/contents/fields/rich-text/components/utils';\nimport { GLOBAL_IMAGE_REGEX } from '$lib/services/contents/fields/rich-text/constants';\nimport { getOrCreate } from '$lib/services/utils/cache';\nimport { escapeHTML } from '$lib/services/utils/string';\n\n/**\n * @import { List, MapOf } from 'immutable';\n * @import { ReactElement } from 'react';\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 * 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 */\nconst MEDIA_URL_ATTRIBUTES = {\n  img: ['src', 'srcset'],\n  source: ['src', 'srcset'],\n  video: ['src', 'poster'],\n  audio: ['src'],\n};\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.\n */\nexport const MEDIA_QUERY_SELECTOR = `:is(${Object.entries(MEDIA_URL_ATTRIBUTES)\n  .flatMap(([tagName, names]) => names.map((name) => `${tagName}[${name}]`))\n  .join(', ')}):not([data-processed])`;\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 * 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. Once a `<source>` of a\n * video or audio element is updated, the media is loaded again, as the element doesn’t pick up the\n * change 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  let updated = false;\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  await Promise.all(\n    names.map(async (name) => {\n      const value = element.getAttribute(name);\n\n      if (!value) {\n        return;\n      }\n\n      if (name === 'srcset') {\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        if (urls.some((url, index) => url !== candidates[index].url)) {\n          element.setAttribute(\n            name,\n            candidates\n              .map(({ descriptor }, index) => [urls[index], descriptor].filter(Boolean).join(' '))\n              .join(', '),\n          );\n          updated = true;\n        }\n\n        return;\n      }\n\n      const url = await resolveURL(value);\n\n      if (url !== value) {\n        element.setAttribute(name, url);\n        updated = true;\n      }\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\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 * 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 * Regex to detect the opening line of a fenced code block (backtick or tilde fence).\n */\nconst FENCE_OPEN_REGEX = /^[ ]{0,3}(`{3,}|~{3,})/;\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 * @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 * Split a Markdown string into logical blocks at blank lines, keeping fenced code blocks (backtick\n * or tilde fences) and HTML block elements (e.g. `<div>`) intact even when they contain blank\n * 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  /** @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\n  markdown.split('\\n').forEach((line) => {\n    if (fence) {\n      current.push(line);\n\n      // Closing fence: same char, at most 3 leading spaces, no trailing content\n      const stripped = line.trimStart();\n\n      if (\n        line.length - stripped.length <= 3 &&\n        stripped.startsWith(fence.char.repeat(fence.length)) &&\n        !/\\S/.test(stripped.slice(fence.length))\n      ) {\n        fence = null;\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 = FENCE_OPEN_REGEX.exec(line);\n\n      if (fenceMatch) {\n        current.push(line);\n        fence = { char: fenceMatch[1][0], length: fenceMatch[1].length };\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 (current.length) {\n            blocks.push(current.splice(0).join('\\n'));\n          }\n        } else {\n          current.push(line);\n        }\n      }\n    }\n  });\n\n  if (current.length) blocks.push(current.join('\\n'));\n\n  return blocks;\n};\n\n/**\n * Encode image URLs in Markdown to ensure spaces are properly handled.\n * E.g. `![alt](my image.png)` -> `![alt](my%20image.png)`.\n * @param {...any} args Arguments from the regex match.\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 } = args.at(-1);\n  const eSrc = src.replaceAll(' ', '%20');\n\n  return title ? `![${alt}](${eSrc} \"${title}\")` : `![${alt}](${eSrc})`;\n};\n\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 {EditorComponentDefinition} 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 {EditorComponentDefinition[]} 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.\n */\nconst findOutermostMatches = (string, componentDefs, regions) => {\n  /** @type {ComponentMatch[]} */\n  const candidates = [];\n\n  componentDefs.forEach((def, order) => {\n    string.matchAll(getGlobalPattern(def.pattern)).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 (match[0] && (!regions || isMatchWithinPreviewValues(candidate, regions))) {\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 * 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  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    chunks.push(string.slice(cursor, index));\n    length += index - cursor;\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    } 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.\n      const placeholder = `<span data-component-key=\"${key}\"></span>`;\n\n      chunks.push(placeholder);\n      length += placeholder.length;\n    }\n\n    cursor = end;\n  });\n\n  chunks.push(string.slice(cursor));\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 {EditorComponentDefinition[]} 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.\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 {EditorComponentDefinition[]} 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  let string = (currentValue ?? '').replace(GLOBAL_IMAGE_REGEX, encodeImageSrc);\n  /** @type {PreviewRegion[] | undefined} */\n  let regions;\n\n  for (let pass = 0; pass < MAX_SUBSTITUTION_PASSES && componentDefs.length; pass += 1) {\n    const matches = findOutermostMatches(string, componentDefs, 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 { DecoratorNode, getNearestEditorFromDOMNode } from 'lexical';\nimport { flushSync, mount, tick, unmount } from 'svelte';\n\nimport EditorComponent from '$lib/components/contents/details/fields/rich-text/editor-component.svelte';\nimport {\n  getSelectorTagNames,\n  isMultiLinePattern,\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';\n\n/**\n * @import {\n * DOMConversion,\n * DOMConversionMap,\n * DOMConversionOutput,\n * DOMExportOutput,\n * LexicalEditor,\n * NodeKey,\n * SerializedLexicalNode,\n * } from 'lexical';\n * @import { ReactElement } from 'react';\n * @import { EditorComponentDefinition } from '$lib/types/public';\n */\n\nconst TAG_NAME_REGEX = /^<(?<tagName>[a-z]+)/i;\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 {EditorComponentDefinition} 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    pattern,\n    toBlock,\n    toPreview,\n    htmlSelector,\n    fromBlockHTML,\n    toBlockHTML,\n  } = componentDef;\n\n  const inline = !isMultiLinePattern(pattern);\n  const htmlSupported = supportsHTML(componentDef);\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 = htmlSupported\n    ? undefined\n    : callWithEmptyProps(toPreview, [getNoAsset, getComponentFieldList(componentDef)]);\n\n  const block = htmlSupported ? undefined : callWithEmptyProps(toBlock);\n  const tagName = htmlSupported ? undefined : getTagName(preview, block);\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     * 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.\n     * @param {SerializedLexicalNode} serializedNode Input.\n     * @returns {CustomNode} New node.\n     */\n    static importJSON(serializedNode) {\n      return new CustomNode().updateFromJSON(serializedNode);\n    }\n\n    /**\n     * Export the node as JSON.\n     * @returns {SerializedLexicalNode} Output.\n     */\n    exportJSON() {\n      return {\n        ...normalizeProps(this.__props ?? {}),\n        type: componentName,\n        version: 1,\n      };\n    }\n\n    /**\n     * Create a DOM node.\n     * @returns {HTMLElement} New element.\n     */\n    createDOM() {\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.\n        // This prevents the parent Lexical editor from stealing focus when updating node props.\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            /**\n             * Restore focus and selection after the Lexical update completes.\n             */\n            onUpdate: () => {\n              if (activeEl && document.body.contains(activeEl)) {\n                activeEl.focus();\n\n                if (selectionRange && selection) {\n                  selection.removeAllRanges();\n                  selection.addRange(selectionRange);\n                }\n              }\n            },\n          },\n        );\n      };\n\n      component = 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      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        // Focus the wrapper if the parent field is editable. This is necessary because `i18n:\n        // duplicate` field is rendered as a read-only textbox in non-default locales, which may\n        // steal focus from the wrapper of the default locale\n        if (wrapper.closest('[role=\"textbox\"][aria-readonly=\"false\"]')) {\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.\n     * @returns {boolean} Result.\n     */\n    updateDOM() {\n      return false;\n    }\n  }\n\n  return CustomNode;\n};\n","import {\n  isMultiLinePattern,\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 { EditorComponentDefinition } from '$lib/types/public';\n */\n\n/**\n * Create a singleline/inline or multiline transformer for the given component definition.\n * @param {object} args Arguments.\n * @param {EditorComponentDefinition} 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 } = 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 (isMultiLinePattern(pattern)) {\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        const endLineIndex = startLineIndex + matchString.split('\\n').length - 1;\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      replace: () => undefined,\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    importRegExp: 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 { 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 { EditorComponentDefinition } from '$lib/types/public';\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 {EditorComponentDefinition} 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    // eslint-disable-next-line jsdoc/require-jsdoc\n    createNode: (props) => new CustomNode(props),\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 {EditorComponentDefinition} 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 { getDateTimeParts } from '@sveltia/utils/datetime';\n\nimport {\n  RASTER_IMAGE_EXTENSION_REGEX,\n  SUPPORTED_IMAGE_TYPES,\n  VECTOR_IMAGE_EXTENSION_REGEX,\n} from '$lib/services/utils/media/image';\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 * 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        // `split()` always yields at least one segment, so `pop()` never returns `undefined`\n        const name = /** @type {string} */ (new URL(img.src).pathname.split('/').pop());\n\n        if (hasImageExtension(name)) {\n          fileName = name;\n        }\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 { TextEditor } 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  import { getContext, tick } from 'svelte';\n\n  import { EditorComponent } from '$lib/components/contents/details/fields/rich-text/custom-node-features';\n  import { customComponentRegistry } from '$lib/services/api/registries';\n  import { cmsConfig } from '$lib/services/config';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { trackPendingFieldUpdate } from '$lib/services/contents/editor/pending';\n  import { getField } from '$lib/services/contents/entry/fields';\n  import {\n    getAssetLibraryFolderMap,\n    getDefaultAssetFolder,\n  } from '$lib/services/contents/fields/file/helpers';\n  import { processResource } from '$lib/services/contents/fields/file/process';\n  import {\n    BUILTIN_COMPONENTS,\n    BUTTON_NAME_MAP,\n    COMPONENT_NAME_PREFIX_REGEX,\n    DEFAULT_BUTTONS,\n    DEFAULT_MODES,\n    getValueFormat,\n    NODE_NAME_MAP,\n  } from '$lib/services/contents/fields/rich-text';\n  import { getComponentDef } from '$lib/services/contents/fields/rich-text/components/definitions';\n  import { supportsHTML } from '$lib/services/contents/fields/rich-text/components/utils';\n  import {\n    getDroppedImages,\n    getPastedImages,\n  } from '$lib/services/contents/fields/rich-text/images';\n  import { getCanonicalLocale, getDirection } from '$lib/services/contents/i18n';\n  import { getDefaultMediaLibraryOptions } from '$lib/services/integrations/media-libraries/default';\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 { FieldEditorContext, FieldEditorProps } 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  /** @type {FieldEditorContext} */\n  const { fieldContext, parentComponentNames, valueStoreKey } = getContext('field-editor') ?? {};\n  /* v8 ignore stop */\n  const inEditorComponent = fieldContext === 'rich-text-editor-component';\n  const componentName = parentComponentNames.at(-1);\n\n  /** @type {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\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  const {\n    // Field type-specific options\n    modes: _modes = defaultConfig.modes ?? [...DEFAULT_MODES],\n    buttons: _buttons = defaultConfig.buttons ?? [...DEFAULT_BUTTONS],\n    editor_components: _editorComponents = defaultConfig.editor_components ??\n      // Include all built-in and custom components by default\n      [...BUILTIN_COMPONENTS, ...customComponentRegistry.keys()],\n    allow_nested_components: _allowNestedComponents,\n    linked_images: linkedImagesEnabled = defaultConfig.linked_images ?? true,\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  } = $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(getValueMapSnapshot(entryDraft.current, locale, valueStoreKey));\n  const buttons = $derived(\n    [\n      ..._buttons,\n      // Include `code-block` implemented as a block type\n      ...(_editorComponents.includes('code-block') ? ['code-block'] : []),\n    ]\n      // @ts-ignore\n      .map((name) => BUTTON_NAME_MAP[name])\n      .filter(Boolean),\n  );\n  const allowNestedComponents = $derived.by(() => {\n    let nested = _allowNestedComponents;\n\n    if (inEditorComponent) {\n      // Retrieve the parent Markdown or RichText field config\n      nested = /** @type {MarkdownField | RichTextField} */ (\n        getField({\n          collectionName,\n          fileName,\n          isIndexFile,\n          valueMap,\n          // Extract the parent field name, e.g. `body:c55:content` -> `body`\n          keyPath: /** @type {string} */ (keyPath.match(/^[^:]+/)?.[0]),\n        })\n      )?.allow_nested_components;\n    }\n\n    return nested ?? defaultConfig.allow_nested_components ?? true;\n  });\n  const components = $derived.by(() => {\n    if (inEditorComponent && !allowNestedComponents) {\n      return [];\n    }\n\n    return (\n      _editorComponents\n        .map((name) =>\n          getComponentDef(name === 'image' && linkedImagesEnabled ? 'linked-image' : name),\n        )\n        .filter((def) => !!def)\n        // Only the components with HTML syntax can be used in HTML\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) =>\n            allowNestedComponents !== 'exclude_self' || !parentComponentNames.includes(def.id),\n        )\n        .map(\n          (def) =>\n            /** @type {import('@sveltia/ui').TextEditorComponent} */ (new EditorComponent(def)),\n        )\n    );\n  });\n  const imageComponent = $derived(\n    components.find(({ id }) => id === 'image' || id === 'linked-image'),\n  );\n  const targetAssetFolder = $derived(\n    getDefaultAssetFolder(\n      getAssetLibraryFolderMap({\n        collectionName,\n        fileName,\n        componentName,\n        typedKeyPath,\n        isIndexFile,\n      }),\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 srcFieldConfig =\n      /** @type {import('@sveltia/ui').TextEditorComponent & EditorComponentDefinition} */ (\n        imageComponent\n      ).fields?.find(({ name }) => name === 'src');\n\n    const { config: libraryConfig } = getDefaultMediaLibraryOptions({\n      fieldConfig: /** @type {ImageField} */ (srcFieldConfig),\n    });\n\n    const draft = entryDraft.current;\n    const folder = targetAssetFolder;\n\n    // eslint-disable-next-line no-restricted-syntax\n    for (const { file, src: externalSrc, alt = '' } of images) {\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        });\n\n        src = value;\n      }\n\n      if (!src) {\n        // eslint-disable-next-line no-continue\n        continue;\n      }\n\n      const _src = src;\n\n      editor.update(() => {\n        insertNodes([imageComponent.createNode({ src: _src, alt }), createParagraphNode()]);\n      });\n    }\n  };\n\n  /**\n   * Handle pasted content. If it includes images, insert them to the editor content.\n   * @param {ClipboardEvent} event `paste` event.\n   */\n  const onPaste = async (event) => {\n    const { target } = event;\n    const images = await getPastedImages(event);\n\n    if (images.length) {\n      await insertImages({ target, images });\n    }\n  };\n\n  /**\n   * Handle dropped content. If it includes images, insert them to the editor content.\n   * @param {DragEvent} event `drop` event.\n   */\n  const onDrop = async (event) => {\n    const { target } = event;\n    const images = await getDroppedImages(event);\n\n    if (images.length) {\n      await insertImages({ target, images });\n    }\n  };\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      Object.keys(draft.extraValues[locale]).forEach((key) => {\n        const [prefix] = key.match(COMPONENT_NAME_PREFIX_REGEX) ?? [];\n\n        if (\n          prefix?.startsWith(`${keyPath}:`) &&\n          !wrapper?.querySelector(`[data-key-path-prefix=\"${prefix}\"]`)\n        ) {\n          delete draft.extraValues[locale][key];\n        }\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\n  $effect(() => {\n    if (!pending) {\n      return undefined;\n    }\n\n    /** @type {PromiseWithResolvers<void>} */\n    const { promise, resolve } = Promise.withResolvers();\n\n    trackPendingFieldUpdate(promise);\n\n    // Settle once the value has reached `currentValue` through the bindings and effects, or when\n    // the editor goes away\n    return async () => {\n      await tick();\n      resolve();\n    };\n  });\n</script>\n\n<div role=\"none\" class=\"wrapper\" class:minimal 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        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<style>\n  .wrapper {\n    --sui-paragraph-margin: 20px;\n    display: contents;\n\n    &.minimal {\n      :global {\n        :is([role='textbox'], textarea) {\n          overflow: auto;\n          max-height: 240px;\n        }\n      }\n    }\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 { marked } from 'marked';\n\nexport default function() {\n  return {\n    useNewRenderer: true,\n    renderer: {\n      heading(...args) {\n        const html = marked.Renderer.prototype.heading.call(this, ...args);\n        return html.replace(/^<(h\\d)/, '<$1 dir=\"auto\"');\n      },\n\n      list(...args) {\n        const html = marked.Renderer.prototype.list.call(this, ...args);\n        return html.replace(/^<(ol|ul)/, '<$1 dir=\"auto\"');\n      },\n\n      paragraph(...args) {\n        const html = marked.Renderer.prototype.paragraph.call(this, ...args);\n        return html.replace(/^<p/, '<p dir=\"auto\"');\n      },\n    },\n  };\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","<!--\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>\n  import { highlightCodeToHTML, loadCodeHighlighter } from '@sveltia/ui';\n  import { parse, use } from 'marked';\n  import markedBidi from 'marked-bidi';\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 { getReactDom, loadReactDom, reactDomLoaded } from '$lib/services/api/react-dom';\n  import { customComponentRegistry } from '$lib/services/api/registries';\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 { BUILTIN_COMPONENTS, getValueFormat } from '$lib/services/contents/fields/rich-text';\n  import { getComponentDef } from '$lib/services/contents/fields/rich-text/components/definitions';\n  import {\n    buildMarkdownWithPreviews,\n    COMPONENT_QUERY_SELECTOR,\n    CONTAINER_QUERY_SELECTOR,\n    MEDIA_QUERY_SELECTOR,\n    resolveMediaURLs,\n    splitHTMLBlocks,\n    splitMarkdownBlocks,\n  } from '$lib/services/contents/fields/rich-text/previews';\n  import { sanitizeRichTextHTML } from '$lib/services/contents/fields/rich-text/sanitize';\n\n  /**\n   * @import { ReactElement } from 'react';\n   * @import { FieldPreviewProps } from '$lib/types/private';\n   * @import { ApiAsset, MarkdownField, RichTextField } from '$lib/types/public';\n   * @import { ComponentPreview } from '$lib/services/contents/fields/rich-text/previews';\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  use(markedBidi());\n\n  use({\n    renderer: {\n      // Add syntax highlighting for code blocks 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.\n      // Shiki loads its engine and grammars on demand, so this returns nothing until the language\n      // is ready; `preloadHighlighter()` below fetches it and triggers a re-render.\n      // eslint-disable-next-line jsdoc/require-jsdoc\n      code({ text, lang }) {\n        return (lang ? highlightCodeToHTML(text, lang) : undefined) ?? false;\n      },\n    },\n  });\n\n  const defaultConfig = cmsConfig.current?.field_defaults?.richtext ?? {};\n  /** @type {SvelteMap<HTMLElement, import('react-dom/client').Root>} */\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  /** @type {FieldPreviewProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    typedKeyPath,\n    fieldConfig,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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  /* 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  const {\n    sanitize_preview: doSanitize = defaultConfig.sanitize_preview ?? true,\n    editor_components: _editorComponents = defaultConfig.editor_components ??\n      // Include all built-in and custom components by default\n      [...BUILTIN_COMPONENTS, ...customComponentRegistry.keys()],\n    linked_images: linkedImagesEnabled = defaultConfig.linked_images ?? true,\n  } = $derived(fieldConfig);\n  const format = $derived(getValueFormat(fieldConfig));\n  const isHTML = $derived(format === 'html');\n  const componentDefs = $derived(\n    _editorComponents\n      .map((name) =>\n        getComponentDef(name === 'image' && linkedImagesEnabled ? 'linked-image' : name),\n      )\n      .filter((def) => !!def),\n  );\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    }),\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: editing near the top of a long document then only re-renders the block that\n   * changed, instead of every block after it. Identical blocks are told apart by their occurrence.\n   * @type {{ key: string, block: string }[]}\n   */\n  const keyedBlocks = $derived.by(() => {\n    // A scratch counter for this computation, not state\n    // eslint-disable-next-line svelte/prefer-svelte-reactivity\n    const occurrences = /** @type {Map<string, number>} */ (new Map());\n\n    return (isHTML ? splitHTMLBlocks : splitMarkdownBlocks)(markdown).map((block) => {\n      const occurrence = occurrences.get(block) ?? 0;\n\n      occurrences.set(block, occurrence + 1);\n\n      return { key: `${occurrence}\\n${block}`, block };\n    });\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 = [...value.matchAll(/^ {0,3}```(\\S+)/gm)]\n      .map(([, lang]) => lang)\n      .filter((lang, index, list) => list.indexOf(lang) === index)\n      .sort()\n      .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 = getReactDom().createRoot(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      }),\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. An HTML value is only sanitized.\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 doSanitize ? sanitizeRichTextHTML(rawHTML) : 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 {\n    /* eslint-disable prefer-const */\n    locale,\n    fieldConfig,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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 {\n    /* eslint-disable prefer-const */\n    fieldConfig,\n    locale,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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 { getContext } from 'svelte';\n\n/**\n * @import { Component } from 'svelte';\n * @import { FieldEditorContext } from '$lib/types/private';\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  /** @type {FieldEditorContext} */\n  const { extraHint } = getContext('field-editor') ?? {};\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.\n  @see https://decapcms.org/docs/widgets/#String\n  @see https://sveltiacms.app/en/docs/fields/string\n-->\n<script>\n  import { 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 } 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 {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  let inputValue = $state('');\n\n  const {\n    type = 'text',\n    // svelte-ignore state_referenced_locally\n    use_emoji_autocomplete: useEmojiAutocomplete = type === 'text',\n  } = $derived(fieldConfig);\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) => getStringInputValue({ currentValue: value, fieldConfig }),\n    (input) => getStringFieldValue({ inputValue: input, fieldConfig }),\n  );\n\n  setExtraHint(CharacterCounter);\n</script>\n\n<TextInput\n  lang={getCanonicalLocale(locale)}\n  dir={getDirection(locale)}\n  bind:value={inputValue}\n  {type}\n  inputmode={type}\n  flex\n  {readonly}\n  {required}\n  {invalid}\n  aria-labelledby=\"{fieldId}-label\"\n  aria-errormessage=\"{fieldId}-error\"\n  {useEmojiAutocomplete}\n/>\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\n  /**\n   * @typedef {object} Props\n   * @property {string} url Video URL.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    url,\n    /* eslint-enable prefer-const */\n  } = $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={encodeURI(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={encodeURI(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\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    fieldConfig,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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={encodeURI(value)}>{value}</a>\n    {:else if previewType === 'email'}\n      <a href=\"mailto:{encodeURI(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\n  /* Remove the padding to make the iframe full-width on small screens */\n  @media (width < 768px) {\n    :global([role='document'] section) > p:has(:global(iframe)) {\n      margin-inline: calc(var(--entry-preview-padding-inline) * -1);\n    }\n  }\n</style>\n","<!--\n  @component\n  Implement the editor 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 { TextArea } 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 { 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 { 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 {\n    /* eslint-disable prefer-const */\n    locale,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = false,\n    invalid = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  let inputValue = $state('');\n\n  const { use_emoji_autocomplete: useEmojiAutocomplete = true } = $derived(fieldConfig);\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  setExtraHint(CharacterCounter);\n</script>\n\n<TextArea\n  lang={getCanonicalLocale(locale)}\n  dir={getDirection(locale)}\n  bind:value={inputValue}\n  flex\n  {readonly}\n  {required}\n  {invalid}\n  aria-labelledby=\"{fieldId}-label\"\n  aria-errormessage=\"{fieldId}-error\"\n  autoResize={true}\n  {useEmojiAutocomplete}\n/>\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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  import { onMount } from 'svelte';\n\n  import { warnDeprecation } from '$lib/services/config/deprecations';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\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  /** @type {FieldEditorProps & Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    fieldId,\n    fieldConfig,\n    currentValue = $bindable(),\n    required = true,\n    readonly = true,\n    invalid = false,\n    /* eslint-enable prefer-const */\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 (!currentValue && (locale === defaultLocale || isFieldTranslatable(fieldConfig?.i18n))) {\n        currentValue = getInitialValue(fieldConfig);\n      }\n    },\n  );\n\n  onMount(() => {\n    // @todo Remove the option prior to the 1.0 release.\n    if ('read_only' in fieldConfig) {\n      warnDeprecation('uuid_read_only');\n    }\n  });\n</script>\n\n<TextInput\n  dir=\"ltr\"\n  bind:value={currentValue}\n  flex\n  readonly={readonly && fieldConfig.read_only !== false}\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 {\n    /* eslint-disable prefer-const */\n    currentValue,\n    /* eslint-enable prefer-const */\n  } = $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 { 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 { getInheritedI18nOption } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { populateDefaultValue } from '$lib/services/contents/draft/defaults';\nimport { deleteSubtree } from '$lib/services/contents/entry/subtree';\nimport { syncAllDuplicateKeys } from '$lib/services/contents/fields/key-value/duplicate-keys';\nimport { getListFieldInfo } from '$lib/services/contents/fields/list/helpers';\nimport { isFieldTranslatable } from '$lib/services/contents/i18n/fields';\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 * FieldWithSubFields,\n * FieldWithTypes,\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` 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 mirrors the default locale’s values of the duplicated fields. Only those fields\n * are reset then.\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, 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    const { fields } = /** @type {FieldWithSubFields} */ (fieldConfig);\n    const { types, typeKey = 'type' } = /** @type {FieldWithTypes} */ (fieldConfig);\n    const { default: objectDefault } = /** @type {ObjectField} */ (fieldConfig);\n    const type = content[`${keyPath}.${typeKey}`];\n    const subFields = fields ?? types?.find(({ name }) => name === type)?.fields ?? [];\n\n    subFields.forEach((subField) => {\n      // The default value of the Object field as a whole takes precedence over the subfield’s own\n      const subFieldConfig =\n        restore && isObject(objectDefault) && subField.name in objectDefault\n          ? /** @type {Field} */ ({ ...subField, default: objectDefault[subField.name] })\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 default locale where the field is duplicated\n      i18n === 'duplicate'\n    : // A field that isn’t translatable follows the default locale, so it can’t be edited in\n      // another locale\n      locale === defaultLocale || isFieldTranslatable(ownI18n);\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 }),\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, if that’s the default locale,\n * in the other locales where the field is duplicated.\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  resetContent({ ...args, content: valueStore[locale], locale });\n\n  if (locale === args.defaultLocale) {\n    Object.entries(valueStore).forEach(([otherLocale, content]) => {\n      if (otherLocale !== locale) {\n        resetContent({ ...args, content, locale: otherLocale, mirror: true });\n      }\n    });\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 {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 {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 * @returns {boolean} Result.\n */\nexport const canResetField = ({ valueMap, restore = false, ...args }) => {\n  const values = collectFieldValues(valueMap, args.keyPath);\n  const resetValues = { ...values };\n\n  resetContent({ ...args, content: resetValues, restore });\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` strategy or along with an ancestor’s.\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 = ({ draft, fieldConfig, keyPath, locale, restore = false }) => {\n  const { collectionName, fileName, isIndexFile, currentValues, defaultLocale } = draft;\n  const getFieldArgs = { collectionName, fileName, isIndexFile };\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      valueStore: currentValues,\n      fieldConfig,\n      keyPath,\n      locale,\n      defaultLocale,\n      restore,\n      inheritedI18n: getInheritedI18nOption({\n        fieldConfig,\n        getFieldArgs: { ...getFieldArgs, keyPath, valueMap: currentValues[locale] },\n      }),\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({ valueStore: currentValues, defaultLocale, getFieldArgs });\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.\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 { collectionName, fileName, isIndexFile, 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: { collectionName, fileName, isIndexFile },\n      });\n    }\n  });\n};\n","import equal from 'fast-deep-equal';\n\nimport { collectFieldValues } from '$lib/services/contents/draft';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { isKeyPathWithin } from '$lib/services/contents/entry/key-paths';\nimport { syncAllDuplicateKeys } from '$lib/services/contents/fields/key-value/duplicate-keys';\nimport { getKeyValueField } from '$lib/services/contents/fields/key-value/pairs';\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.\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.\n */\nexport const resolveOriginalKeyPath = (valueMap, keyPath) => {\n  const parts = keyPath.split('.');\n\n  for (let i = parts.length - 1; i >= 1; i -= 1) {\n    if (isNumeric(parts[i])) {\n      const itemPrefix = parts.slice(0, i + 1).join('.');\n      const originalPrefix = valueMap[`${itemPrefix}.__sc_item_original_key_path`];\n\n      if (originalPrefix !== undefined) {\n        const suffix = parts.slice(i + 1).join('.');\n\n        return {\n          originalKeyPath: suffix ? `${originalPrefix}.${suffix}` : originalPrefix,\n          currentPrefix: itemPrefix,\n          originalPrefix,\n        };\n      }\n    }\n  }\n\n  return undefined;\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 fieldConfig =\n        getField({ ...getFieldArgs, keyPath: _keyPath }) ??\n        // A KeyValue pair is governed by its field\n        getKeyValueField({ ...getFieldArgs, keyPath: _keyPath });\n\n      if (\n        isDefaultLocale ||\n        [true, 'translate', 'duplicate_keys'].includes(fieldConfig?.i18n ?? false)\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 */\nexport const revertLocale = ({ draft, keyPath, locale }) => {\n  const {\n    collection,\n    collectionName,\n    collectionFile,\n    fileName,\n    currentValues,\n    originalValues,\n    isIndexFile,\n  } = draft;\n\n  const { defaultLocale } = (collectionFile ?? collection)._i18n;\n  const isDefaultLocale = locale === defaultLocale;\n  /** @type {GetFieldArgs} */\n  const getFieldArgs = { collectionName, fileName, keyPath: '', isIndexFile };\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 * 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 {\n    collection,\n    collectionName,\n    collectionFile,\n    fileName,\n    isIndexFile,\n    currentValues,\n    originalPath,\n    originalSlugs,\n  } = draft;\n\n  const { allLocales, defaultLocale } = (collectionFile ?? collection)._i18n;\n  const locales = targetLanguage ? [targetLanguage] : allLocales;\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 — or a move or rename would survive the revert and still be\n  // committed on the next save\n  const revertsEverything = !targetLanguage && !keyPath;\n\n  locales.forEach((locale) => {\n    revertLocale({ draft, keyPath, locale });\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: { collectionName, fileName, isIndexFile },\n  });\n\n  if (revertsEverything) {\n    draft.currentPath = originalPath;\n    draft.currentSlugs = { ...originalSlugs };\n  }\n};\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Menu, MenuButton, Spacer } from '@sveltia/ui';\n  import { getContext, setContext } from 'svelte';\n\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 { canResetField, resetField } from '$lib/services/contents/draft/update/reset';\n  import { isFieldChanged, revertChanges } from '$lib/services/contents/draft/update/revert';\n  import { getValueMapSnapshot } from '$lib/services/contents/draft/value-map.svelte';\n  import { getFieldLocaleAccess } from '$lib/services/contents/editor/locale';\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 { getDraftI18nConfig } from '$lib/services/contents/i18n/config';\n  import { createRawState } from '$lib/services/utils/state.svelte';\n  import { sanitizeInlineMarkdown } 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 {\n   * BooleanField,\n   * CustomField,\n   * Field,\n   * FieldKeyPath,\n   * NumberField,\n   * StringField,\n   * VisibleField,\n   * } from '$lib/types/public';\n   */\n\n  /** @type {FieldEditorContext} */\n  const parent = getContext('field-editor') ?? {};\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   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldConfig,\n    context: fieldContext = parent.fieldContext ?? undefined,\n    componentName,\n    valueStoreKey = parent.valueStoreKey ?? 'currentValues',\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const fieldId = $props.id();\n\n  /**\n   * Parse the given string as Markdown and sanitize the result to only allow certain tags. A\n   * literal `\\n` is turned into a line break.\n   * @param {string} str Original string.\n   * @returns {string} Sanitized string.\n   */\n  const _sanitize = (str) =>\n    sanitizeInlineMarkdown(str.replaceAll('\\\\n', '<br>'), {\n      allowedTags: ['strong', 'em', 'del', 'code', 'a', 'br'],\n    });\n\n  /**\n   * Write a value coming from the widget editor back to the entry draft.\n   *\n   * The write is deferred to a microtask so that it happens outside Svelte’s update cycle. Widget\n   * editors sync their local state to this binding from an `$effect`, and Svelte can only memoize\n   * its dirty-marking traversal for writes made outside a running reaction. Without the deferral,\n   * marking re-walks the derived graph once per path that reaches it, which is exponential in the\n   * depth of the editor tree — tens of seconds per keystroke on a deeply nested entry.\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    queueMicrotask(() => {\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  setContext(\n    'field-editor',\n    // svelte-ignore state_referenced_locally\n    /** @type {FieldEditorContext} */ ({\n      fieldContext,\n      parentComponentNames: [...(parent.parentComponentNames ?? []), componentName].filter(Boolean),\n      extraHint,\n      valueStoreKey,\n    }),\n  );\n\n  const inEditorComponent = $derived(fieldContext === 'rich-text-editor-component');\n  const { name: fieldName, widget: fieldType = 'string' } = $derived(fieldConfig);\n  const {\n    label = '',\n    hint = '',\n    readonly: readonlyOption,\n  } = $derived(/** @type {VisibleField} */ (fieldConfig));\n  const required = $derived(isFieldRequired({ fieldConfig, locale }));\n  const multiple = $derived(isFieldMultiple(fieldConfig));\n  const allowPrefix = $derived(['string'].includes(fieldType));\n  const prefix = $derived(\n    allowPrefix ? /** @type {StringField} */ (fieldConfig).prefix : undefined,\n  );\n  const suffix = $derived(\n    allowPrefix ? /** @type {StringField} */ (fieldConfig).suffix : undefined,\n  );\n  const allowExtraLabels = $derived(['boolean', 'number', 'string'].includes(fieldType));\n  const beforeInputLabel = $derived(\n    allowExtraLabels\n      ? /** @type {BooleanField | NumberField | StringField} */ (fieldConfig).before_input\n      : undefined,\n  );\n  const afterInputLabel = $derived(\n    allowExtraLabels\n      ? /** @type {BooleanField | NumberField | StringField} */ (fieldConfig).after_input\n      : undefined,\n  );\n  const hasExtraLabels = $derived(!!(prefix || suffix || beforeInputLabel || afterInputLabel));\n  const isList = $derived(fieldType === 'list' || multiple);\n  const originalValues = $derived(entryDraft.current?.originalValues);\n  const { i18nEnabled, allLocales, defaultLocale } = $derived(\n    getDraftI18nConfig(entryDraft.current),\n  );\n  const otherLocales = $derived(i18nEnabled ? allLocales.filter((l) => l !== locale) : []);\n  const valueMap = $derived(getValueMapSnapshot(entryDraft.current, locale, valueStoreKey));\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(label || fieldName);\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  const hidden = $derived(fieldType === 'compute' || (autoNow && !!entryDraft.current?.isNew));\n  const readonly = $derived(\n    // The `readonly` option defaults to `true` for the UUID field type, which can be unlocked\n    (readonlyOption ?? fieldType === 'uuid') ||\n      autoNow ||\n      locked ||\n      isDuplicated ||\n      fieldType === 'compute',\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  /**\n   * Whether restoring the default value or clearing the field would change anything. It takes\n   * going through the whole field, so it’s only checked as the menu opens rather than on every\n   * change.\n   */\n  let resetAvailability = $state({ restore: false, clear: false });\n  const invalid = $derived(validity?.valid === false);\n\n  /**\n   * Check whether restoring the default value or clearing the field would change anything.\n   */\n  const updateResetAvailability = () => {\n    const args = { valueMap, fieldConfig, keyPath, locale, defaultLocale };\n\n    resetAvailability = {\n      restore: canResetField({ ...args, restore: true }),\n      clear: canResetField(args),\n    };\n  };\n  const editorProps = $derived({\n    locale,\n    keyPath,\n    typedKeyPath,\n    fieldId,\n    fieldLabel,\n    fieldConfig,\n    readonly,\n    required,\n    invalid,\n  });\n</script>\n\n{#snippet beforeInput()}\n  {#if beforeInputLabel}\n    <div role=\"none\" class=\"before-input\">{@html _sanitize(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 _sanitize(afterInputLabel)}</div>\n  {/if}\n{/snippet}\n\n{#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 && ['richtext', 'markdown', 'string', 'text', 'list', 'object'].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={updateResetAvailability}\n          onkeydown={updateResetAvailability}\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 ? resetAvailability : {}),\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      {#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    </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 _sanitize(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      input:is([type='color'], [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']) {\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        ) {\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","<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 {\n    /* eslint-disable prefer-const */\n    node,\n    selectedPath,\n    onSelectPath,\n    /* eslint-enable prefer-const */\n  } = $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';\n\n/**\n * @import { Entry, InternalCollection, InternalLocaleCode } from '$lib/types/private';\n */\n\n/**\n * A folder within a nested collection, 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 = path.slice(path.lastIndexOf('/') + 1);\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 nested collection.\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 * is not a nested collection 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 nested collection in the primary sidebar. Only folders are\n * included; the entries themselves are listed in the main area once a folder is 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 * is not a nested collection 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","<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 { getEntriesByCollection } from '$lib/services/contents/collection/entries';\n  import {\n    getEntryDirPath,\n    getMetaPathConfig,\n    getNestedConfig,\n    getSharedEntryFileName,\n  } from '$lib/services/contents/collection/nested';\n  import { localizeDirPath } from '$lib/services/contents/collection/nested/i18n';\n  import {\n    addFolderToTree,\n    findNestedTreeNode,\n    getMaxParentFolderDepth,\n    getParentFolderTree,\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  import { mergeUnpublishedEntries, unpublishedEntries } from '$lib/services/workflow';\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    /* eslint-enable prefer-const */\n  } = $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.by(() => {\n    const subPath = entryDraft.current?.originalEntry?.subPath;\n\n    if (\n      entryDraft.current?.isNew ||\n      !subPath ||\n      !collection ||\n      !getSharedEntryFileName(collection)\n    ) {\n      return undefined;\n    }\n\n    const dirPath = getEntryDirPath(subPath);\n\n    return dirPath ? dirPath.slice(dirPath.lastIndexOf('/') + 1) : undefined;\n  });\n\n  /* v8 ignore next -- the editor is only rendered for a nested collection, 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    const { name } = collection;\n\n    // With Editorial Workflow a section can be started and filled in one sitting: a page that only\n    // exists as a draft has to be offered as a parent too, or its sub-pages couldn’t be filed under\n    // it until it’s published. A pending move is reflected the same way, so the tree shows the\n    // folders as they’ll be once the drafts land\n    const entries = mergeUnpublishedEntries(\n      getEntriesByCollection(name),\n      unpublishedEntries.current.filter(({ workflow }) => workflow.collectionName === name),\n    );\n\n    return /** @type {NestedTreeNode} */ ({\n      path: '',\n      label: getCollectionLabel(collection),\n      children: newFolderPaths.reduce(\n        (nodes, path) => addFolderToTree({ nodes, path }),\n        getParentFolderTree({\n          collection,\n          entries,\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\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(\n    (selectedNode?.children ?? []).map(({ path }) => path.slice(path.lastIndexOf('/') + 1)),\n  );\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 {\n    /* eslint-disable prefer-const */\n    locale,\n    /* eslint-enable prefer-const */\n  } = $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","<!--\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 { escapeAttr } from '$lib/services/utils/string';\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   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    styleURLs,\n    children,\n    reactComponent,\n    reactProps,\n    /* eslint-enable prefer-const */\n  } = $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  /**\n   * Generate the HTML content for the iframe.\n   * @returns {string} The HTML string.\n   */\n  const generateHTML = () => `\n    <!DOCTYPE html>\n    <html lang=\"${escapeAttr(locale)}\">\n    <head>\n      <meta charset=\"UTF-8\">\n      <base href=\"${escapeAttr(window.location.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  /**\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 blobURL = URL.createObjectURL(new Blob([generateHTML()], { 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    };\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 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 { createElement } 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 } 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 * Create a field preview mounting function.\n * @param {object} args Arguments.\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 {Omit<GetFieldArgs, 'keyPath'>} args.getFieldArgs Arguments for getField function.\n * @returns {(target: HTMLElement, keyPath: FieldKeyPath) => Record<string, any>} Function that\n * mounts a field preview component.\n */\nexport const createFieldPreviewMounter =\n  ({ entryDraft, locale, getFieldArgs }) =>\n  /**\n   * Mount a Svelte component for field preview.\n   * @param {HTMLElement} target The DOM element to mount the Svelte component into.\n   * @param {FieldKeyPath} keyPath The key path of the field to preview.\n   * @returns {Record<string, any>} The mounted Svelte component instance.\n   */\n  (target, keyPath) =>\n    mount(FieldPreview, {\n      target,\n      context: createEntryDraftMountContext(entryDraft),\n      props: {\n        keyPath,\n        typedKeyPath: '',\n        locale,\n        fieldConfig: /** @type {Field} */ (getField({ ...getFieldArgs, keyPath })),\n        showLabel: false,\n      },\n    });\n\n/**\n * Create a widget preview function for React preview templates.\n * @param {(target: HTMLElement, keyPath: FieldKeyPath) => Record<string, any>} mountComponent\n * Function to mount Svelte components for field preview.\n * @returns {(keyPath: string) => ReactElement} Function that creates widget preview components.\n */\nexport const createWidgetFor =\n  (mountComponent) =>\n  /**\n   * Get a widget preview component for a field.\n   * @param {string} keyPath Field key path.\n   * @returns {ReactElement} Widget preview. It’s a React element that renders a Svelte component\n   * inside a div.\n   */\n  (keyPath) => {\n    /** @type {Record<string, any>} */\n    let component;\n\n    /**\n     * Mount or unmount the Svelte component when the div is added or removed from the DOM.\n     * @param {HTMLElement | null} div The div element to mount the Svelte component into.\n     */\n    const ref = (div) => {\n      if (div) {\n        component = mountComponent(div, keyPath);\n      } else if (component) {\n        unmount(component);\n      }\n    };\n\n    return createElement('div', { ref });\n  };\n\n/**\n * Create widgets map for an object value.\n * @param {Record<string, any>} obj Object value.\n * @param {string} basePath Base key path.\n * @param {(keyPath: string) => ReactElement} 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(Object.keys(obj).map((key) => [key, widgetFor(`${basePath}.${key}`)])),\n  );\n\n/**\n * Create a widgetsFor function.\n * @param {RawEntryContent} content Unflattened entry content.\n * @param {(keyPath: string) => ReactElement} widgetFor Function to create widget 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  // Create factory functions with bound dependencies\n  const mountFieldPreview = createFieldPreviewMounter({ entryDraft, locale, getFieldArgs });\n  const widgetFor = createWidgetFor(mountFieldPreview);\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 {\n    customPreviewStyleRegistry,\n    customPreviewTemplateRegistry,\n  } from '$lib/services/api/registries';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\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   */\n\n  const entryDraft = getEntryDraftContext();\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    locale,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const {\n    collectionName,\n    fileName,\n    fields = [],\n  } = $derived(/** @type {EntryDraft} */ (entryDraft.current ?? {}));\n  const styleURLs = $derived([...customPreviewStyleRegistry]);\n  const reactComponent = $derived(customPreviewTemplateRegistry.get(fileName ?? collectionName));\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\n          draft: {\n            ...entryDraft.current,\n            currentValues: $state.snapshot(entryDraft.current.currentValues),\n          },\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    <VisibilityObserver>\n      <FieldPreview\n        keyPath={fieldConfig.name}\n        typedKeyPath={fieldConfig.name}\n        {locale}\n        {fieldConfig}\n      />\n    </VisibilityObserver>\n  {/each}\n{/snippet}\n\n<VisibilityObserver>\n  {#if reactComponent && reactProps}\n    <EntryPreviewIframe {locale} {styleURLs} {reactComponent} {reactProps} />\n  {:else if styleURLs.length}\n    <EntryPreviewIframe {locale} {styleURLs} {children} />\n  {:else}\n    <div role=\"document\" aria-label={_('content_preview')}>\n      {@render children()}\n    </div>\n  {/if}\n</VisibilityObserver>\n\n<style>\n  div {\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","/**\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.targetOffsetTop Offset top of the matching field in the other pane.\n * @param {number} args.targetHeight Client 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, targetOffsetTop, targetHeight }) => {\n  const ratio = (y - top) / height;\n\n  if (ratio < 0 || ratio > 1) {\n    return undefined;\n  }\n\n  return targetOffsetTop - y + targetHeight * ratio;\n};\n","<script module>\n  /**\n   * Content area the user is scrolling, with the mouse wheel or a touch. Only its scroll events\n   * are synced to the other pane: the other pane’s own scroll events come from being synced, and\n   * syncing them back would make the panes chase each other.\n   * @type {HTMLElement | undefined}\n   */\n  let scrollSource;\n</script>\n\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, EmptyState } from '@sveltia/ui';\n  import { sleep } from '@sveltia/utils/misc';\n  import { untrack } from 'svelte';\n\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 {\n    customPreviewStyleRegistry,\n    customPreviewTemplateRegistry,\n  } from '$lib/services/api/registries';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { toggleLocale } from '$lib/services/contents/draft/update/locale';\n  import {\n    getFieldAlignedScrollTop,\n    getProportionalScrollTop,\n  } from '$lib/services/contents/editor/scroll';\n  import { entryEditorSettings } from '$lib/services/contents/editor/settings';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\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 {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    /* eslint-disable prefer-const */\n    id,\n    thisPane,\n    thisPaneContentArea = $bindable(),\n    thatPaneContentArea = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const { syncScrolling } = $derived(entryEditorSettings.current ?? {});\n  const locale = $derived(thisPane.current?.locale);\n  const mode = $derived(thisPane.current?.mode);\n  const hasContent = $derived(!!locale && !!entryDraft.current?.currentValues[locale]);\n  /* v8 ignore start -- only read for a disabled locale, which the pane always has */\n  const labelOptions = $derived({\n    values: { locale: locale ? (getLocaleLabel(locale) ?? locale) : '' },\n  });\n  /* v8 ignore stop */\n  const MainContent = $derived(mode === 'preview' ? EntryPreview : EntryEditor);\n\n  /** @type {HTMLElement | undefined} */\n  let contentArea = $state();\n\n  /**\n   * Sync the scroll position with the other edit/preview pane.\n   */\n  const syncScrollPosition = () => {\n    window.requestAnimationFrame(() => {\n      if (!syncScrolling || !contentArea || !thisPaneContentArea || !thatPaneContentArea) {\n        return;\n      }\n\n      const isIframe = thisPaneContentArea !== contentArea;\n      const { x, y } = isIframe ? { x: 0, y: 0 } : thisPaneContentArea.getBoundingClientRect();\n      const { ownerDocument, scrollTop, scrollHeight, clientHeight } = thisPaneContentArea;\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            targetOffsetTop: thatElement.offsetTop,\n            targetHeight: thatElement.clientHeight,\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 = thisPaneContentArea;\n  };\n\n  /**\n   * Sync the other pane once this pane has been scrolled by the user.\n   */\n  const onScroll = () => {\n    if (scrollSource === thisPaneContentArea) {\n      syncScrollPosition();\n    }\n  };\n\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  /** @type {AddEventListenerOptions} */\n  const eventOptions = { capture: true, passive: true };\n  /**\n   * Options for the scroll listener, which isn’t capturing: scroll events don’t bubble, and\n   * capturing would also get those of a field scrolled within the pane, e.g. a text area.\n   * @type {AddEventListenerOptions}\n   */\n  const scrollEventOptions = { passive: true };\n  /** Counter to ignore an outdated initialization once a newer one has started. */\n  let initCount = 0;\n\n  /**\n   * Find the preview iframe, which is used in the preview mode only when a custom preview\n   * stylesheet or template is provided. The preview is rendered lazily once it’s visible, so the\n   * iframe may not be in the DOM yet when the pane mode changes.\n   * @returns {Promise<HTMLIFrameElement | null>} Iframe, if any.\n   */\n  const findPreviewIframe = async () => {\n    for (let i = 0; i < 10; i += 1) {\n      const iframe = contentArea?.querySelector('iframe.preview');\n\n      if (iframe) {\n        return /** @type {HTMLIFrameElement} */ (iframe);\n      }\n\n      // eslint-disable-next-line no-await-in-loop\n      await sleep(50);\n    }\n\n    return null;\n  };\n\n  /**\n   * Initialize the scroll synchronization by setting up event listeners and ensuring the content\n   * area is ready. The content area is either the main content area or the iframe’s content area.\n   * An iframe is used only when a custom preview stylesheet is provided.\n   */\n  const initializeScrollSync = async () => {\n    if (!contentArea) {\n      return;\n    }\n\n    initCount += 1;\n\n    const currentCount = initCount;\n\n    if (thisPaneContentArea) {\n      // Remove previous event listeners if they exist\n      thisPaneContentArea.removeEventListener('wheel', markScrollSource, eventOptions);\n      thisPaneContentArea.removeEventListener('touchstart', markScrollSource, eventOptions);\n      scrollEventTarget?.removeEventListener('scroll', onScroll, scrollEventOptions);\n    }\n\n    // The preview is only rendered in an iframe with a custom preview stylesheet or template. Don’t\n    // wait for one otherwise, as the other pane can’t follow this one until it’s set up\n    const iframe =\n      mode === 'preview' && (customPreviewStyleRegistry.size || customPreviewTemplateRegistry.size)\n        ? await findPreviewIframe()\n        : null;\n\n    if (iframe) {\n      // Wait for the content to be loaded in the iframe\n      await sleep(250);\n    }\n\n    if (currentCount !== initCount) {\n      // The mode has changed in the meantime, and a newer initialization has taken over\n      return;\n    }\n\n    if (iframe) {\n      thisPaneContentArea = /** @type {HTMLElement} */ (iframe.contentDocument?.firstElementChild);\n    } else {\n      thisPaneContentArea = contentArea;\n    }\n\n    // A preview frame removed while its content was loading has no document left to listen to\n    /* v8 ignore next 3 -- a test can’t detach the frame within that moment */\n    if (!thisPaneContentArea) {\n      return;\n    }\n\n    scrollEventTarget = iframe ? thisPaneContentArea.ownerDocument : thisPaneContentArea;\n    thisPaneContentArea.scrollTop = 0;\n    // Add event listeners manually to use passive mode\n    thisPaneContentArea.addEventListener('wheel', markScrollSource, eventOptions);\n    thisPaneContentArea.addEventListener('touchstart', markScrollSource, eventOptions);\n    scrollEventTarget.addEventListener('scroll', onScroll, scrollEventOptions);\n  };\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    // may use an iframe if a custom preview stylesheet is provided.\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(() => initializeScrollSync());\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    if (scrollSource === thisPaneContentArea) {\n      scrollSource = undefined;\n    }\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}>\n      <MainContent {locale} />\n    </div>\n  {:else if mode === 'edit'}\n    <EmptyState>\n      <span role=\"alert\">\n        {_(hasContent ? 'locale_x_now_disabled' : 'locale_x_has_been_disabled', labelOptions)}\n      </span>\n      <Button\n        variant=\"tertiary\"\n        label={_(hasContent ? 'reenable_x_locale' : 'enable_x_locale', labelOptions)}\n        onclick={() => {\n          /* v8 ignore next 3 -- the button is only offered for a disabled locale */\n          if (locale && entryDraft.current) {\n            toggleLocale({ draft: entryDraft.current, locale });\n          }\n        }}\n      />\n    </EmptyState>\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 {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    action,\n    locale = undefined,\n    onClose = undefined,\n    /* eslint-enable prefer-const */\n  } = $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 {\n    /* eslint-disable prefer-const */\n    thisPane,\n    /* eslint-enable prefer-const */\n  } = $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 { 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   * 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    /* eslint-disable prefer-const */\n    entry,\n    locale,\n    collection,\n    collectionFile,\n    pullRequest,\n    as = 'button',\n    variant = 'ghost',\n    size = 'medium',\n    iconic = false,\n    /* eslint-enable prefer-const */\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\n  const description = $derived(\n    state === 'error'\n      ? _('deploy_preview.failed')\n      : state === 'checking'\n        ? _('deploy_preview.checking')\n        : state === 'pending'\n          ? _('deploy_preview.building')\n          : undefined,\n  );\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    // Neither of these reads the liveness store this effect writes, so the check can’t retrigger\n    // itself however the URL is composed\n    const canPing = pingable;\n    const pageURL = url;\n\n    if (canPing && pageURL) {\n      pingURL(pageURL);\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 panes so that the default locale is always shown in the first pane\n    (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 * current or default locale, and the second one holds the preview, or another locale when there’s\n * no preview to show, or nothing at all when there’s no room for it.\n * @param {object} args Arguments.\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  currentLocale,\n  defaultLocale,\n  allLocales,\n  i18nEnabled,\n  canPreview,\n  showPreview,\n  showSecondPane,\n  singlePane,\n}) => {\n  const locale = currentLocale ?? defaultLocale;\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 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 { 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   * @import { ResetAction } from '$lib/services/contents/editor/reset';\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 {\n    /* eslint-disable prefer-const */\n    id,\n    thisPane,\n    thatPane = createRawState(null),\n    /* eslint-enable prefer-const */\n  } = $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  /**\n   * Whether restoring the default values or clearing the fields would change anything. It takes\n   * going through the whole locale, so it’s only checked as the menu opens rather than on every\n   * change.\n   */\n  let resetAvailability = $state({ restore: false, clear: false });\n  /** @type {ResetAction} */\n  let resetAction = $state('revert');\n  let showResetDialog = $state(false);\n  /** @type {MenuButton | undefined} */\n  let menuButton = $state();\n\n  /**\n   * Check whether restoring the default values or clearing the fields would change anything.\n   */\n  const updateResetAvailability = () => {\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;\n    }\n\n    resetAvailability = {\n      restore: canResetEntry({ draft, locale, restore: true }),\n      clear: canResetEntry({ draft, locale }),\n    };\n  };\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  // 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}\n      <LocaleSwitcher {id} {thisPane} {thatPane} />\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={updateResetAvailability}\n          onkeydown={updateResetAvailability}\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, ...resetAvailability }}\n                  onSelect={(action) => {\n                    resetAction = action;\n                    showResetDialog = true;\n                  }}\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                {#if prefs.devModeEnabled}\n                  <MenuItem\n                    disabled={!backend.current?.repository?.blobBaseURL}\n                    label={backend.current?.repository?.label\n                      ? _('view_on_x', { values: { service: backend.current.repository.label } })\n                      : _('view_in_repository')}\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              {/if}\n            </Menu>\n          {/snippet}\n        </MenuButton>\n      {/if}\n    {/if}\n  </Toolbar>\n</div>\n\n<ResetDialog\n  bind:open={showResetDialog}\n  action={resetAction}\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","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 { 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 draft’s original entry with the one in the store to tell whether the entry has been\n * 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  const current = allEntries.current.find(({ id }) => id === originalEntry.id);\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. A 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 * 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 = commitAuthor?.name || commitAuthor?.login || commitAuthor?.email;\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 { checkForRemoteChanges, MIN_CHECK_GAP } from '$lib/services/backends/refresh';\nimport { isDraftModified } from '$lib/services/contents/draft';\nimport { deleteBackup, getBackup, getBackupSlug } 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  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 } 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</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\n        variant=\"link\"\n        label={_('remote_change.reload_entry')}\n        onclick={() => {\n          // Nothing to lose unless the user has edited the entry\n          if (isDraftModified(draft)) {\n            showReloadDialog = true;\n          } else {\n            reload();\n          }\n        }}\n      />\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","<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 {\n    /* eslint-disable prefer-const */\n    title,\n    actions = undefined,\n    children = undefined,\n    /* eslint-enable prefer-const */\n  } = $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 { 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 {\n  getEntryRelationValues,\n  getReferencingRelationFields,\n  getRelationValues,\n} from '$lib/services/contents/entry/relations';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\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 =\n            sourceEntry.locales[locale]?.content ?? Object.values(sourceEntry.locales)[0]?.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            fieldLabel: fieldConfig.label || fieldConfig.name,\n            entry: sourceEntry,\n            summary: getEntrySummary(sourceCollection, sourceEntry),\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 { encodeRoutePath, goto } from '$lib/services/app/navigation';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\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(\n                encodeRoutePath(`/collections/${ref.collectionName}/entries/${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 { getEntryPaths } from '$lib/services/contents/entry/paths';\n\n/**\n * @import { Entry, FileCommit } from '$lib/types/private';\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 * @returns {Promise<EntryHistory>} The commit history result.\n */\nexport const fetchEntryHistory = async (entry) => {\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 = getEntryPaths(entry);\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 { onMount } from 'svelte';\n\n  import PanelContainer from '$lib/components/contents/details/sidebar/panels/panel-container.svelte';\n  import { backend } from '$lib/services/backends';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { fetchEntryHistory } from '$lib/services/contents/entry/history';\n  import { formatDate } from '$lib/services/utils/date';\n  import { openNewTab } from '$lib/services/utils/window';\n\n  /**\n   * @import { 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   * Load the commit history for the current entry, using the external cache.\n   */\n  const load = async () => {\n    const entry = entryDraft.current?.originalEntry;\n\n    /* v8 ignore next 3 -- the panel is only offered for an existing entry */\n    if (!entry) {\n      return;\n    }\n\n    loading = true;\n    ({ commits, error } = await fetchEntryHistory(entry));\n    loading = false;\n  };\n\n  onMount(() => {\n    load();\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        <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            {#if commit.authorAvatarURL}\n              <img\n                class=\"avatar\"\n                src={commit.authorAvatarURL}\n                alt=\"\"\n                width=\"24\"\n                height=\"24\"\n                loading=\"lazy\"\n              />\n            {:else}\n              <span class=\"avatar placeholder\" aria-hidden=\"true\"></span>\n            {/if}\n            <span class=\"details\">\n              <span class=\"author\"><bdi>{commit.authorName}</bdi></span>\n              <span class=\"date\">{formatDate(commit.date, appLocale.current)}</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  .avatar {\n    flex: none;\n    width: 24px;\n    height: 24px;\n    border-radius: 50%;\n    background-color: var(--sui-secondary-background-color);\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  .author {\n    overflow: hidden;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n  }\n\n  .date {\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 {\n    /* eslint-disable prefer-const */\n    label,\n    showLabel = true,\n    children,\n    /* eslint-enable prefer-const */\n  } = $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","<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 { validateNewFolderName } from '$lib/services/common/slug';\n  import { getFolderName } from '$lib/services/contents/collection/nested/i18n';\n  import { getSlugOptions } from '$lib/services/contents/collection/slug';\n  import { hasLocalizedSlugs } from '$lib/services/contents/draft/slugs';\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 {\n    getOwnFolderPaths,\n    getTakenFolderNames,\n    renameEntryFolders,\n    updateSlugs,\n  } from '$lib/services/contents/editor/slug';\n  import { getLocaleLabel } from '$lib/services/contents/i18n';\n\n  /**\n   * @import { EntryDraft, InternalLocaleCode } from '$lib/types/private';\n   */\n\n  /**\n   * @typedef {object} Row\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  const entryDraft = getEntryDraftContext();\n\n  // The form is only rendered while the draft is there\n  const draft = $derived(/** @type {EntryDraft} */ (entryDraft.current));\n  const { currentSlugs } = $derived(draft);\n  /**\n   * The collection’s `pattern` slug option. The slug can only be edited in an entry collection.\n   */\n  const { pattern } = $derived(getSlugOptions(draft.collection));\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   * Whether each locale has a folder of its own, which is the case when the slugs are localized, as\n   * the folder is named after the slug. Otherwise, the folder is shared by every locale.\n   * @see https://github.com/sveltia/sveltia-cms/issues/962\n   */\n  const localized = $derived(hasLocalizedSlugs(draft.collection));\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   * 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  /**\n   * Values to edit: the entry’s folder names or slugs. A locale the entry has no file for has no\n   * slug to rename.\n   * @type {Row[]}\n   */\n  const rows = $derived(\n    ownFolderPaths\n      ? Object.entries(ownFolderPaths).map(([locale, dirPath]) => ({\n          locale,\n          ...getLabel(locale),\n          value: getFolderName(dirPath),\n        }))\n      : Object.entries(currentSlugs)\n          .filter(([, slug]) => slug !== undefined)\n          .map(([locale, slug]) => ({\n            locale,\n            ...getLabel(locale),\n            value: /** @type {string} */ (slug),\n          })),\n  );\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    const text = texts[locale];\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 error = validateSlug({ slug: text, pattern, takenSlugs: takenSlugs[locale], locale });\n\n    return error ? getSlugValidationMessage({ error, pattern }) : undefined;\n  };\n\n  /**\n   * Apply the edited value of the given locale to the draft. It’s saved along with the entry.\n   * @param {Row} 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 } from '$lib/services/contents/collection/slug';\n  import { hasLocalizedSlugs } from '$lib/services/contents/draft/slugs';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { canUpdateSlug, getSlugPreviews, hasEntrySlug } 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, in the enabled locales: the ones a new entry would be saved with if\n   * it was saved now, or an existing entry’s current slugs. A locale-agnostic slug is under the `_`\n   * key.\n   */\n  const readonlySlugs = $derived(\n    /** @type {[string, string][]} */ (\n      Object.entries(draft?.isNew ? getSlugPreviews(draft) : (draft?.currentSlugs ?? {})).filter(\n        ([locale, slug]) =>\n          slug !== undefined && (locale === '_' || !!draft?.currentLocales[locale]),\n      )\n    ),\n  );\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] (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          {/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  .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 { backend } from '$lib/services/backends';\nimport { entryEditorSettings } from '$lib/services/contents/editor/settings';\nimport { hasEntrySlug } from '$lib/services/contents/editor/slug';\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`.\n * @property {string} icon Material icon name.\n * @property {boolean} disabled Whether the panel is unavailable for the draft.\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    {\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 {\n    /* eslint-disable prefer-const */\n    onSelectField = highlightEditorField,\n    /* eslint-enable prefer-const */\n  } = $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\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 {\n    /* eslint-disable prefer-const */\n    key,\n    onSelectField = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\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}\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 { _ } from '@sveltia/i18n';\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 { 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 ? _(`entry_sidebar.${key}.title`) : ''}\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 { 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  /** The displayed panel, falling back to Validation if the saved panel is unknown. */\n  const activeKey = $derived(\n    draftPanelKey ??\n      (savedKey ? (panels.find((p) => p.key === savedKey)?.key ?? 'validation') : 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 { key, icon, disabled } (key)}\n      <SelectButton\n        iconic\n        aria-label={_(`entry_sidebar.${key}.title`)}\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        <Icon name={icon} />\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  .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  const showSecondPane = $derived(entryEditorSettings.current?.showSecondPane ?? true);\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 canShowSecondPane = $derived((i18nEnabled && allLocales.length > 1) || canPreview);\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={!canShowSecondPane}\n  onChange={() => {\n    toggleEntryEditorSetting('showSecondPane', true);\n  }}\n/>\n<!-- The preview is rendered in the second pane, so it’s unavailable while hidden -->\n<MenuItemCheckbox\n  label={_('show_preview')}\n  checked={entryEditorSettings.current?.showPreview}\n  disabled={!showSecondPane || !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  ITEM_INDEX_SUFFIX_REGEX,\n} from '$lib/services/contents/entry/cascade';\nimport { createSyntheticDraft } from '$lib/services/contents/entry/changes';\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 {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    discardsDraft,\n    useWorkflow,\n    withAssets,\n    onOk,\n    onClose,\n    /* eslint-enable prefer-const */\n  } = $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 { saveChanges } from '$lib/services/backends/save';\nimport {\n  contentUpdatesToast,\n  UPDATE_TOAST_DEFAULT_STATE,\n} from '$lib/services/contents/collection/data';\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 { 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';\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\n    if (Number(entry.locales[defaultLocale]?.content?.[orderKey]) !== 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  const { changes, savingEntries } = isArrayFileCollection(collection)\n    ? buildArrayFileReorderChanges(collection, orderedEntries)\n    : await buildReorderChanges(collection, orderedEntries);\n\n  if (!changes.length) {\n    return 0;\n  }\n\n  await saveChanges({\n    changes,\n    savingEntries,\n    options: { commitType: 'update', collection },\n  });\n\n  contentUpdatesToast.current = {\n    ...UPDATE_TOAST_DEFAULT_STATE,\n    saved: true,\n    count: savingEntries.length,\n  };\n\n  return savingEntries.length;\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 { 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 { 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","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';\nimport { getPathInfo } from '@sveltia/utils/file';\n\nimport { isInCmsFolder } from '$lib/services/assets/reserved';\nimport { getErrorMessage } from '$lib/services/backends/git/shared/errors';\nimport { createFileList } from '$lib/services/backends/process';\nimport { 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 {\n  getEntryDirPath,\n  getNestedConfig,\n  isDescendantPath,\n} from '$lib/services/contents/collection/nested';\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 { unpublishedEntries } from '$lib/services/workflow';\n\n/**\n * @import {\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([\n    { path, name: getPathInfo(path).basename, sha: '', size: 0 },\n  ]);\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 paths below the given entry’s folder in a nested collection with subfolders, which moving\n * the entry moves along with it. An entry at the top of the collection has no folder of its own,\n * and nothing can be moved with it.\n * @param {InternalCollection | undefined} collection Collection.\n * @param {Entry} entry Entry as it stands on the configured branch.\n * @returns {string[]} Paths of the descendant entries, as they stand on the configured branch.\n */\nconst getDescendantPaths = (collection, entry) => {\n  if (!collection || !getNestedConfig(collection)?.subfolders) {\n    return [];\n  }\n\n  const dirPath = getEntryDirPath(entry.subPath);\n\n  if (!dirPath) {\n    return [];\n  }\n\n  return getEntriesByCollection(collection.name)\n    .filter((e) => e.id !== entry.id && isDescendantPath(dirPath, e.subPath))\n    .flatMap((e) => getEntryPaths(e));\n};\n\n/**\n * Get the folders below which the given entry’s descendants land once it has moved, which are the\n * folders of its own files in a nested collection with subfolders.\n * @param {InternalCollection | undefined} collection Collection.\n * @param {Entry} entry Entry as it stands on the pull request’s branch.\n * @returns {string[]} Folder paths, each with a trailing slash.\n */\nconst getDescendantFolders = (collection, entry) => {\n  if (!collection || !getNestedConfig(collection)?.subfolders || !getEntryDirPath(entry.subPath)) {\n    return [];\n  }\n\n  return getEntryPaths(entry).map((path) => path.slice(0, path.lastIndexOf('/') + 1));\n};\n\n/**\n * Get the paths of the entries whose references to the given entry the CMS rewrites along with it:\n * those referencing its published version when it’s renamed, or when it’s deleted. A selection of\n * entries is deleted with the same rewrite in each pull request, so the references to the other\n * entries of the collection awaiting deletion count as well. 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 | 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 * @returns {string[]} Paths.\n */\nconst getReferencingPaths = ({ entry, collection, updatedEntry, deletion }) => {\n  const { collectionName, fileName } = entry.workflow;\n\n  if (!collection) {\n    return [];\n  }\n\n  const collectionFile = fileName ? getCollectionFile(collection, fileName) : undefined;\n\n  const targets = deletion\n    ? planCascadeDelete({\n        collection,\n        collectionFile,\n        entries: [\n          entry,\n          ...unpublishedEntries.current.filter(\n            (e) =>\n              e !== entry &&\n              e.workflow.status === 'pending_deletion' &&\n              e.workflow.collectionName === collectionName &&\n              e.workflow.fileName === fileName,\n          ),\n        ],\n      }).targets\n    : collectRenameTargets({\n        collection,\n        collectionFile,\n        originalEntry: updatedEntry,\n        savingEntry: entry,\n      });\n\n  return targets.flatMap((target) => getEntryPaths(target.entry));\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 — would otherwise go live without having been seen.\n * What the CMS itself commits along with an entry is allowed: the entry’s own files, and those of\n * its published version, which a rename removes; assets, which go with the entry and are listed as\n * its unpublished assets, and are only removed when the entry is moved or deleted, except for any\n * file in an `admin` or `cms` folder, where the CMS itself is served from; when the entry\n * is renamed or deleted, the entries referencing it, which are rewritten; and, in a nested\n * collection with subfolders, the entries below the folder of an entry being moved, which move\n * along with it. A Relation field doesn’t offer to add an entry while an entry is saved through\n * Editorial Workflow, so no other new entry is expected.\n * @param {UnpublishedEntry} entry Unpublished entry being published.\n * @param {WorkflowChangedFile[]} files Files the pull request changes.\n * @returns {string[]} Paths of the files that aren’t accounted for.\n */\nexport const findUnexpectedChanges = (entry, files) => {\n  const { collectionName } = 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  // 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\n  const descendantPaths = new Set(\n    moved ? getDescendantPaths(collection, /** @type {Entry} */ (updatedEntry)) : [],\n  );\n\n  const descendantFolders = moved ? getDescendantFolders(collection, entry) : [];\n\n  const referencingPaths = new Set(\n    getReferencingPaths({ entry, collection, updatedEntry, deletion }),\n  );\n\n  /**\n   * Check whether the given change is one the CMS makes along with the entry.\n   * @param {PathChange} pathChange Path change.\n   * @returns {boolean} Result.\n   */\n  const isExpected = ({ path, change, mode }) => {\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    const kind = classifyPath(path);\n\n    if (!kind) {\n      return false;\n    }\n\n    // An asset is only removed along with the entry it sits beside, or moved away with it. Nothing\n    // in the folder the CMS is served from is an asset of an entry, whatever the change\n    if (kind.type === 'asset') {\n      return !isInCmsFolder(path) && (change !== 'removed' || deletion || moved);\n    }\n\n    const sameCollection = kind.collectionName === collectionName;\n\n    if (change === 'removed') {\n      return sameCollection && descendantPaths.has(path);\n    }\n\n    if (change === 'added') {\n      return sameCollection && descendantFolders.some((folder) => path.startsWith(folder));\n    }\n\n    return referencingPaths.has(path) || (sameCollection && descendantPaths.has(path));\n  };\n\n  return [\n    ...new Set(\n      getPathChanges(files)\n        .filter((pathChange) => !isExpected(pathChange))\n        .map(({ path }) => path),\n    ),\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 = 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 * 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';\n\nimport { callEventHooks } from '$lib/services/api/events';\nimport { backend } from '$lib/services/backends';\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 { toRepoChanges } from '$lib/services/backends/root-dir';\nimport { getCommitAuthor } from '$lib/services/backends/save';\nimport { allEntries } from '$lib/services/contents';\nimport { getCollection } from '$lib/services/contents/collection';\nimport { getCollectionFile } from '$lib/services/contents/collection/files';\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 {\n  getUnpublishedEntryByBranch,\n  getUnpublishedEntryBySlug,\n  publishingBranches,\n  unpublishedEntries,\n} from '$lib/services/workflow';\nimport {\n  mergeWorkflowAssets,\n  publishWorkflowAssets,\n  removeWorkflowAssets,\n} from '$lib/services/workflow/assets';\nimport { getBranchName } from '$lib/services/workflow/branch';\nimport { trackDeployingEntry } from '$lib/services/workflow/deploy';\nimport { isEntryAlreadyPublished, openAuthoring } from '$lib/services/workflow/open-authoring';\nimport { verifyMergeState } from '$lib/services/workflow/verify';\n\n/**\n * @import {\n * Asset,\n * CascadeTarget,\n * ChangeResults,\n * Entry,\n * FileChange,\n * CommitOptions,\n * InternalCollection,\n * InternalCollectionFile,\n * UnpublishedEntry,\n * WorkflowBackendService,\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 * 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 */\nconst resolveWorkflowBranch = ({ collectionName, slug, entry }) => {\n  const currentBranch = /** @type {UnpublishedEntry | undefined} */ (entry)?.workflow?.pullRequest\n    .branch;\n\n  const existingEntry =\n    (currentBranch ? getUnpublishedEntryByBranch(currentBranch) : undefined) ??\n    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 * Replace or append the given unpublished entry in the {@link unpublishedEntries} store, keyed by\n * the workflow branch name. An existing entry is replaced in place, so a status change doesn’t make\n * 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 = unpublishedEntries.current;\n  const index = entries.findIndex((e) => e.workflow.pullRequest.branch === branch);\n\n  unpublishedEntries.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  unpublishedEntries.current = unpublishedEntries.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 unpublishedEntries} 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 * @returns {UnpublishedEntry} Unpublished entry.\n */\nconst storeUnpublishedEntry = (entry, { pullRequest, collectionName, fileName, previousPaths }) => {\n  /** @type {UnpublishedEntry} */\n  const unpublishedEntry = {\n    ...entry,\n    workflow: { pullRequest, status: pullRequest.status, collectionName, fileName, previousPaths },\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 {@link unpublishedEntries}\n * store, settle the assets committed to its branch, and forget the 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 * 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 */\nconst settlePublishedEntry = (entry, { deletion = false, cascadedEntries = new Map() } = {}) => {\n  const { workflow, ...publishedEntry } = entry;\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(getEntryPaths(entry, { includePrevious: true }));\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];\n\n  clearUnpublishedEntry(workflow.pullRequest, publishWorkflowAssets);\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 * @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}) => {\n  const workflow = getWorkflowService();\n\n  const { existingEntry, branch } = resolveWorkflowBranch({\n    collectionName,\n    slug,\n    entry: originalEntry,\n  });\n\n  const { commit, pullRequest } = await workflow.savePullRequest({\n    changes,\n    options,\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), options),\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: { ...pullRequest, headSHA: commit.sha },\n      collectionName,\n      fileName,\n      previousPaths,\n    },\n  );\n\n  mergeWorkflowAssets(savedAssets);\n\n  return {\n    commit: { ...commit, author: commitAuthor },\n    savedEntries: [unpublishedEntry],\n    savedAssets,\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.\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  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 */\nconst mergeWorkflowEntry = async (entry) => {\n  const workflow = getWorkflowService();\n  const { pullRequest, status } = entry.workflow;\n  const deletion = status === 'pending_deletion';\n  const hookArgs = getEventHookArgs(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  // 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  await verifyMergeState(\n    entry,\n    await workflow.fetchMergeState(pullRequest),\n    workflow.fetchUnchangedPaths,\n  );\n\n  if (hookArgs) {\n    await callEventHooks({ ...hookArgs, type: preType });\n  }\n\n  await workflow.publish(pullRequest);\n\n  // A removal also rewrote the entries referencing the deleted one, so the store is brought up to\n  // date with those as well, or they would show the stale references until the next reload. The\n  // references are worked out again rather than remembered from when the pull request was opened,\n  // because the entries may have been reloaded since; this has to happen while the deleted entry\n  // is still in the store, as it’s what the 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: [entry],\n        }).targets.map(({ entry: target }) => [target.id, target])\n      : [],\n  );\n\n  settlePublishedEntry(entry, { deletion, cascadedEntries });\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\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  const pending = pendingPublishes.get(branch);\n\n  if (pending) {\n    return pending;\n  }\n\n  const promise = mergeWorkflowEntry(entry).finally(() => {\n    pendingPublishes.delete(branch);\n    publishingBranches.current = publishingBranches.current.filter((b) => b !== branch);\n  });\n\n  pendingPublishes.set(branch, promise);\n  publishingBranches.current = [...publishingBranches.current, branch];\n\n  return promise;\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\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 * @returns {Promise<UnpublishedEntry>} Entry with the pull request attached.\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 * @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 } = {},\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  // 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  // 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  // 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\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  const { commit, pullRequest } = await workflow.savePullRequest({\n    changes: [\n      ...[...paths, ...assetPaths].map(\n        (path) => /** @type {FileChange} */ ({ action: 'delete', slug, path }),\n      ),\n      ...cascadeChanges,\n    ],\n    options: { commitType: 'delete', collection },\n    branch,\n    title: createCommitMessage(toRepoChanges([{ action: 'delete', slug, path: paths[0] }]), {\n      commitType: 'delete',\n      collection,\n    }),\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  });\n\n  // A reused pull request keeps the status it already had, so it still needs the switch. It also\n  // carries the head commit from before this one, which publishing compares with the branch, so\n  // it’s pointed at the new commit\n  const readyPullRequest = {\n    ...(pullRequest.status === 'pending_deletion'\n      ? pullRequest\n      : await workflow.updateStatus(pullRequest, 'pending_deletion')),\n    headSHA: commit.sha,\n  };\n\n  return storeUnpublishedEntry(entry, {\n    pullRequest: readyPullRequest,\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: getPreviousPaths(existingEntry, paths),\n  });\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.\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, CascadeTarget[]>} */\n  const targetMap = new Map();\n\n  groups.forEach((group, key) => {\n    const [{ collection, collectionFile }] = group;\n\n    targetMap.set(\n      key,\n      planCascadeDeleteOrThrow(\n        { collection, collectionFile, entries: group.map(({ entry }) => entry) },\n        'Cannot delete entries that other entries require',\n      ),\n    );\n  });\n\n  await runConcurrently(items, async (item) => {\n    const { entry, collection, collectionFile, assets } = item;\n\n    await deleteWorkflowEntry(entry, collection, collectionFile, assets, {\n      targets: targetMap.get(getKey(item)),\n    });\n  });\n};\n","import { deleteEntries } from '$lib/services/contents/collection/data/delete';\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 * 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  if (drafts.length) {\n    await discardWorkflowEntries(drafts);\n  }\n\n  if (items.length) {\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\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      items.map(({ entry }) => entry),\n      items.flatMap(({ assets }) => assets),\n    );\n\n    return undefined;\n  }\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 { 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 { 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.\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  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\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    /* eslint-enable prefer-const */\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    /** @type {Partial<UpdateToastState> | undefined} */\n    let toastState;\n\n    progressMessage = progressKey;\n    deleting = true;\n\n    try {\n      toastState = await action();\n    } catch (/** @type {any} */ ex) {\n      deleteErrorMessage = getErrorMessage(ex, 'deleting_entry_failed');\n      showDeleteErrorToast = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n\n      return;\n    } finally {\n      deleting = false;\n    }\n\n    if (toastState) {\n      contentUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, count: 1, ...toastState };\n    }\n\n    onDone();\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 {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    conflict,\n    onOverwrite,\n    onClose,\n    /* eslint-enable prefer-const */\n  } = $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","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';\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","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.\n-->\n<script>\n  import { _ } from '@sveltia/i18n';\n  import { Alert, Menu, MenuButton, MenuItemRadio, Toast } from '@sveltia/ui';\n\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 { handleEntryAlreadyPublished } from '$lib/services/workflow/editor';\n  import { workflowStages } from '$lib/services/workflow/open-authoring';\n  import { updateWorkflowStatus } from '$lib/services/workflow/save';\n  import { canMoveToStatus } from '$lib/services/workflow/validate';\n  import { getWorkflowErrorMessage } from '$lib/services/workflow/verify';\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 {\n    /* eslint-disable prefer-const */\n    entry,\n    disabled = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  let updating = $state(false);\n  let showErrorToast = $state(false);\n  let errorMessage = $state('');\n  let showValidationToast = $state(false);\n\n  const status = $derived(entry.workflow.status);\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    // An entry can be saved as a draft with its required fields left empty, so it has to be checked\n    // before it moves towards being published\n    if (!canMoveToStatus({ entry, status: newStatus, draft: entryDraft.current })) {\n      showValidationToast = true;\n\n      return;\n    }\n\n    updating = true;\n\n    // Read these up front: an entry that turns out to have been published leaves\n    // `unpublishedEntries`, and the `entry` prop is derived from that store\n    const { collectionName, pullRequest } = entry.workflow;\n\n    try {\n      await updateWorkflowStatus(entry, newStatus);\n    } catch (/** @type {any} */ ex) {\n      // An entry published since it was opened closes the editor instead\n      if (\n        !handleEntryAlreadyPublished(ex, { entryDraft, branch: pullRequest.branch, collectionName })\n      ) {\n        errorMessage = getWorkflowErrorMessage(ex, 'workflow.status_change_failed');\n        showErrorToast = true;\n        // eslint-disable-next-line no-console\n        console.error(ex);\n      }\n    } finally {\n      updating = false;\n    }\n  };\n</script>\n\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      {#each workflowStages.current 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    </Menu>\n  {/snippet}\n</MenuButton>\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  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 { getCollection } from '$lib/services/contents/collection';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { isPublishAllowed, publishingBranches } from '$lib/services/workflow';\n  import { getPublishDialogStrings } from '$lib/services/workflow/dialogs';\n  import { closeWorkflowEntryEditor } from '$lib/services/workflow/editor';\n  import { publishWorkflowEntry } from '$lib/services/workflow/save';\n  import { canPublish } from '$lib/services/workflow/validate';\n  import { getWorkflowErrorMessage } from '$lib/services/workflow/verify';\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 {\n    /* eslint-disable prefer-const */\n    entry,\n    disabled = false,\n    modified = false,\n    /* eslint-enable prefer-const */\n  } = $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\n  const visible = $derived(isPublishAllowed(entry, getCollection(entry.workflow.collectionName)));\n\n  /**\n   * Publish the entry by merging the pull request, then go back to the entry list.\n   */\n  const publish = async () => {\n    // An entry can be saved as a draft with its required fields left empty, so it’s checked first\n    if (!canPublish({ entry, draft: entryDraft.current })) {\n      showValidationToast = true;\n\n      return;\n    }\n\n    // Read these up front: publishing takes the entry out of `unpublishedEntries`, and the `entry`\n    // prop is derived from that store, so it’s `undefined` once the merge resolves\n    const { collectionName, pullRequest } = entry.workflow;\n\n    try {\n      await publishWorkflowEntry(entry);\n      closeWorkflowEntryEditor({ entryDraft, branch: pullRequest.branch, collectionName });\n    } catch (/** @type {any} */ ex) {\n      errorMessage = getWorkflowErrorMessage(ex, 'workflow.publishing_entry_failed');\n      showErrorToast = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    }\n  };\n</script>\n\n{#if visible}\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{/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 { getDateTimeParts } from '@sveltia/utils/datetime';\n\nimport {\n  DATE_TIME_FIELDS,\n  TEMPLATE_TAG_REGEX,\n  TEMPLATE_TAG_REPLACE_REGEX,\n} from '$lib/services/common/template/constants';\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 { 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 */\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' && TEMPLATE_TAG_REGEX.test(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' || !TEMPLATE_TAG_REGEX.test(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 * @returns {Date | undefined} Date, or `undefined` if the value can’t be parsed.\n */\nconst toDate = (value, dateFieldConfig) => {\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);\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 * @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 }) => {\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);\n    const targetDate = toDate(target, dateFieldConfig);\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 * @returns {PreparedConditions} Prepared conditions.\n */\nexport const prepareConditions = (conditions, { dateFieldConfig, now = new Date() } = {}) => {\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) };\n    }\n\n    return { operator, target };\n  });\n\n  return { pattern, regex: getRegex(pattern), comparisons, dateFieldConfig };\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 } = 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 });\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 { getField } from '$lib/services/contents/entry/fields';\nimport { getPropertyValue } from '$lib/services/contents/entry/values';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { Entry, FilteringConditions, InternalEntryCollection } from '$lib/types/private';\n * @import { DateTimeField, ViewFilter, ViewFilters } 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 * 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  // Resolve the template tags and compile the regexes once per filter instead of for every entry\n  const preparedFilters = validFilters.map((conditions) => {\n    const fieldConfig = getField({ collectionName, keyPath: conditions.field });\n\n    const dateFieldConfig =\n      fieldConfig?.widget === 'datetime' ? /** @type {DateTimeField} */ (fieldConfig) : undefined;\n\n    return {\n      field: conditions.field,\n      conditions: prepareConditions(conditions, { dateFieldConfig, now }),\n    };\n  });\n\n  return entries.filter((entry) =>\n    preparedFilters.every(({ field, conditions }) => {\n      // Check both the raw value and referenced value\n      const args = { entry, locale, collectionName, key: field };\n      const rawValue = getPropertyValue({ ...args, resolveRef: false });\n      const refValue = getPropertyValue({ ...args });\n\n      return matchesConditions({ rawValue, refValue, conditions });\n    }),\n  );\n};\n\n/**\n * View filters for the selected entry collection.\n * @type {{ readonly current: ViewFilter[] }}\n */\nexport const viewFilters = createDerivedState(() => {\n  const collection = selectedCollection.current;\n\n  // Disable filters for file/singleton collection\n  if (collection?._type !== 'entry') {\n    return [];\n  }\n\n  return parseFilterConfig(collection.view_filters).options;\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 { createRawState, createRootEffect } from '$lib/services/utils/state.svelte';\n\n/**\n * @import { BackendService, EntryListView } 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.\n * @type {{ current: EntryListView }}\n */\nexport const currentView = createRawState({ type: 'list' });\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 * 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","import {\n  buildGroupMap,\n  getConditionKey,\n  getViewConditions,\n  hasComparison,\n  OTHER_GROUP_NAME,\n} from '$lib/services/common/view';\nimport { selectedCollection } from '$lib/services/contents/collection';\nimport { getReorderGroupName } from '$lib/services/contents/collection/entries/reorder/config';\nimport {\n  matchesConditions,\n  prepareConditions,\n} from '$lib/services/contents/collection/view/conditions';\nimport { parseViewOptions } from '$lib/services/contents/collection/view/options';\nimport { currentView } from '$lib/services/contents/collection/view/settings';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getPropertyValue } from '$lib/services/contents/entry/values';\nimport { createDerivedState } from '$lib/services/utils/state.svelte';\n\n/**\n * @import {\n * Entry,\n * GroupingConditions,\n * InternalCollection,\n * InternalEntryCollection,\n * } from '$lib/types/private';\n * @import { DateTimeField, 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 fieldConfig = getField({ collectionName, keyPath: field });\n\n  const dateFieldConfig =\n    fieldConfig?.widget === 'datetime' ? /** @type {DateTimeField} */ (fieldConfig) : undefined;\n\n  const prepared = prepareConditions(conditions, { dateFieldConfig, 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    const args = { entry, locale, collectionName, key: field };\n    const rawValue = getPropertyValue({ ...args, resolveRef: false });\n    const refValue = getPropertyValue({ ...args });\n\n    (matchesConditions({ rawValue, refValue, conditions: prepared }) ? matched : others).push(\n      entry,\n    );\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 * @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 = (entries, collection, conditions, now = new Date()) => {\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 sortCondition = currentView.current.sort;\n\n  const sortedGroups = buildGroupMap(entries, pattern, (entry) =>\n    getPropertyValue({ 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 = createDerivedState(() => {\n  const collection = selectedCollection.current;\n\n  // Disable grouping for file/singleton collection\n  if (collection?._type !== 'entry') {\n    return [];\n  }\n\n  return parseGroupConfig(collection.view_groups).options;\n});\n","import { sortItemsByKey } from '$lib/services/common/view';\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 { getSortKeyType } from '$lib/services/contents/collection/view/sort-keys';\nimport { getField } from '$lib/services/contents/entry/fields';\nimport { getEntrySummary } from '$lib/services/contents/entry/summary';\nimport { getPropertyValue } from '$lib/services/contents/entry/values';\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.\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} 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') {\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 = getPropertyValue({ entry, locale, collectionName, key });\n\n      return raw ? Number(getDate(raw, dateFieldConfig) ?? 0) : 0;\n    };\n  }\n\n  if (type === String) {\n    return (/** @type {Entry} */ entry) => {\n      const raw = getPropertyValue({ entry, locale, collectionName, key });\n      const str = raw ? 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  return (/** @type {Entry} */ entry) => {\n    const raw = getPropertyValue({ entry, locale, collectionName, key });\n\n    return Number(raw ?? 0);\n  };\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    name: collectionName,\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, keeping its place among the others. The\n  // field may not be defined under the collection’s `fields`, so it would otherwise default to a\n  // string sort, and a missing value would come first\n  if (key === '_manual' || key === getOrderFieldKey(collection)) {\n    const sorted = sortEntriesByOrderField(\n      entries,\n      /** @type {InternalEntryCollection} */ (collection),\n    );\n\n    if (order === 'descending') {\n      sorted.reverse();\n    }\n\n    return moveIndexFileToTop(sorted, collection);\n  }\n\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  // `sortItemsByKey()` computes the key once per entry, so there’s no need for a lookup table here\n  sortItemsByKey(_entries, getSortKey, !dateFieldConfig && type === String, order);\n\n  return moveIndexFileToTop(_entries, collection);\n};\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 { 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 * 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 {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 * 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 nested collection.\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, because the reorder UI persists an order field on the published\n  // entries, and the draft version must not leak into that commit\n  if (reordering.current) {\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 * 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}. Unlike an update to an\n * existing entry, which replaces the published version in {@link listedEntries}, these are listed\n * in a separate group above the published entries.\n * @type {{ readonly current: Entry[] }}\n */\nexport const listedUnpublishedEntries = createDerivedState(() => {\n  const { current: _collection } = selectedCollection;\n\n  if (_collection?._type !== 'entry' || reordering.current) {\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  /** @type {Entry[]} */\n  let entries = 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  if (!entries.length) {\n    return [];\n  }\n\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 * Map from entry ID to the entry’s index in {@link listedEntries}, used by list rows to resolve\n * their `aria-rowindex` in O(1). Rows are appended by an infinite scroller and never unmounted, so\n * 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(listedEntries.current.map((entry, index) => [entry.id, index])),\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\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 canReorder =\n      !readonly &&\n      isManuallyOrdered(_selectedCollection) &&\n      !openAuthoring.current &&\n      !lockedBranch.current;\n\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      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    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(filteredEntries.current, collection, group, viewTime.current);\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  const view = { ...(entryListSettings.current?.[collection.name] ?? { type: 'list' }) };\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// 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\ncreateRootEffect(() => {\n  const collection = selectedCollection.current;\n  const { current: _allEntries } = allEntries;\n\n  if (collection?._type === 'entry') {\n    untrack(() => {\n      restoreView(collection, _allEntries);\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\ncreateRootEffect(() => {\n  const collection = selectedCollection.current;\n\n  // Reset the reorder state when switching collections, to avoid accidentally reordering entries in\n  // the wrong collection or leaving the UI in a broken state if the new collection doesn’t support\n  // reordering. Discard any view snapshot first so it isn’t restored against the wrong collection,\n  // which would otherwise corrupt the new collection’s persisted view via `entryListSettings`.\n  untrack(() => {\n    viewBeforeReorder.current = undefined;\n\n    if (reordering.current) {\n      setReorderMode(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 { getAssetFoldersByPath } from '$lib/services/assets/folders';\nimport { createDisplayBlobURL, getAssetBlob } from '$lib/services/assets/info';\nimport { MARKDOWN_IMAGE_REGEX } from '$lib/services/assets/references';\nimport { getOwnedEntryFolderPath } from '$lib/services/contents/draft/save/assets';\nimport { getField, getTypedKeyPath } from '$lib/services/contents/entry/fields';\nimport { MEDIA_FIELD_TYPES, RICH_TEXT_FIELD_TYPES } from '$lib/services/contents/fields';\nimport {\n  getAssetLibraryFolderMap,\n  getDefaultAssetFolder,\n} from '$lib/services/contents/fields/file/helpers';\nimport { getEntryAssetVersion } from '$lib/services/workflow/assets';\n\n/**\n * @import {\n * AssetFolderInfo,\n * EntryDraft,\n * EntryFileMap,\n * FlattenedEntryContent,\n * LocaleContentMap,\n * TypedFieldKeyPath,\n * } from '$lib/types/private';\n * @import { FieldKeyPath } 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 = (entry.locales[defaultLocale] ?? Object.values(entry.locales)[0])?.path;\n  const ownsFolder = !!entryFilePath && !!getOwnedEntryFolderPath(collection, entryFilePath);\n  /**\n   * Copies in progress, keyed by asset path, so an asset referenced more than once, from another\n   * locale or field, is copied once and shares the blob URL.\n   * @type {Map<string, Promise<string | undefined>>}\n   */\n  const copies = new Map();\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   * @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 }) => {\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 }),\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    let copy = copies.get(asset.path);\n\n    if (!copy) {\n      copy = (async () => {\n        /** @type {Blob} */\n        let blob;\n\n        try {\n          blob = await getAssetBlob(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        const file = new File([blob], asset.name, { type: blob.type });\n        // The file comes 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(asset.path, copy);\n    }\n\n    return copy;\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 {FieldKeyPath} args.keyPath Key path of the field.\n   */\n  const copyFieldAssets = async ({ valueMap, keyPath }) => {\n    const value = valueMap[keyPath];\n\n    if (typeof value !== 'string' || !value) {\n      return;\n    }\n\n    const getFieldArgs = { collectionName, fileName, valueMap, keyPath, isIndexFile };\n    const { widget: fieldType = 'string' } = getField(getFieldArgs) ?? {};\n\n    if (!ASSET_FIELD_TYPES.includes(fieldType)) {\n      return;\n    }\n\n    const typedKeyPath = getTypedKeyPath(getFieldArgs);\n\n    // Where the field editor puts a newly picked file, so the copy ends up in the same place\n    const folder = getDefaultAssetFolder(\n      getAssetLibraryFolderMap({ collectionName, fileName, typedKeyPath, isIndexFile }),\n    );\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    if (!folder.entryRelative || !(ownsFolder || folder.hasTemplateTags)) {\n      return;\n    }\n\n    if (MEDIA_FIELD_TYPES.includes(fieldType)) {\n      const blobURL = await copyAsset({ value, folder, typedKeyPath });\n\n      if (blobURL) {\n        valueMap[keyPath] = blobURL;\n      }\n\n      return;\n    }\n\n    // Images embedded in a Markdown body\n    const sources = [...new Set([...value.matchAll(MARKDOWN_IMAGE_REGEX)].map(([, src]) => src))];\n\n    const blobURLs = new Map(\n      await Promise.all(\n        sources.map(\n          async (src) =>\n            /** @type {[string, string | undefined]} */ ([\n              src,\n              await copyAsset({ value: src, folder, typedKeyPath }),\n            ]),\n        ),\n      ),\n    );\n\n    // Replace the source within each image only, once every copy is ready. A plain text replacement\n    // would also hit a source whose name contains another’s, e.g. `hero-image.png` for `image.png`,\n    // as well as the file name mentioned anywhere else in the text\n    valueMap[keyPath] = value.replace(MARKDOWN_IMAGE_REGEX, (image, src) => {\n      const blobURL = blobURLs.get(src);\n\n      if (!blobURL) {\n        return image;\n      }\n\n      // The source comes right after the first `](`, as the alt text is matched lazily\n      const start = image.indexOf('](') + 2;\n\n      return `${image.slice(0, start)}${blobURL}${image.slice(start + src.length)}`;\n    });\n  };\n\n  await Promise.all(\n    Object.values(currentValues).flatMap((valueMap) =>\n      Object.keys(valueMap).map((keyPath) => copyFieldAssets({ valueMap, 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, isDuplicatedField } from '$lib/services/contents/draft/create/proxy.svelte';\nimport { fillUuidValues } from '$lib/services/contents/draft/create/uuid';\nimport { showDuplicateToast } from '$lib/services/contents/editor';\nimport { getAliasesKey, removeAliases } from '$lib/services/contents/entry/aliases';\nimport { 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 as getInitialUuidValue } from '$lib/services/contents/fields/uuid/helpers';\nimport { isFieldLocalized, isFieldTranslatable } from '$lib/services/contents/i18n/fields';\nimport { getOrCreate } from '$lib/services/utils/cache';\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 * GetFieldArgs,\n * InternalLocaleCode,\n * LocaleContentMap,\n * } from '$lib/types/private';\n * @import { ComputeField, 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 * 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 { collectionName, fileName, collection, collectionFile, fields, isIndexFile } = draft;\n\n  const {\n    defaultLocale,\n    canonicalSlug: { key: canonicalSlugKey },\n  } = (collectionFile ?? collection)._i18n;\n\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  /**\n   * Key paths of the duplicated Hidden fields in each non-default locale, which take the default\n   * locale’s new values once those are in place.\n   * @type {Map<InternalLocaleCode, Set<FieldKeyPath>>}\n   */\n  const duplicatedHiddenFieldMap = new Map();\n  /**\n   * Duplicated UUID fields cleared in each non-default locale, along with their configuration, for\n   * the ones the default locale has no value to copy for.\n   * @type {Map<InternalLocaleCode, Map<FieldKeyPath, UuidField>>}\n   */\n  const clearedUuidFieldMap = new Map();\n\n  Object.entries(currentValues).forEach(([locale, valueMap]) => {\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\n    // a unique order even after backup/restore round trips\n    if (orderFieldKey) {\n      delete valueMap[orderFieldKey];\n    }\n\n    const getFieldArgs = { collectionName, fileName, valueMap, isIndexFile };\n    /** @type {Map<FieldKeyPath, HiddenField>} */\n    const hiddenFields = new Map();\n\n    // Reset some unique values\n    Object.keys(valueMap).forEach((keyPath) => {\n      const fieldConfig = getField({ ...getFieldArgs, keyPath });\n\n      if (fieldConfig?.widget === 'uuid') {\n        if (locale === defaultLocale || isFieldTranslatable(fieldConfig.i18n)) {\n          valueMap[keyPath] = getInitialUuidValue(/** @type {UuidField} */ (fieldConfig));\n        } else if (isDuplicatedField({ fieldConfig, getFieldArgs: { ...getFieldArgs, keyPath } })) {\n          // Cleared for `fillUuidValues()` below to copy the default locale’s new value\n          valueMap[keyPath] = '';\n          getOrCreate(clearedUuidFieldMap, locale, () => new Map()).set(\n            keyPath,\n            /** @type {UuidField} */ (fieldConfig),\n          );\n        }\n      }\n\n      // A Compute field keeps the UUIDs found in its current value when it’s resolved again, so\n      // the value has to be cleared for the duplicate to get UUIDs of its own. The field is\n      // resolved as soon as the new draft is in place\n      if (\n        fieldConfig?.widget === 'compute' &&\n        hasUuidTag(/** @type {ComputeField} */ (fieldConfig).value)\n      ) {\n        if (locale === defaultLocale || isFieldLocalized(fieldConfig?.i18n)) {\n          valueMap[keyPath] = '';\n        }\n      }\n\n      const hidden = findHiddenField({ ...getFieldArgs, keyPath });\n\n      if (hidden) {\n        if (locale === defaultLocale || isFieldTranslatable(hidden.fieldConfig.i18n)) {\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\n          delete valueMap[keyPath];\n          hiddenFields.set(hidden.keyPath, hidden.fieldConfig);\n        } else if (\n          isDuplicatedField({\n            fieldConfig: hidden.fieldConfig,\n            getFieldArgs: { ...getFieldArgs, keyPath: hidden.keyPath },\n          })\n        ) {\n          delete valueMap[keyPath];\n          getOrCreate(duplicatedHiddenFieldMap, locale, () => new Set()).add(hidden.keyPath);\n        }\n      }\n    });\n\n    // Fill in the defaults once all the old values are gone, so a key path that comes after its\n    // own items, like `tags` after `tags.0`, doesn’t take the default away again\n    hiddenFields.forEach((fieldConfig, keyPath) => {\n      Object.assign(\n        valueMap,\n        getHiddenFieldDefaultValueMap({ fieldConfig, keyPath, locale, defaultLocale }),\n      );\n    });\n  });\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({\n    contentMap: currentValues,\n    defaultLocale,\n    getFieldArgs: { collectionName, fileName, isIndexFile },\n  });\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  // 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 { 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 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  entryDraft.current = newDraft;\n  showDuplicateToast.current = true;\n\n  return newDraft;\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  getNestedConfig,\n  isDescendantPath,\n} from '$lib/services/contents/collection/nested';\nimport {\n  buildEntryFileChanges,\n  resolveCacheDB,\n} from '$lib/services/contents/draft/save/file-changes';\nimport { hasLocalizedSlugs } from '$lib/services/contents/draft/slugs';\nimport { createSyntheticDraft } from '$lib/services/contents/entry/changes';\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 * InternalEntryCollection,\n * InternalLocaleCode,\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. In a nested collection 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  return {\n    ...entry,\n    locales: Object.fromEntries(\n      Object.entries(locales).map(([locale, localizedEntry]) => [\n        locale,\n        localizedEntry.content\n          ? // Copy the content, which is shared with the entry in the store\n            { ...localizedEntry, content: { ...localizedEntry.content, [key]: canonicalSlug } }\n          : localizedEntry,\n      ]),\n    ),\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        const previousPath = originalEntry.locales[defaultLocale].path;\n        const { slug, path } = movedEntry.locales[defaultLocale];\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 collection entry along with the\n * entry itself. In the `subfolders` mode, an entry owns the folder it’s stored in, so relocating it\n * with the path editor has to take everything below that folder with it, or the descendants would\n * 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\n  if (!originalEntry || !getNestedConfig(collection)?.subfolders) {\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 = descendants.flatMap((entry) => {\n    const movedEntry = moveEntry({ entry, dirMove, localeDirMoves });\n\n    return movedEntry\n      ? [\n          {\n            originalEntry: entry,\n            movedEntry: updateCanonicalSlug({ collection, entry: movedEntry }),\n          },\n        ]\n      : [];\n  });\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 { getAssetFolder } from '$lib/services/assets/folders';\nimport { getAssetBlob } from '$lib/services/assets/info';\nimport { allAssets } from '$lib/services/assets/state';\nimport { getOwnedEntryFolderPath } from '$lib/services/contents/draft/save/assets';\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 */\nconst 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 * 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\n          .filter(({ path }) => path.startsWith(`${oldFolderPath}/`))\n          .map(async (asset) => {\n            const path = `${newFolderPath}${asset.path.slice(oldFolderPath.length)}`;\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            const blob = asset.file ?? (await getAssetBlob(asset));\n\n            moveChanges.push({\n              action: 'move',\n              path,\n              previousPath: asset.path,\n              previousSha: asset.sha,\n              // Read the bytes up front. A blob backed by the file system points at the file about\n              // to be moved away, and reading it afterwards — to write the copy or to hash it —\n              // fails because there’s nothing at that path anymore\n              data: new File([await blob.arrayBuffer()], asset.name, { type: blob.type }),\n            });\n\n            savingAssets.push({ ...asset, path });\n          }),\n      ),\n    ),\n  );\n\n  return { changes: moveChanges, savingAssets };\n};\n","import equal from 'fast-deep-equal';\n\nimport { backend } from '$lib/services/backends';\nimport { getUnpublishedEntryByDraft } from '$lib/services/workflow';\nimport { loadUnpublishedEntries } 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 is gone, which is what a pull request merged or closed outside the CMS leaves\n  // behind. That’s a separate known issue — such a pull request stays on the board until the next\n  // reload, and saving it fails on the missing branch — so it’s left as it is rather than reported\n  // here as a change to save over\n  if (!head) {\n    return undefined;\n  }\n\n  const canOverwrite = originalEntry.arrayIndex === undefined;\n\n  // The branch has moved, so read the entry back from it. The reload swallows its own failures,\n  // which leaves the stores as they were and the comparison below with nothing to report\n  await loadUnpublishedEntries();\n\n  const current = getUnpublishedEntryByDraft({ collectionName, fileName, originalEntry });\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\n  if (!equal(current.locales, originalEntry.locales)) {\n    return { type: 'modified', entry: current, canOverwrite };\n  }\n\n  return undefined;\n};\n","import { callEventHooks } from '$lib/services/api/events';\nimport { skipCIConfigured, skipCIEnabled } from '$lib/services/backends/git/shared/integration';\nimport { saveChanges } from '$lib/services/backends/save';\nimport { getReadonlyMessage, isDraftReadonly } from '$lib/services/config/readonly';\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 { deleteBackup, getBackupSlug } from '$lib/services/contents/draft/backup';\nimport { getReferencedPendingEntries } from '$lib/services/contents/draft/pending-entries';\nimport { buildEntryAssetMoveChanges } from '$lib/services/contents/draft/save/asset-move';\nimport { createSavingEntryData } from '$lib/services/contents/draft/save/changes';\nimport { detectEntryConflict } from '$lib/services/contents/draft/save/conflict';\nimport { assignManualSortOrder } from '$lib/services/contents/draft/save/sort-order';\nimport { getSlugs } from '$lib/services/contents/draft/slugs';\nimport { isRequiredEnforced } from '$lib/services/contents/draft/validate/required';\nimport { validateAndRevealErrors } from '$lib/services/contents/draft/validate/reveal';\nimport { clearEntryHistoryCache } from '$lib/services/contents/entry/history';\nimport { buildCascadeChanges } from '$lib/services/contents/entry/relations/cascade/update';\nimport { assignAutoNowValues } from '$lib/services/contents/fields/date-time/auto-now';\nimport { setLastCommitPublishHint } from '$lib/services/deployments';\nimport { isWorkflowDraft } 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 * } from '$lib/types/private';\n */\n\n/**\n * Update the application stores with deployment settings.\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  // With Editorial Workflow, changes go to a pull request, so nothing is published yet\n  const published = !useWorkflow && skipCIConfigured.current && !(skipCI ?? skipCIEnabled.current);\n\n  contentUpdatesToast.current = {\n    ...UPDATE_TOAST_DEFAULT_STATE,\n    saved: true,\n    published,\n    count,\n  };\n\n  setLastCommitPublishHint(published);\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 * @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 }) => {\n  const { collection, fileName, originalEntry } = draft;\n\n  try {\n    const { savingEntry, changes, savingAssets } = await createSavingEntryData({ draft, slugs });\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 nested collection takes everything below it to the new 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\n    const { changes: assetMoveChanges, savingAssets: movedAssets } =\n      await buildEntryAssetMoveChanges({\n        collection,\n        fileName,\n        originalEntry,\n        savingEntry,\n        changes,\n      });\n\n    changes.push(...assetMoveChanges);\n    savingAssets.push(...movedAssets);\n\n    return { savingEntry, changes, savingAssets, cascadeEntries, movedEntries };\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 * 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 * @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 ({ draft, skipCI = undefined, overwrite = false }) => {\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  const { isNew, collection, collectionName, fileName, originalEntry } = draft;\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 = isWorkflowDraft(draft);\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  if (!(await validateAndRevealErrors({ draft, enforceRequired: isRequiredEnforced(draft) }))) {\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  if (isNew && collection._type === 'entry') {\n    // The entries added to the same collection from a Relation field have already taken the orders\n    // after the highest one, so the new entry comes after them\n    assignManualSortOrder(\n      draft,\n      draft.pendingEntries.filter((pendingEntry) => pendingEntry.collectionName === collectionName)\n        .length,\n    );\n  }\n\n  // Set the DateTime fields with the `auto_now` option at save time rather than when the draft was\n  // created, so the value tells when the entry was actually saved\n  assignAutoNowValues(draft);\n\n  const slugs = getSlugs({ draft });\n  const { defaultLocaleSlug } = slugs;\n\n  const { savingEntry, changes, savingAssets, cascadeEntries, movedEntries } = await buildChanges({\n    draft,\n    slugs,\n  });\n\n  // The entries created from a Relation field go into the same commit as the entry referring to\n  // them, so neither can end up without the other\n  const pendingEntries = getReferencedPendingEntries(draft);\n\n  changes.push(...pendingEntries.flatMap((pendingEntry) => pendingEntry.changes));\n  savingAssets.push(...pendingEntries.flatMap((pendingEntry) => pendingEntry.savingAssets));\n\n  const savingPendingEntries = pendingEntries.map((pendingEntry) => pendingEntry.entry);\n  /** @type {ChangeResults} */\n  let results;\n  /** @type {CommitOptions} */\n  const options = { commitType: isNew ? 'create' : 'update', collection, skipCI };\n\n  try {\n    results = useWorkflow\n      ? await saveWorkflowChanges({\n          changes,\n          savingEntry,\n          savingAssets,\n          options,\n          collectionName,\n          fileName,\n          slug: defaultLocaleSlug,\n          originalEntry,\n        })\n      : await saveChanges({\n          changes,\n          savingEntries: [savingEntry, ...cascadeEntries, ...movedEntries, ...savingPendingEntries],\n          savingAssets,\n          options,\n        });\n  } catch (/** @type {any} */ ex) {\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  // 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 slug the entry had when it was opened, which a rename leaves behind\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 }) =>\n      callEventHooks({\n        type: 'postSave',\n        entry,\n        collection: /** @type {InternalCollection} */ (getCollection(pendingCollectionName)),\n        isNew: true,\n      }),\n    ),\n  );\n\n  updateStores({\n    useWorkflow,\n    skipCI,\n    count: 1 + cascadeEntries.length + movedEntries.length + pendingEntries.length,\n  });\n\n  if (originalEntry) {\n    clearEntryHistoryCache(originalEntry.id);\n  }\n\n  return results.savedEntries[0];\n};\n","/**\n * @import { 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 nested collection.\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","<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 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 {\n    encodeRoutePath,\n    getEntryEditorBackPath,\n    goBack,\n    goto,\n    overlayTitle,\n  } from '$lib/services/app/navigation';\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 { isNestedCollection, 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 { duplicateDraft } from '$lib/services/contents/draft/create/duplicate';\n  import { saveEntry } from '$lib/services/contents/draft/save';\n  import { getEntryDraftContext } from '$lib/services/contents/draft/state.svelte';\n  import { canResetEntry } from '$lib/services/contents/draft/update/reset';\n  import { validateDraft } from '$lib/services/contents/draft/validate';\n  import { countInvalidFields } from '$lib/services/contents/draft/validate/reveal';\n  import { activeInlineEditors, copyFromLocaleToast } from '$lib/services/contents/editor';\n  import {\n    awaitPendingFieldUpdates,\n    fieldUpdatePending,\n  } from '$lib/services/contents/editor/pending';\n  import { getSidebarPanels, showSidebarPanel } from '$lib/services/contents/editor/sidebar';\n  import { canUpdateSlug } from '$lib/services/contents/editor/slug';\n  import {\n    canDuplicateEntry,\n    getRemovalMenuItems,\n    getSaveFailure,\n  } 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    checkPublishedVersion,\n    getUnpublishedEntryByDraft,\n    isPendingDeletion,\n    isWorkflowEnabled,\n    workflowEnabled,\n  } from '$lib/services/workflow';\n  import { getDiscardDialogStrings } from '$lib/services/workflow/dialogs';\n  import { openAuthoring } from '$lib/services/workflow/open-authoring';\n  import { updateWorkflowStatus } from '$lib/services/workflow/save';\n  import { getWorkflowErrorMessage } from '$lib/services/workflow/verify';\n\n  /**\n   * @import { UnpublishedEntry } from '$lib/types/private';\n   * @import { EntryConflict } from '$lib/services/contents/draft/save/conflict';\n   * @import { ResetAction } from '$lib/services/contents/editor/reset';\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\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    disabled = false,\n    /* eslint-enable prefer-const */\n  } = $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   * 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 } | undefined}\n   */\n  let saveConflict = $state();\n  let showErrorDialog = $state(false);\n  let errorMessage = $state('');\n  let saving = $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  /**\n   * Whether restoring the default values or clearing the fields would change anything. It takes\n   * going through the whole entry, so it’s only checked as the menu opens rather than on every\n   * change.\n   */\n  let resetAvailability = $state({ restore: false, clear: false });\n  /** @type {ResetAction} */\n  let resetAction = $state('revert');\n  let showResetDialog = $state(false);\n\n  /**\n   * Check whether restoring the default values or clearing the fields would change anything.\n   */\n  const updateResetAvailability = () => {\n    const draft = entryDraft.current;\n\n    resetAvailability = {\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 entryCollection = $derived(collection?._type === 'entry' ? collection : undefined);\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  const associatedAssets = $derived(\n    collectionName && originalEntry\n      ? getEntryRelativeAssets({ entry: originalEntry, collectionName, fileName })\n      : [],\n  );\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  // 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 = $derived(!!unpublishedEntry || isWorkflowEnabled(collection));\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(entryCollection?.delete !== false);\n  // The entry can be published from another view, so the check depends on `allEntries`\n  const publishedVersionExists = $derived(checkPublishedVersion(unpublishedEntry));\n  // Deleting an entry that was never published just throws the draft away; anything else takes an\n  // entry off the site\n  const discardsDraft = $derived(!!unpublishedEntry && !publishedVersionExists);\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\n  const canDeleteEntry = $derived(canDelete && (discardsDraft || !openAuthoring.current));\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\n  const pendingDeletion = $derived(isPendingDeletion(unpublishedEntry));\n  // An entry in a read-only collection, or a read-only collection file, can only be viewed: there’s\n  // nothing to save, move through the stages, publish, discard or delete\n  const readonly = $derived(isDraftReadonly(entryDraft.current));\n  // Neither kind of entry can have its content changed\n  const locked = $derived(pendingDeletion || readonly);\n  const canDuplicate = $derived(\n    canDuplicateEntry({\n      collection,\n      collectionFile,\n      isIndexFile,\n      readonly,\n      creationDisabled: collectionState.current.creationDisabled,\n    }),\n  );\n  // A collection file is part of the collection definition, so it can only be discarded\n  const removalMenuItems = $derived(\n    getRemovalMenuItems({\n      publishedVersionExists,\n      canDeleteEntry,\n      isCollectionFile: !!collectionFile,\n      readonly,\n      locked,\n    }),\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 && isNestedCollection(collection) ? nestedFilterPath.current : '';\n\n    goBack(getEntryEditorBackPath({ collectionName, dirPath }), {\n      returnTo: isSearchResultsPath,\n    });\n  };\n\n  /**\n   * Check whether the entry that has just been saved is complete enough to be handed over for\n   * review. Required fields aren’t enforced while an entry is a draft, so it may have been saved\n   * with some of them empty. The check leaves the editor state alone: nothing is wrong with the\n   * draft as saved, so no errors are shown for it.\n   * @returns {boolean} Result.\n   */\n  const isReadyForReview = () => {\n    const draft = entryDraft.current;\n\n    return !!draft && validateDraft({ draft }).valid;\n  };\n\n  /**\n   * Ask whether the entry just saved should be handed over for review, and wait for the answer.\n   * @returns {Promise<boolean>} `true` if the user wants to send it.\n   */\n  const askForReview = () =>\n    new Promise((resolve) => {\n      resolveReviewPrompt = resolve;\n      showReviewDialog = true;\n    });\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   */\n  const save = async ({ skipCI = undefined, overwrite = false } = {}) => {\n    const draft = entryDraft.current;\n\n    if (!collection || !draft) {\n      return;\n    }\n\n    saving = true;\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 (!isNew && !entryDraft.modified) {\n        return;\n      }\n\n      const savedEntry = await saveEntry({ draft, skipCI, overwrite });\n      const savedDraft = /** @type {UnpublishedEntry} */ (savedEntry);\n      let statusChangeFailed = false;\n\n      // Saving with Editorial Workflow leaves the entry as a draft, which nothing on screen says:\n      // it hasn’t been handed to anyone yet, and the status menu that would do it is easy to miss.\n      // Offer it as the next step instead, once, while the entry is still in the drafting stage\n      if (\n        useWorkflow &&\n        savedDraft.workflow?.status === 'draft' &&\n        // An incomplete entry isn’t ready to be handed over; the status menu is still there once\n        // the remaining fields have been filled in\n        isReadyForReview() &&\n        (await askForReview())\n      ) {\n        try {\n          await updateWorkflowStatus(savedDraft, 'pending_review');\n        } catch (/** @type {any} */ ex) {\n          showErrorDialog = true;\n          errorMessage = getWorkflowErrorMessage(ex, 'workflow.status_change_failed');\n          statusChangeFailed = true;\n          // eslint-disable-next-line no-console\n          console.error(ex);\n        }\n      }\n\n      if (isNew) {\n        // Update the URL. A collection file is addressed by its name, while its `subPath` is the\n        // whole file path. This is done even when the editor is about to be closed, so the `new`\n        // 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        goto(\n          encodeRoutePath(\n            `/collections/${collectionName}/entries/${fileName ?? savedEntry.subPath}`,\n          ),\n          { replaceState: true, notifyChange: false },\n        );\n      }\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\n      if ((prefs.closeOnSave ?? true) && !statusChangeFailed) {\n        _goBack();\n        entryDraft.current = null;\n      } else {\n        // Reset the draft. 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\n        // else’s change to the entry\n        createDraft({\n          entryDraft,\n          collection,\n          collectionFile,\n          originalEntry: savedEntry,\n          extraValues: draft.extraValues,\n          expanderStates: draft.expanderStates,\n        });\n      }\n    } catch (/** @type {any} */ ex) {\n      const failure = getSaveFailure(ex);\n\n      if (failure.type === 'validation') {\n        errorCount = countInvalidFields(draft.validities);\n        showValidationToast = true;\n      } else if (failure.type === 'conflict') {\n        // Someone else has changed the entry since it was opened; let the user decide\n        saveConflict = { conflict: failure.conflict, skipCI };\n        showConflictDialog = true;\n      } else {\n        showErrorDialog = true;\n        errorMessage = failure.message;\n\n        if (failure.unexpected) {\n          // eslint-disable-next-line no-console\n          console.error(ex);\n        }\n      }\n    } finally {\n      saving = 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 !env.isSmallScreen}\n    {@render overflowButtons()}\n  {/if}\n  {#if unpublishedEntry && !locked}\n    <EntryStatusMenu entry={unpublishedEntry} disabled={controlsDisabled} />\n  {/if}\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}\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 && !readonly}\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={updateResetAvailability}\n    onkeydown={updateResetAvailability}\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 { key, disabled: panelDisabled } (key)}\n              <MenuItem\n                label={_(`entry_sidebar.${key}.title`)}\n                disabled={panelDisabled}\n                onclick={() => {\n                  showSidebarPanel(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 original’s own assets are copied along with the entry, so this can take a\n                // moment. The URL is updated only once the duplicate is in place\n                const duplicated = !!(await duplicateDraft(entryDraft));\n\n                duplicating = false;\n\n                if (duplicated) {\n                  goto(`/collections/${collectionName}/new`, {\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: resetAvailability.restore && !locked,\n            clear: resetAvailability.clear && !locked,\n          }}\n          onSelect={(action) => {\n            resetAction = action;\n            showResetDialog = true;\n          }}\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<Toast bind:show={showValidationToast}>\n  <Alert status=\"error\">\n    {_('entry_validation_errors', { values: { count: errorCount } })}\n    <Button\n      variant=\"secondary\"\n      size=\"small\"\n      label={_('show_errors')}\n      onclick={() => {\n        showValidationToast = false;\n        showSidebarPanel('validation');\n      }}\n    />\n  </Alert>\n</Toast>\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<ResetDialog\n  bind:open={showResetDialog}\n  action={resetAction}\n  onClose={() => {\n    menuButton?.focus();\n  }}\n/>\n\n<ConfirmationDialog\n  bind:open={showReviewDialog}\n  title={_('workflow.send_for_review')}\n  okLabel={_('workflow.send_for_review')}\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  {_('workflow.confirm_sending_for_review')}\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 });\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  .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 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 { focusOverlay, rememberFocus } from '$lib/services/app/focus';\n  import { goto } from '$lib/services/app/navigation';\n  import { getReadonlyMessage, isDraftReadonly } 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/proxy.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 { watch } from '$lib/services/utils/state.svelte';\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 {\n    /* eslint-disable prefer-const */\n    entryDraft,\n    editorLocale = undefined,\n    loading = false,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  // svelte-ignore state_referenced_locally\n  setEntryDraftContext(entryDraft);\n\n  let restoring = false;\n  let switching = false;\n  /**\n   * Number of field highlight requests so far, so a request still looking for its field can tell\n   * whether a newer one has come in.\n   */\n  let highlightRequestCount = 0;\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    collection,\n    collectionName,\n    collectionFile,\n    fileName,\n    isIndexFile,\n  } = $derived(/** @type {EntryDraft} */ (entryDraft.current ?? {}));\n  const { showPreview, showSecondPane = true } = $derived(entryEditorSettings.current ?? {});\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\n  const readonly = $derived(isDraftReadonly(entryDraft.current));\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        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    highlightRequestCount += 1;\n\n    const request = highlightRequestCount;\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 = () => request !== highlightRequestCount;\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      void draft.pendingEntries.length;\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  $effect(() => {\n    if (paneStateKey) {\n      // Reset the editor panes\n      editorFirstPane.current = null;\n      editorSecondPane.current = null;\n    }\n  });\n\n  watch(\n    () => [\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    <!-- A new entry that can’t be created gets the message in place of the editor instead -->\n    {#if readonly && !loading && !(isNew && creationDisabled)}\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    {/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      <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                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\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  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 { WORKFLOW_STATUS_LABELS } from '$lib/services/workflow/constants';\n\n  /**\n   * @import { 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 {\n    /* eslint-disable prefer-const */\n    status,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<span role=\"none\" class=\"status-badge {status}\">\n  {_(WORKFLOW_STATUS_LABELS[status])}\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-badge {\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    &.draft {\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    &.pending_review {\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    &.pending_publish {\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    &.pending_deletion {\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  Shared cells (checkbox, thumbnail image, title) used by both the read-only entry list row and the\n  reorder list row.\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 { selectedEntryIdSet } from '$lib/services/contents/collection/entries';\n  import {\n    getIndexFile,\n    isCollectionIndexFile,\n  } from '$lib/services/contents/collection/entries/index-file';\n  import { getEntrySummary } from '$lib/services/contents/entry/summary';\n  import { env } from '$lib/services/user/env.svelte';\n\n  /**\n   * @import {\n   * Entry,\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   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    collection,\n    entry,\n    viewType,\n    showCheckbox = false,\n    onSelect = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  // Editorial Workflow information, only present on an unpublished entry\n  const workflow = $derived(/** @type {UnpublishedEntry} */ (entry).workflow);\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{#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 === 'list' ? 'icon' : 'tile'} />\n  </GridCell>\n{/if}\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<GridCell class=\"status\">\n  {#if workflow}\n    <StatusBadge status={workflow.status} />\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 { encodeRoutePath, 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 { 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 { 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   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    collection,\n    entry,\n    viewType,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  // `aria-rowindex` is 1-based, unlike the index map. `undefined` for an entry that has never been\n  // published, as those are listed in a separate group above `listedEntries`. The attribute is then\n  // omitted rather than set to an invalid index.\n  const rowIndex = $derived.by(() => {\n    const index = listedEntryIndexMap.current.get(entry.id);\n\n    return index === undefined ? undefined : 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(encodeRoutePath(`/collections/${collection.name}/entries/${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    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\n  import EntryListItemCells from '$lib/components/contents/list/entry-list-item-cells.svelte';\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    /* eslint-disable prefer-const */\n    collection,\n    entry,\n    viewType,\n    canMoveUp = false,\n    canMoveDown = false,\n    onMoveUp = undefined,\n    onMoveDown = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n</script>\n\n<EntryListItemCells {collection} {entry} {viewType} />\n<GridCell class=\"reorder-actions\">\n  <Button\n    variant=\"ghost\"\n    iconic\n    disabled={!canMoveUp}\n    aria-label={_('move_up')}\n    onclick={(event) => {\n      event.stopPropagation();\n      onMoveUp?.();\n    }}\n  >\n    {#snippet startIcon()}\n      <Icon name=\"arrow_upward\" />\n    {/snippet}\n  </Button>\n  <Button\n    variant=\"ghost\"\n    iconic\n    disabled={!canMoveDown}\n    aria-label={_('move_down')}\n    onclick={(event) => {\n      event.stopPropagation();\n      onMoveDown?.();\n    }}\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    listedEntryIndexMap,\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  /**\n   * Get the 1-based `aria-rowindex` of an entry, or `undefined` for an entry that isn’t in the\n   * listed index, so the attribute is omitted rather than set to an invalid value.\n   * @param {Entry} entry Entry.\n   * @returns {number | undefined} Row index.\n   */\n  const rowIndex = (entry) => {\n    const index = listedEntryIndexMap.current.get(entry.id);\n\n    return index === undefined ? undefined : index + 1;\n  };\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-source={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 marking the gap it would drop into. The\n        pointer already carries the browser’s own drag image of it, so showing it twice at full\n        strength would just be confusing. */\n\n      .grid-row.drag-source {\n        opacity: 0.25;\n        cursor: grabbing;\n      }\n\n      .grid-row[draggable='true']:not(.drag-source) {\n        cursor: grab;\n      }\n    }\n  }\n</style>\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 {\n    /* eslint-disable prefer-const */\n    collectionName,\n    label = undefined,\n    keyShortcuts = undefined,\n    /* eslint-enable prefer-const */\n  } = $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\n  import ListContainer from '$lib/components/common/list-container.svelte';\n  import ListingGrid from '$lib/components/common/listing-grid.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 CreateEntryButton from '$lib/components/contents/toolbar/create-entry-button.svelte';\n  import { getGroupLabel, isGroupCollapsed, setGroupCollapsed } from '$lib/services/common/view';\n  import { selectedCollection } from '$lib/services/contents/collection';\n  import {\n    entryGroups,\n    listedEntries,\n    listedUnpublishedEntries,\n    reordering,\n  } from '$lib/services/contents/collection/view';\n  import { currentView } from '$lib/services/contents/collection/view/settings';\n\n  /**\n   * @import { Entry, InternalEntryCollection } from '$lib/types/private';\n   */\n\n  const collection = $derived(\n    /** @type {InternalEntryCollection | undefined} */ (selectedCollection.current),\n  );\n  const viewType = $derived(reordering.current ? 'list' : currentView.current.type);\n  const allEntries = $derived(entryGroups.current.flatMap(({ entries }) => entries));\n</script>\n\n<ListContainer aria-label={_('entry_list')}>\n  {#if collection}\n    {#if allEntries.length || listedUnpublishedEntries.current.length}\n      {@const { defaultLocale } = collection._i18n}\n      <ListingGrid\n        {viewType}\n        id=\"entry-list\"\n        aria-label={_('entries')}\n        aria-rowcount={listedEntries.current.length + listedUnpublishedEntries.current.length}\n      >\n        <!-- @todo Implement custom table column option that can replace summary template -->\n        {#if reordering.current}\n          <EntryReorderList {collection} {viewType} />\n        {:else}\n          {#if listedUnpublishedEntries.current.length}\n            <GridBody label={_('workflow.unpublished_entries')}>\n              {#each listedUnpublishedEntries.current as entry (entry.id)}\n                <EntryListItem {collection} {entry} {viewType} />\n              {/each}\n            </GridBody>\n          {/if}\n          {#each entryGroups.current as { name, entries } (name)}\n            {#await sleep() then}\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)}\n                onChange={({ detail: { expanded } }) => {\n                  currentView.current = setGroupCollapsed(currentView.current, name, !expanded);\n                }}\n              >\n                <InfiniteScroll\n                  items={entries.filter(\n                    ({ locales }) =>\n                      !!(locales[defaultLocale] ?? Object.values(locales)[0])?.content,\n                  )}\n                  itemKey=\"id\"\n                >\n                  {#snippet renderItem(/** @type {Entry} */ entry)}\n                    {#await sleep() then}\n                      <EntryListItem {collection} {entry} {viewType} />\n                    {/await}\n                  {/snippet}\n                </InfiniteScroll>\n              </GridBody>\n            {/await}\n          {/each}\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  import { sleep } from '@sveltia/utils/misc';\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 { encodeRoutePath, 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 { unpublishedEntries } from '$lib/services/workflow';\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 status 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(({ workflow }) => [workflow.fileName, workflow.status]),\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          {#await sleep() then}\n            <GridRow\n              onclick={() => {\n                goto(\n                  encodeRoutePath(\n                    `/collections/${selectedCollection.current?.name}/entries/${name}`,\n                  ),\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                    {label || name}\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          {/await}\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 { encodeRoutePath, 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\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 {\n    /* eslint-disable prefer-const */\n    node,\n    collectionName,\n    /* eslint-enable prefer-const */\n  } = $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(encodeRoutePath(`/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 {\n    countCollectionEntries,\n    getEntriesByCollection,\n  } from '$lib/services/contents/collection/entries';\n  import { nestedFilterPath } from '$lib/services/contents/collection/nested';\n  import { getNestedTree } from '$lib/services/contents/collection/nested/tree';\n  import { env } from '$lib/services/user/env.svelte';\n  import { mergeUnpublishedEntries, unpublishedEntries } from '$lib/services/workflow';\n\n  /**\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 {\n    /* eslint-disable prefer-const */\n    collection,\n    isSearchPage = false,\n    /* eslint-enable prefer-const */\n  } = $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.by(() =>\n    'files' in collection\n      ? []\n      : mergeUnpublishedEntries(\n          getEntriesByCollection(name),\n          unpublishedEntries.current.filter(({ workflow }) => workflow.collectionName === name),\n        ),\n  );\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  const treeNodes = $derived.by(() => {\n    const internalCollection = getCollection(name);\n\n    return internalCollection ? getNestedTree({ collection: internalCollection, entries }) : [];\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 class=\"count\" aria-label=\"({_('x_entries', { values: { count: entryCount } })})\">\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, encodeRoutePath, goto } from '$lib/services/app/navigation';\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 {\n    /* eslint-disable prefer-const */\n    file,\n    /* eslint-enable prefer-const */\n  } = $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(encodeRoutePath(`/collections/_singletons/entries/${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 {\n  deployments,\n  lastCommitPublishHint,\n  productionSHA,\n  setLastCommitPublishHint,\n} from '$lib/services/deployments';\nimport { prefs } from '$lib/services/user/prefs.svelte';\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 a backend that can trigger a build itself — and the last commit\n * has to be out of date.\n */\nexport const canTriggerDeployment = createDerivedState(\n  () =>\n    (!!prefs.deployHookURL || typeof backend.current?.triggerDeployment === 'function') &&\n    !isLastCommitPublished.current,\n);\n\n/**\n * Trigger a manual deployment on the CI/CD provider, by calling the deploy hook URL configured by\n * the user if there is one, 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 { deployHookURL, deployHookAuthHeader } = prefs;\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 { isNestedCollection } 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 {\n    /* eslint-disable prefer-const */\n    isSearchPage = false,\n    /* eslint-enable prefer-const */\n  } = $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 nested collection has a folder tree, and with it a chevron in front of its icon. Without\n  // one, nothing in the list can expand, so the space kept for the chevrons is dropped.\n  const hasNestedCollections = $derived(\n    collections.some((collection) => !('divider' in collection) && isNestedCollection(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={hasNestedCollections ? undefined : 'flat'}\n    ariaLabel={_('collection_list')}\n    aria-controls={isSearchPage ? 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 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  import { Alert, Button, Toast } from '@sveltia/ui';\n\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  let saving = $state(false);\n  let errorToast = $state(false);\n</script>\n\n<Button\n  variant=\"primary\"\n  label={_('done')}\n  aria-label={_('done_reordering_entries')}\n  disabled={saving || !reorderDirty.current}\n  onclick={async () => {\n    const collection = /** @type {InternalEntryCollection} */ (selectedCollection.current);\n\n    saving = true;\n\n    try {\n      await reorderEntries(collection, reorderedEntries.current);\n      setReorderMode(false);\n    } catch (/** @type {any} */ ex) {\n      // eslint-disable-next-line no-console\n      console.error(ex);\n      errorToast = true;\n    }\n\n    saving = false;\n  }}\n/>\n<Button\n  variant=\"secondary\"\n  label={_('cancel')}\n  aria-label={_('cancel_reordering_entries')}\n  disabled={saving}\n  onclick={() => {\n    setReorderMode(false);\n  }}\n/>\n\n<Toast bind:show={errorToast}>\n  <Alert status=\"error\">\n    {_('saving_reorder_failed')}\n  </Alert>\n</Toast>\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 { 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 { getEntryRelativeAssets } 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 { 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 discards the draft instead of committing a deletion, so the two\n  // kinds of entries have to be handled separately\n  const draftEntries = $derived(\n    /** @type {UnpublishedEntry[]} */ (\n      selectedEntries.current.filter((entry) => 'workflow' in entry)\n    ),\n  );\n  const publishedEntries = $derived(\n    /** @type {Entry[]} */ (selectedEntries.current.filter((entry) => !('workflow' in entry))),\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    const collectionName = selectedCollection.current?.name;\n\n    return publishedEntries.map((entry) => ({\n      entry,\n      assets: collectionName ? getEntryRelativeAssets({ entry, collectionName }) : [],\n    }));\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    try {\n      const collection = selectedCollection.current;\n\n      const toastState = await deleteOrDiscardEntries({\n        drafts: draftEntries,\n        items: publishedEntryAssets,\n        collection,\n        useWorkflow: isWorkflowEnabled(collection),\n      });\n\n      if (toastState) {\n        contentUpdatesToast.current = { ...UPDATE_TOAST_DEFAULT_STATE, ...toastState };\n      }\n    } catch (/** @type {any} */ ex) {\n      errorMessage = getErrorMessage(ex, 'deleting_entry_failed');\n      showErrorToast = true;\n      // eslint-disable-next-line no-console\n      console.error(ex);\n\n      return;\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\n  import BackButton from '$lib/components/common/page-toolbar/back-button.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 { 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    collectionState,\n    listedEntries,\n    listedUnpublishedEntries,\n    reordering,\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\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    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</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    {: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          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      {#if canReorder}\n        <Button\n          variant=\"ghost\"\n          label={_('reorder')}\n          aria-label={_('reorder_entries')}\n          disabled={!listedEntries.current.length}\n          onclick={() => {\n            setReorderMode(true);\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 { encodeRoutePath, 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\n  const folder = $derived(getAssetFolder({ collectionName: selectedCollection.current?.name }));\n  const assets = $derived(\n    folder ? allAssets.current.filter((asset) => isAssetInFolder(asset, folder)) : [],\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(encodeRoutePath(`/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    entryGroups,\n    listedEntries,\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 } 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  /* v8 ignore start -- only read for an entry collection */\n  const thumbnailFieldNames = $derived(entryCollection?._thumbnailFieldNames ?? []);\n  /* v8 ignore stop */\n  // The unpublished entries are listed in their own group above the published ones, so they count\n  // towards the list total as well\n  const listedEntryCount = $derived(\n    listedEntries.current.length + listedUnpublishedEntries.current.length,\n  );\n  const hasListedEntries = $derived(!!listedEntryCount);\n  const hasMultipleEntries = $derived(listedEntryCount > 1);\n</script>\n\n{#if entryCollection && !reordering.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    {#if thumbnailFieldNames.length}\n      <ViewSwitcher disabled={!hasListedEntries} {currentView} aria-controls=\"entry-list\" />\n    {/if}\n    {#if !(env.isSmallScreen || env.isMediumScreen)}\n      <Divider orientation=\"vertical\" />\n      <Button\n        variant=\"ghost\"\n        iconic\n        disabled={!hasListedEntries || !getAssetFolder({ collectionName })}\n        pressed={!!currentView.current.showMedia}\n        aria-controls={currentView.current.showMedia ? 'collection-assets' : undefined}\n        aria-expanded={currentView.current.showMedia}\n        aria-label={_(currentView.current.showMedia ? 'hide_assets' : 'show_assets')}\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  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 { InternalCollection, InternalCollectionFile } 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 */\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 * 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 nested collection’s folder 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  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  const collectionFile = fileMap[subPath];\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  // 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 = getUnpublishedEntry({ collectionName, subPath }) ??\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  params,\n}) => {\n  if (routeType === 'new' && !subPath) {\n    // Decap CMS passes the folder for a new entry in a nested collection 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 originalEntry =\n      getUnpublishedEntry({ collectionName, subPath }) ??\n      // Not `listedEntries`, which a nested collection limits to the folder being browsed,\n      // 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  // `/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  };\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 { listedEntries, listedUnpublishedEntries } 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  // The unpublished entries are listed too, and can be the only ones in the collection\n  const hasListedEntries = $derived(\n    !!(listedEntries.current.length || listedUnpublishedEntries.current.length),\n  );\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          {#if selectedCollection.current?._type === 'entry' && hasListedEntries}\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  $effect(() => {\n    // Update the input value when a different translator service is selected\n    inputValue = prefs.apiKeys?.[serviceId] ?? '';\n  });\n\n  $effect(() => {\n    if (!showContentOverlay.current && translatorApiKeyDialogState.current.show) {\n      // Close the dialog when the Content Editor is closed\n      translatorApiKeyDialogState.current.show = false;\n      translatorApiKeyDialogState.current.resolve?.();\n    }\n  });\n\n  /**\n   * Saves the API key to the user preferences if it matches the expected pattern.\n   */\n  const saveKey = () => {\n    const apiKey = saveApiKey(serviceId, inputValue, apiKeyPattern);\n\n    if (apiKey !== undefined) {\n      translatorApiKeyDialogState.current.show = false;\n      translatorApiKeyDialogState.current.resolve?.(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={() => saveKey()}\n  onOk={() => saveKey()}\n  onCancel={() => {\n    translatorApiKeyDialogState.current.resolve?.();\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 { getUISettingsDB } from '$lib/services/app/ui-settings';\nimport { backend } from '$lib/services/backends';\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.\n */\nexport const canShowMobileSignInDialog = createDerivedState(\n  () =>\n    env.isLargeScreen &&\n    env.hasMouse &&\n    !env.isLocalHost &&\n    !!backend.current?.isGit &&\n    !!user.account?.token,\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} 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 * Create the state of a one-off notice, such as an infobar, that stays hidden once dismissed. The\n * dismissal is stored in the UI settings database under the given name.\n * @param {string} name State name to store the dismissal under.\n * @returns {OneOffNotice} Notice state.\n */\nexport const createOneOffNotice = (name) => {\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 getState(name));\n    },\n    /**\n     * Hide the notice and remember it, so it doesn’t come back.\n     */\n    hide: () => {\n      show.current = false;\n      setState(name, true);\n    },\n  };\n};\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","<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","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Icon, SelectButton, SelectButtonGroup } from '@sveltia/ui';\n\n  import { encodeRoutePath, goto, selectedPageName } from '$lib/services/app/navigation';\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 { workflowEnabled } from '$lib/services/workflow';\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 encodeRoutePath(`/assets/${selectedAssetFolder.current?.internalPath ?? '-/all'}`);\n    }\n\n    return getCloudServicePath(enabledCloudServices.current[0] ?? linkedFilesService);\n  });\n\n  const pages = $derived.by(() => {\n    const _pages = [\n      {\n        key: 'collections',\n        label: _('contents'),\n        icon: 'article',\n        link: '/collections',\n        /** @type {string | undefined} */\n        searchMode: 'contents',\n      },\n    ];\n\n    // Hide the Assets page if there is nothing to show: no asset folder, no external location and\n    // no linked file\n    if (\n      allAssetFolders.current.length ||\n      enabledCloudServices.current.length ||\n      linkedAssets.current.length\n    ) {\n      _pages.push({\n        key: 'assets',\n        label: _('assets'),\n        icon: 'photo',\n        link: assetsLink,\n        searchMode: 'assets',\n      });\n    }\n\n    if (workflowEnabled.current) {\n      _pages.push({\n        key: 'workflow',\n        label: _('editorial_workflow'),\n        icon: 'rebase_edit',\n        link: '/workflow',\n        searchMode: undefined,\n      });\n    }\n\n    if (env.isSmallScreen) {\n      _pages.push({\n        key: 'menu',\n        label: _('menu'),\n        icon: 'menu',\n        link: '/menu',\n        searchMode: undefined,\n      });\n    }\n\n    return _pages;\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, searchMode: sMode }, index (key)}\n      <SelectButton\n        variant=\"ghost\"\n        iconic\n        selected={selectedPageName.current === key || searchMode.current === sMode}\n        aria-label={label}\n        keyShortcuts=\"Alt+{index + 1}\"\n        onclick={() => {\n          goto(link);\n        }}\n      >\n        {#snippet startIcon()}\n          <Icon name={icon} />\n        {/snippet}\n      </SelectButton>\n    {/each}\n  </SelectButtonGroup>\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","<script>\n  import { _ } from '@sveltia/i18n';\n  import { MenuItem } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  let canInstall = $state(false);\n  /** @type {any} */\n  let installPrompt;\n\n  /**\n   * Show the install button when the app is installable.\n   * @param {any} event `BeforeInstallPromptEvent` event.\n   * @see https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps/How_to/Trigger_install_prompt\n   */\n  const beforeInstallPromptHandler = (event) => {\n    event.preventDefault();\n    installPrompt = event;\n    canInstall = true;\n  };\n\n  /**\n   * Hide the install button when the app is installed.\n   */\n  const appInstalledHandler = () => {\n    installPrompt = null;\n    canInstall = false;\n  };\n\n  onMount(() => {\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</script>\n\n{#if canInstall}\n  <MenuItem\n    label={_('install_as_app')}\n    onclick={async () => {\n      await installPrompt?.prompt();\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 {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    onClose = undefined,\n    /* eslint-enable prefer-const */\n  } = $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 {\n    /* eslint-disable prefer-const */\n    menuButton,\n    /* eslint-enable prefer-const */\n  } = $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 {\n    /* eslint-disable prefer-const */\n    key,\n    label,\n    defaultValue = true,\n    /* eslint-enable prefer-const */\n  } = $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","import { IndexedDB, LocalStorage } from '@sveltia/utils/storage';\n\nimport { backend } from '$lib/services/backends';\nimport { TEST_BACKEND_NAME, TEST_BACKEND_ROOT_DIR_NAME } 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, generated asset thumbnails and\n * the asset hashes computed by the local backend. The data in these stores can always be re-fetched\n * or regenerated, so it’s safe to delete.\n * @type {string[]}\n */\nconst CACHE_STORE_NAMES = ['file-cache', 'asset-thumbnails', 'asset-hashes'];\n/**\n * Prefix shared by all the local storage keys written by the CMS, such as `sveltia-cms.prefs`.\n */\nconst LOCAL_STORAGE_KEY_PREFIX = 'sveltia-cms.';\n/**\n * Pattern matching the IndexedDB database names created by the CMS, which are made up of a Git\n * backend name and a repository path, e.g. `github:owner/repo`. Used to leave any database owned by\n * the site hosting the CMS untouched.\n */\nconst DATABASE_NAME_REGEX = new RegExp(`^(?:${Object.keys(gitBackendServices).join('|')}):`);\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 } = backend.current?.repository ?? {};\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","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Button, ConfirmationDialog, TextInput } from '@sveltia/ui';\n\n  import PrefSwitch from '$lib/components/settings/controls/pref-switch.svelte';\n  import { clearFileCache, eraseAllData } from '$lib/services/app/cache';\n  import { skipCIConfigured } from '$lib/services/backends/git/shared/integration';\n  import { prefs } from '$lib/services/user/prefs.svelte';\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 {\n    /* eslint-disable prefer-const */\n    onChange = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\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.advanced.beta.title')}\n  </h3>\n  <p>\n    {_('prefs.advanced.beta.description')}\n  </p>\n  <div role=\"none\">\n    <PrefSwitch key=\"beta\" label={_('prefs.advanced.beta.switch_label')} defaultValue={false} />\n  </div>\n</section>\n<section>\n  <h3>\n    {_('prefs.advanced.developer_mode.title')}\n  </h3>\n  <p>\n    {_('prefs.advanced.developer_mode.description')}\n  </p>\n  <div role=\"none\">\n    <PrefSwitch\n      key=\"devModeEnabled\"\n      label={_('prefs.advanced.developer_mode.switch_label')}\n      defaultValue={false}\n    />\n  </div>\n</section>\n{#if skipCIConfigured.current}\n  <section>\n    <h3>\n      {_('prefs.advanced.deploy_hook.title')}\n    </h3>\n    <p>\n      {_('prefs.advanced.deploy_hook.description')}\n    </p>\n    <div role=\"none\">\n      <TextInput\n        dir=\"ltr\"\n        bind:value={prefs.deployHookURL}\n        flex\n        ariaLabel={_('prefs.advanced.deploy_hook.url.field_label')}\n        showInlineLabel={true}\n        onchange={() => {\n          onChange?.({\n            message: _(\n              prefs.deployHookURL\n                ? 'prefs.advanced.deploy_hook.url.saved'\n                : 'prefs.advanced.deploy_hook.url.removed',\n            ),\n          });\n        }}\n      />\n    </div>\n    <div role=\"none\">\n      <TextInput\n        dir=\"ltr\"\n        bind:value={prefs.deployHookAuthHeader}\n        flex\n        ariaLabel={_('prefs.advanced.deploy_hook.auth.field_label')}\n        showInlineLabel={true}\n        onchange={() => {\n          onChange?.({\n            message: _(\n              prefs.deployHookAuthHeader\n                ? 'prefs.advanced.deploy_hook.auth.saved'\n                : 'prefs.advanced.deploy_hook.auth.removed',\n            ),\n          });\n        }}\n      />\n    </div>\n  </section>\n{/if}\n<section>\n  <h3>\n    {_('prefs.advanced.clear_data.title')}\n  </h3>\n  <p>\n    {_('prefs.advanced.clear_data.file_cache.description')}\n  </p>\n  <div role=\"none\">\n    <Button\n      variant=\"tertiary\"\n      label={_('prefs.advanced.clear_data.file_cache.button_label')}\n      onclick={() => {\n        showClearCacheDialog = true;\n      }}\n    />\n  </div>\n  <p>\n    {_('prefs.advanced.clear_data.all_data.description')}\n  </p>\n  <div role=\"none\">\n    <Button\n      variant=\"tertiary\"\n      label={_('prefs.advanced.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.advanced.clear_data.file_cache.button_label')}\n  okLabel={_('prefs.advanced.clear_data.file_cache.button_label')}\n  onOk={clearCache}\n>\n  {_('prefs.advanced.clear_data.file_cache.confirmation')}\n</ConfirmationDialog>\n\n<ConfirmationDialog\n  bind:open={showEraseDataDialog}\n  title={_('prefs.advanced.clear_data.all_data.button_label')}\n  okLabel={_('prefs.advanced.clear_data.all_data.button_label')}\n  onOk={eraseData}\n>\n  {_('prefs.advanced.clear_data.all_data.confirmation')}\n</ConfirmationDialog>\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 { SecretInput } from '@sveltia/ui';\n  import { onMount } from 'svelte';\n\n  import { setApiKey } from '$lib/services/user/api-keys';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n\n  /**\n   * @import {\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 {MediaLibraryService | TranslationService} service The service for which the API key\n   * 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 {\n    /* eslint-disable prefer-const */\n    serviceId,\n    service,\n    ariaLabel,\n    onChange = undefined,\n    /* eslint-enable prefer-const */\n  } = $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 = !!apiKey && !!apiKeyPattern && !apiKeyPattern.test(apiKey);\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<SecretInput bind:value flex autocomplete=\"off\" spellcheck=\"false\" {ariaLabel} {onchange} />\n","<script>\n  import { _ } from '@sveltia/i18n';\n\n  import ApiKeyInput from '$lib/components/settings/controls/api-key-input.svelte';\n  import TranslatorSelector from '$lib/components/settings/controls/translator-selector.svelte';\n  import { allTranslationServices } from '$lib/services/integrations/translators';\n  import { makeLink } from '$lib/services/utils/string';\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 {\n    /* eslint-disable prefer-const */\n    onChange = undefined,\n    /* eslint-enable prefer-const */\n  } = $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<section>\n  <h3>{_('prefs.i18n.translators.api_keys.title')}</h3>\n  <p>\n    {@html makeLink(\n      _('prefs.i18n.translators.api_keys.description'),\n      'https://sveltiacms.app/en/docs/integrations/translations',\n    )}\n  </p>\n  {#each Object.entries(allTranslationServices) as [serviceId, service] (serviceId)}\n    {@const label = service.serviceLabel}\n    <section>\n      <h4>{label}</h4>\n      <div role=\"none\">\n        <ApiKeyInput\n          {serviceId}\n          {service}\n          ariaLabel={_('prefs.i18n.translators.field_label', { values: { service: label } })}\n          {onChange}\n        />\n      </div>\n    </section>\n  {/each}\n</section>\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 ApiKeyInput from '$lib/components/settings/controls/api-key-input.svelte';\n  import { allCloudStorageServices } from '$lib/services/integrations/media-libraries/cloud';\n  import {\n    allStockAssetProviders,\n    getStockAssetMediaLibraryOptions,\n  } from '$lib/services/integrations/media-libraries/stock';\n  import { makeLink } from '$lib/services/utils/string';\n\n  /**\n   * @import { MediaLibraryService, SettingsPanelOnChangeArgs } from '$lib/types/private';\n   * @import { StockAssetProviderName } from '$lib/types/public';\n   */\n\n  /**\n   * @typedef {object} Props\n   * @property {(detail: SettingsPanelOnChangeArgs) => void} [onChange] `change` event handler.\n   */\n\n  /** @type {Props} */\n  let {\n    /* eslint-disable prefer-const */\n    onChange = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  const enabledStockAssetProviderEntries = $derived.by(() => {\n    const { providers = [] } = getStockAssetMediaLibraryOptions();\n\n    return /** @type {[StockAssetProviderName, MediaLibraryService][]} */ (\n      Object.entries(allStockAssetProviders)\n    ).filter(([serviceId, { authType }]) => providers.includes(serviceId) && authType !== 'none');\n  });\n\n  /* v8 ignore start -- every built-in service says whether it’s enabled */\n  const enabledCloudServiceEntries = $derived(\n    Object.entries(allCloudStorageServices).filter(\n      ([, { isEnabled, authType }]) => (isEnabled?.() ?? true) && authType !== 'widget',\n    ),\n  );\n  /* v8 ignore stop */\n</script>\n\n<section>\n  <h3>{_('prefs.media.cloud_storage.api_keys.title')}</h3>\n  <p>\n    {@html makeLink(\n      enabledCloudServiceEntries.length\n        ? _('prefs.media.cloud_storage.api_keys.description')\n        : _('prefs.media.cloud_storage.no_services'),\n      'https://sveltiacms.app/en/docs/media',\n    )}\n  </p>\n  {#each enabledCloudServiceEntries as [serviceId, service] (serviceId)}\n    {@const label = service.serviceLabel}\n    <section>\n      <h4>{label}</h4>\n      <div role=\"none\">\n        <ApiKeyInput\n          {serviceId}\n          {service}\n          ariaLabel={_('prefs.media.cloud_storage.field_label', { values: { service: label } })}\n          {onChange}\n        />\n      </div>\n    </section>\n  {/each}\n</section>\n<section>\n  <h3>{_('prefs.media.stock_photos.api_keys.title')}</h3>\n  <p>\n    {@html makeLink(\n      enabledStockAssetProviderEntries.length\n        ? _('prefs.media.stock_photos.api_keys.description')\n        : _('prefs.media.stock_photos.no_services'),\n      'https://sveltiacms.app/en/docs/integrations/stock-photos',\n    )}\n  </p>\n  {#each enabledStockAssetProviderEntries as [serviceId, service] (serviceId)}\n    {@const label = service.serviceLabel}\n    <section>\n      <h4>{label}</h4>\n      <div role=\"none\">\n        <ApiKeyInput\n          {serviceId}\n          {service}\n          ariaLabel={_('prefs.media.stock_photos.field_label', { values: { service: label } })}\n          {onChange}\n        />\n      </div>\n    </section>\n  {/each}\n</section>\n","import AccessibilityPanel from '$lib/components/settings/panels/accessibility-panel.svelte';\nimport AdvancedPanel from '$lib/components/settings/panels/advanced-panel.svelte';\nimport AppearancePanel from '$lib/components/settings/panels/appearance-panel.svelte';\nimport ContentsPanel from '$lib/components/settings/panels/contents-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 { 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. A panel with `enabled: false` is hidden.\n * @type {{ readonly current: { key: string, icon: string, component: Component,\n * enabled?: boolean }[] }}\n */\nexport const panels = createDerivedState(() => [\n  { key: 'appearance', icon: 'palette', component: AppearancePanel },\n  { key: 'language', icon: 'language', component: LanguagePanel },\n  { key: 'contents', icon: 'library_books', component: ContentsPanel },\n  {\n    key: 'i18n',\n    icon: 'translate',\n    component: I18nPanel,\n    enabled: (cmsConfig.current?.i18n?.locales?.length ?? 0) > 1,\n  },\n  { key: 'media', icon: 'photo_library', component: MediaPanel },\n  { key: 'accessibility', icon: 'accessibility_new', component: AccessibilityPanel },\n  { key: 'advanced', icon: 'build', component: AdvancedPanel },\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 {\n    /* eslint-disable prefer-const */\n    Panel,\n    /* eslint-enable prefer-const */\n  } = $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 {\n    /* eslint-disable prefer-const */\n    open = $bindable(false),\n    onClose = undefined,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  let selectedPanel = $state('appearance');\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, enabled = true } (key)}\n        {#if enabled}\n          <Tab\n            label={_(`prefs.${key}.title`)}\n            selected={key === selectedPanel}\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        {/if}\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 { 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 { 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 { 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 {\n    /* eslint-disable prefer-const */\n    menuButton,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  let showPrefsDialog = $state(false);\n\n  const isLocalRepo = $derived(backendName.current === 'local');\n  const isTestRepo = $derived(backendName.current === 'test-repo');\n</script>\n\n<Menu ariaLabel={_('account')}>\n  <MenuItem\n    label={isLocalRepo\n      ? _('working_with_local_repo')\n      : isTestRepo\n        ? _('working_with_test_repo')\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    <MenuItem\n      label={_('cms_config')}\n      onclick={() => {\n        goto('/config', { transitionType: 'forwards' });\n      }}\n    />\n  {/if}\n  <Divider />\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<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    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 } 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. Uploading commits straight to the configured branch, so an Open Authoring contributor or a\n  // user who can’t push to the branch can’t do it either\n  const assetsDisabled = $derived(assetsLocked.current || isReadonly());\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  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 { 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('https://github.com/sveltia/sveltia-cms/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 { 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 {\n    /* eslint-disable prefer-const */\n    menuButton,\n    /* eslint-enable prefer-const */\n  } = $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', 'https://sveltiacms.app/en/docs')}\n    <ReleaseNotesMenuItem />\n    {@render link(\n      'announcements',\n      'https://github.com/sveltia/sveltia-cms/discussions/categories/announcements',\n    )}\n    <Divider />\n    {@render link('report_issue', 'https://github.com/sveltia/sveltia-cms/issues')}\n    {@render link(\n      'share_feedback',\n      'https://github.com/sveltia/sveltia-cms/discussions/categories/ideas',\n    )}\n    {@render link('get_help', 'https://github.com/sveltia/sveltia-cms/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    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    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 { 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 { prefs } from '$lib/services/user/prefs.svelte';\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          <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","// can-promise has a crash in some versions of react native that dont have\n// standard global objects\n// https://github.com/soldair/node-qrcode/issues/157\n\nmodule.exports = function () {\n  return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then\n}\n","let toSJISFunction\nconst CODEWORDS_COUNT = [\n  0, // Not used\n  26, 44, 70, 100, 134, 172, 196, 242, 292, 346,\n  404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,\n  1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,\n  2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706\n]\n\n/**\n * Returns the QR Code size for the specified version\n *\n * @param  {Number} version QR Code version\n * @return {Number}         size of QR code\n */\nexports.getSymbolSize = function getSymbolSize (version) {\n  if (!version) throw new Error('\"version\" cannot be null or undefined')\n  if (version < 1 || version > 40) throw new Error('\"version\" should be in range from 1 to 40')\n  return version * 4 + 17\n}\n\n/**\n * Returns the total number of codewords used to store data and EC information.\n *\n * @param  {Number} version QR Code version\n * @return {Number}         Data length in bits\n */\nexports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {\n  return CODEWORDS_COUNT[version]\n}\n\n/**\n * Encode data with Bose-Chaudhuri-Hocquenghem\n *\n * @param  {Number} data Value to encode\n * @return {Number}      Encoded value\n */\nexports.getBCHDigit = function (data) {\n  let digit = 0\n\n  while (data !== 0) {\n    digit++\n    data >>>= 1\n  }\n\n  return digit\n}\n\nexports.setToSJISFunction = function setToSJISFunction (f) {\n  if (typeof f !== 'function') {\n    throw new Error('\"toSJISFunc\" is not a valid function.')\n  }\n\n  toSJISFunction = f\n}\n\nexports.isKanjiModeEnabled = function () {\n  return typeof toSJISFunction !== 'undefined'\n}\n\nexports.toSJIS = function toSJIS (kanji) {\n  return toSJISFunction(kanji)\n}\n","exports.L = { bit: 1 }\nexports.M = { bit: 0 }\nexports.Q = { bit: 3 }\nexports.H = { bit: 2 }\n\nfunction fromString (string) {\n  if (typeof string !== 'string') {\n    throw new Error('Param is not a string')\n  }\n\n  const lcStr = string.toLowerCase()\n\n  switch (lcStr) {\n    case 'l':\n    case 'low':\n      return exports.L\n\n    case 'm':\n    case 'medium':\n      return exports.M\n\n    case 'q':\n    case 'quartile':\n      return exports.Q\n\n    case 'h':\n    case 'high':\n      return exports.H\n\n    default:\n      throw new Error('Unknown EC Level: ' + string)\n  }\n}\n\nexports.isValid = function isValid (level) {\n  return level && typeof level.bit !== 'undefined' &&\n    level.bit >= 0 && level.bit < 4\n}\n\nexports.from = function from (value, defaultValue) {\n  if (exports.isValid(value)) {\n    return value\n  }\n\n  try {\n    return fromString(value)\n  } catch (e) {\n    return defaultValue\n  }\n}\n","function BitBuffer () {\n  this.buffer = []\n  this.length = 0\n}\n\nBitBuffer.prototype = {\n\n  get: function (index) {\n    const bufIndex = Math.floor(index / 8)\n    return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1\n  },\n\n  put: function (num, length) {\n    for (let i = 0; i < length; i++) {\n      this.putBit(((num >>> (length - i - 1)) & 1) === 1)\n    }\n  },\n\n  getLengthInBits: function () {\n    return this.length\n  },\n\n  putBit: function (bit) {\n    const bufIndex = Math.floor(this.length / 8)\n    if (this.buffer.length <= bufIndex) {\n      this.buffer.push(0)\n    }\n\n    if (bit) {\n      this.buffer[bufIndex] |= (0x80 >>> (this.length % 8))\n    }\n\n    this.length++\n  }\n}\n\nmodule.exports = BitBuffer\n","/**\n * Helper class to handle QR Code symbol modules\n *\n * @param {Number} size Symbol size\n */\nfunction BitMatrix (size) {\n  if (!size || size < 1) {\n    throw new Error('BitMatrix size must be defined and greater than 0')\n  }\n\n  this.size = size\n  this.data = new Uint8Array(size * size)\n  this.reservedBit = new Uint8Array(size * size)\n}\n\n/**\n * Set bit value at specified location\n * If reserved flag is set, this bit will be ignored during masking process\n *\n * @param {Number}  row\n * @param {Number}  col\n * @param {Boolean} value\n * @param {Boolean} reserved\n */\nBitMatrix.prototype.set = function (row, col, value, reserved) {\n  const index = row * this.size + col\n  this.data[index] = value\n  if (reserved) this.reservedBit[index] = true\n}\n\n/**\n * Returns bit value at specified location\n *\n * @param  {Number}  row\n * @param  {Number}  col\n * @return {Boolean}\n */\nBitMatrix.prototype.get = function (row, col) {\n  return this.data[row * this.size + col]\n}\n\n/**\n * Applies xor operator at specified location\n * (used during masking process)\n *\n * @param {Number}  row\n * @param {Number}  col\n * @param {Boolean} value\n */\nBitMatrix.prototype.xor = function (row, col, value) {\n  this.data[row * this.size + col] ^= value\n}\n\n/**\n * Check if bit at specified location is reserved\n *\n * @param {Number}   row\n * @param {Number}   col\n * @return {Boolean}\n */\nBitMatrix.prototype.isReserved = function (row, col) {\n  return this.reservedBit[row * this.size + col]\n}\n\nmodule.exports = BitMatrix\n","/**\n * Alignment pattern are fixed reference pattern in defined positions\n * in a matrix symbology, which enables the decode software to re-synchronise\n * the coordinate mapping of the image modules in the event of moderate amounts\n * of distortion of the image.\n *\n * Alignment patterns are present only in QR Code symbols of version 2 or larger\n * and their number depends on the symbol version.\n */\n\nconst getSymbolSize = require('./utils').getSymbolSize\n\n/**\n * Calculate the row/column coordinates of the center module of each alignment pattern\n * for the specified QR Code version.\n *\n * The alignment patterns are positioned symmetrically on either side of the diagonal\n * running from the top left corner of the symbol to the bottom right corner.\n *\n * Since positions are simmetrical only half of the coordinates are returned.\n * Each item of the array will represent in turn the x and y coordinate.\n * @see {@link getPositions}\n *\n * @param  {Number} version QR Code version\n * @return {Array}          Array of coordinate\n */\nexports.getRowColCoords = function getRowColCoords (version) {\n  if (version === 1) return []\n\n  const posCount = Math.floor(version / 7) + 2\n  const size = getSymbolSize(version)\n  const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2\n  const positions = [size - 7] // Last coord is always (size - 7)\n\n  for (let i = 1; i < posCount - 1; i++) {\n    positions[i] = positions[i - 1] - intervals\n  }\n\n  positions.push(6) // First coord is always 6\n\n  return positions.reverse()\n}\n\n/**\n * Returns an array containing the positions of each alignment pattern.\n * Each array's element represent the center point of the pattern as (x, y) coordinates\n *\n * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}\n * and filtering out the items that overlaps with finder pattern\n *\n * @example\n * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.\n * The alignment patterns, therefore, are to be centered on (row, column)\n * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).\n * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns\n * and are not therefore used for alignment patterns.\n *\n * let pos = getPositions(7)\n * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]\n *\n * @param  {Number} version QR Code version\n * @return {Array}          Array of coordinates\n */\nexports.getPositions = function getPositions (version) {\n  const coords = []\n  const pos = exports.getRowColCoords(version)\n  const posLength = pos.length\n\n  for (let i = 0; i < posLength; i++) {\n    for (let j = 0; j < posLength; j++) {\n      // Skip if position is occupied by finder patterns\n      if ((i === 0 && j === 0) || // top-left\n          (i === 0 && j === posLength - 1) || // bottom-left\n          (i === posLength - 1 && j === 0)) { // top-right\n        continue\n      }\n\n      coords.push([pos[i], pos[j]])\n    }\n  }\n\n  return coords\n}\n","const getSymbolSize = require('./utils').getSymbolSize\nconst FINDER_PATTERN_SIZE = 7\n\n/**\n * Returns an array containing the positions of each finder pattern.\n * Each array's element represent the top-left point of the pattern as (x, y) coordinates\n *\n * @param  {Number} version QR Code version\n * @return {Array}          Array of coordinates\n */\nexports.getPositions = function getPositions (version) {\n  const size = getSymbolSize(version)\n\n  return [\n    // top-left\n    [0, 0],\n    // top-right\n    [size - FINDER_PATTERN_SIZE, 0],\n    // bottom-left\n    [0, size - FINDER_PATTERN_SIZE]\n  ]\n}\n","/**\n * Data mask pattern reference\n * @type {Object}\n */\nexports.Patterns = {\n  PATTERN000: 0,\n  PATTERN001: 1,\n  PATTERN010: 2,\n  PATTERN011: 3,\n  PATTERN100: 4,\n  PATTERN101: 5,\n  PATTERN110: 6,\n  PATTERN111: 7\n}\n\n/**\n * Weighted penalty scores for the undesirable features\n * @type {Object}\n */\nconst PenaltyScores = {\n  N1: 3,\n  N2: 3,\n  N3: 40,\n  N4: 10\n}\n\n/**\n * Check if mask pattern value is valid\n *\n * @param  {Number}  mask    Mask pattern\n * @return {Boolean}         true if valid, false otherwise\n */\nexports.isValid = function isValid (mask) {\n  return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7\n}\n\n/**\n * Returns mask pattern from a value.\n * If value is not valid, returns undefined\n *\n * @param  {Number|String} value        Mask pattern value\n * @return {Number}                     Valid mask pattern or undefined\n */\nexports.from = function from (value) {\n  return exports.isValid(value) ? parseInt(value, 10) : undefined\n}\n\n/**\n* Find adjacent modules in row/column with the same color\n* and assign a penalty value.\n*\n* Points: N1 + i\n* i is the amount by which the number of adjacent modules of the same color exceeds 5\n*/\nexports.getPenaltyN1 = function getPenaltyN1 (data) {\n  const size = data.size\n  let points = 0\n  let sameCountCol = 0\n  let sameCountRow = 0\n  let lastCol = null\n  let lastRow = null\n\n  for (let row = 0; row < size; row++) {\n    sameCountCol = sameCountRow = 0\n    lastCol = lastRow = null\n\n    for (let col = 0; col < size; col++) {\n      let module = data.get(row, col)\n      if (module === lastCol) {\n        sameCountCol++\n      } else {\n        if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)\n        lastCol = module\n        sameCountCol = 1\n      }\n\n      module = data.get(col, row)\n      if (module === lastRow) {\n        sameCountRow++\n      } else {\n        if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)\n        lastRow = module\n        sameCountRow = 1\n      }\n    }\n\n    if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)\n    if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)\n  }\n\n  return points\n}\n\n/**\n * Find 2x2 blocks with the same color and assign a penalty value\n *\n * Points: N2 * (m - 1) * (n - 1)\n */\nexports.getPenaltyN2 = function getPenaltyN2 (data) {\n  const size = data.size\n  let points = 0\n\n  for (let row = 0; row < size - 1; row++) {\n    for (let col = 0; col < size - 1; col++) {\n      const last = data.get(row, col) +\n        data.get(row, col + 1) +\n        data.get(row + 1, col) +\n        data.get(row + 1, col + 1)\n\n      if (last === 4 || last === 0) points++\n    }\n  }\n\n  return points * PenaltyScores.N2\n}\n\n/**\n * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,\n * preceded or followed by light area 4 modules wide\n *\n * Points: N3 * number of pattern found\n */\nexports.getPenaltyN3 = function getPenaltyN3 (data) {\n  const size = data.size\n  let points = 0\n  let bitsCol = 0\n  let bitsRow = 0\n\n  for (let row = 0; row < size; row++) {\n    bitsCol = bitsRow = 0\n    for (let col = 0; col < size; col++) {\n      bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col)\n      if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++\n\n      bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row)\n      if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++\n    }\n  }\n\n  return points * PenaltyScores.N3\n}\n\n/**\n * Calculate proportion of dark modules in entire symbol\n *\n * Points: N4 * k\n *\n * k is the rating of the deviation of the proportion of dark modules\n * in the symbol from 50% in steps of 5%\n */\nexports.getPenaltyN4 = function getPenaltyN4 (data) {\n  let darkCount = 0\n  const modulesCount = data.data.length\n\n  for (let i = 0; i < modulesCount; i++) darkCount += data.data[i]\n\n  const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10)\n\n  return k * PenaltyScores.N4\n}\n\n/**\n * Return mask value at given position\n *\n * @param  {Number} maskPattern Pattern reference value\n * @param  {Number} i           Row\n * @param  {Number} j           Column\n * @return {Boolean}            Mask value\n */\nfunction getMaskAt (maskPattern, i, j) {\n  switch (maskPattern) {\n    case exports.Patterns.PATTERN000: return (i + j) % 2 === 0\n    case exports.Patterns.PATTERN001: return i % 2 === 0\n    case exports.Patterns.PATTERN010: return j % 3 === 0\n    case exports.Patterns.PATTERN011: return (i + j) % 3 === 0\n    case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0\n    case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0\n    case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0\n    case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0\n\n    default: throw new Error('bad maskPattern:' + maskPattern)\n  }\n}\n\n/**\n * Apply a mask pattern to a BitMatrix\n *\n * @param  {Number}    pattern Pattern reference number\n * @param  {BitMatrix} data    BitMatrix data\n */\nexports.applyMask = function applyMask (pattern, data) {\n  const size = data.size\n\n  for (let col = 0; col < size; col++) {\n    for (let row = 0; row < size; row++) {\n      if (data.isReserved(row, col)) continue\n      data.xor(row, col, getMaskAt(pattern, row, col))\n    }\n  }\n}\n\n/**\n * Returns the best mask pattern for data\n *\n * @param  {BitMatrix} data\n * @return {Number} Mask pattern reference number\n */\nexports.getBestMask = function getBestMask (data, setupFormatFunc) {\n  const numPatterns = Object.keys(exports.Patterns).length\n  let bestPattern = 0\n  let lowerPenalty = Infinity\n\n  for (let p = 0; p < numPatterns; p++) {\n    setupFormatFunc(p)\n    exports.applyMask(p, data)\n\n    // Calculate penalty\n    const penalty =\n      exports.getPenaltyN1(data) +\n      exports.getPenaltyN2(data) +\n      exports.getPenaltyN3(data) +\n      exports.getPenaltyN4(data)\n\n    // Undo previously applied mask\n    exports.applyMask(p, data)\n\n    if (penalty < lowerPenalty) {\n      lowerPenalty = penalty\n      bestPattern = p\n    }\n  }\n\n  return bestPattern\n}\n","const ECLevel = require('./error-correction-level')\r\n\r\nconst EC_BLOCKS_TABLE = [\r\n// L  M  Q  H\r\n  1, 1, 1, 1,\r\n  1, 1, 1, 1,\r\n  1, 1, 2, 2,\r\n  1, 2, 2, 4,\r\n  1, 2, 4, 4,\r\n  2, 4, 4, 4,\r\n  2, 4, 6, 5,\r\n  2, 4, 6, 6,\r\n  2, 5, 8, 8,\r\n  4, 5, 8, 8,\r\n  4, 5, 8, 11,\r\n  4, 8, 10, 11,\r\n  4, 9, 12, 16,\r\n  4, 9, 16, 16,\r\n  6, 10, 12, 18,\r\n  6, 10, 17, 16,\r\n  6, 11, 16, 19,\r\n  6, 13, 18, 21,\r\n  7, 14, 21, 25,\r\n  8, 16, 20, 25,\r\n  8, 17, 23, 25,\r\n  9, 17, 23, 34,\r\n  9, 18, 25, 30,\r\n  10, 20, 27, 32,\r\n  12, 21, 29, 35,\r\n  12, 23, 34, 37,\r\n  12, 25, 34, 40,\r\n  13, 26, 35, 42,\r\n  14, 28, 38, 45,\r\n  15, 29, 40, 48,\r\n  16, 31, 43, 51,\r\n  17, 33, 45, 54,\r\n  18, 35, 48, 57,\r\n  19, 37, 51, 60,\r\n  19, 38, 53, 63,\r\n  20, 40, 56, 66,\r\n  21, 43, 59, 70,\r\n  22, 45, 62, 74,\r\n  24, 47, 65, 77,\r\n  25, 49, 68, 81\r\n]\r\n\r\nconst EC_CODEWORDS_TABLE = [\r\n// L  M  Q  H\r\n  7, 10, 13, 17,\r\n  10, 16, 22, 28,\r\n  15, 26, 36, 44,\r\n  20, 36, 52, 64,\r\n  26, 48, 72, 88,\r\n  36, 64, 96, 112,\r\n  40, 72, 108, 130,\r\n  48, 88, 132, 156,\r\n  60, 110, 160, 192,\r\n  72, 130, 192, 224,\r\n  80, 150, 224, 264,\r\n  96, 176, 260, 308,\r\n  104, 198, 288, 352,\r\n  120, 216, 320, 384,\r\n  132, 240, 360, 432,\r\n  144, 280, 408, 480,\r\n  168, 308, 448, 532,\r\n  180, 338, 504, 588,\r\n  196, 364, 546, 650,\r\n  224, 416, 600, 700,\r\n  224, 442, 644, 750,\r\n  252, 476, 690, 816,\r\n  270, 504, 750, 900,\r\n  300, 560, 810, 960,\r\n  312, 588, 870, 1050,\r\n  336, 644, 952, 1110,\r\n  360, 700, 1020, 1200,\r\n  390, 728, 1050, 1260,\r\n  420, 784, 1140, 1350,\r\n  450, 812, 1200, 1440,\r\n  480, 868, 1290, 1530,\r\n  510, 924, 1350, 1620,\r\n  540, 980, 1440, 1710,\r\n  570, 1036, 1530, 1800,\r\n  570, 1064, 1590, 1890,\r\n  600, 1120, 1680, 1980,\r\n  630, 1204, 1770, 2100,\r\n  660, 1260, 1860, 2220,\r\n  720, 1316, 1950, 2310,\r\n  750, 1372, 2040, 2430\r\n]\r\n\r\n/**\r\n * Returns the number of error correction block that the QR Code should contain\r\n * for the specified version and error correction level.\r\n *\r\n * @param  {Number} version              QR Code version\r\n * @param  {Number} errorCorrectionLevel Error correction level\r\n * @return {Number}                      Number of error correction blocks\r\n */\r\nexports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {\r\n  switch (errorCorrectionLevel) {\r\n    case ECLevel.L:\r\n      return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]\r\n    case ECLevel.M:\r\n      return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]\r\n    case ECLevel.Q:\r\n      return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]\r\n    case ECLevel.H:\r\n      return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]\r\n    default:\r\n      return undefined\r\n  }\r\n}\r\n\r\n/**\r\n * Returns the number of error correction codewords to use for the specified\r\n * version and error correction level.\r\n *\r\n * @param  {Number} version              QR Code version\r\n * @param  {Number} errorCorrectionLevel Error correction level\r\n * @return {Number}                      Number of error correction codewords\r\n */\r\nexports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {\r\n  switch (errorCorrectionLevel) {\r\n    case ECLevel.L:\r\n      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]\r\n    case ECLevel.M:\r\n      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]\r\n    case ECLevel.Q:\r\n      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]\r\n    case ECLevel.H:\r\n      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]\r\n    default:\r\n      return undefined\r\n  }\r\n}\r\n","const EXP_TABLE = new Uint8Array(512)\nconst LOG_TABLE = new Uint8Array(256)\n/**\n * Precompute the log and anti-log tables for faster computation later\n *\n * For each possible value in the galois field 2^8, we will pre-compute\n * the logarithm and anti-logarithm (exponential) of this value\n *\n * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}\n */\n;(function initTables () {\n  let x = 1\n  for (let i = 0; i < 255; i++) {\n    EXP_TABLE[i] = x\n    LOG_TABLE[x] = i\n\n    x <<= 1 // multiply by 2\n\n    // The QR code specification says to use byte-wise modulo 100011101 arithmetic.\n    // This means that when a number is 256 or larger, it should be XORed with 0x11D.\n    if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)\n      x ^= 0x11D\n    }\n  }\n\n  // Optimization: double the size of the anti-log table so that we don't need to mod 255 to\n  // stay inside the bounds (because we will mainly use this table for the multiplication of\n  // two GF numbers, no more).\n  // @see {@link mul}\n  for (let i = 255; i < 512; i++) {\n    EXP_TABLE[i] = EXP_TABLE[i - 255]\n  }\n}())\n\n/**\n * Returns log value of n inside Galois Field\n *\n * @param  {Number} n\n * @return {Number}\n */\nexports.log = function log (n) {\n  if (n < 1) throw new Error('log(' + n + ')')\n  return LOG_TABLE[n]\n}\n\n/**\n * Returns anti-log value of n inside Galois Field\n *\n * @param  {Number} n\n * @return {Number}\n */\nexports.exp = function exp (n) {\n  return EXP_TABLE[n]\n}\n\n/**\n * Multiplies two number inside Galois Field\n *\n * @param  {Number} x\n * @param  {Number} y\n * @return {Number}\n */\nexports.mul = function mul (x, y) {\n  if (x === 0 || y === 0) return 0\n\n  // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized\n  // @see {@link initTables}\n  return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]\n}\n","const GF = require('./galois-field')\n\n/**\n * Multiplies two polynomials inside Galois Field\n *\n * @param  {Uint8Array} p1 Polynomial\n * @param  {Uint8Array} p2 Polynomial\n * @return {Uint8Array}    Product of p1 and p2\n */\nexports.mul = function mul (p1, p2) {\n  const coeff = new Uint8Array(p1.length + p2.length - 1)\n\n  for (let i = 0; i < p1.length; i++) {\n    for (let j = 0; j < p2.length; j++) {\n      coeff[i + j] ^= GF.mul(p1[i], p2[j])\n    }\n  }\n\n  return coeff\n}\n\n/**\n * Calculate the remainder of polynomials division\n *\n * @param  {Uint8Array} divident Polynomial\n * @param  {Uint8Array} divisor  Polynomial\n * @return {Uint8Array}          Remainder\n */\nexports.mod = function mod (divident, divisor) {\n  let result = new Uint8Array(divident)\n\n  while ((result.length - divisor.length) >= 0) {\n    const coeff = result[0]\n\n    for (let i = 0; i < divisor.length; i++) {\n      result[i] ^= GF.mul(divisor[i], coeff)\n    }\n\n    // remove all zeros from buffer head\n    let offset = 0\n    while (offset < result.length && result[offset] === 0) offset++\n    result = result.slice(offset)\n  }\n\n  return result\n}\n\n/**\n * Generate an irreducible generator polynomial of specified degree\n * (used by Reed-Solomon encoder)\n *\n * @param  {Number} degree Degree of the generator polynomial\n * @return {Uint8Array}    Buffer containing polynomial coefficients\n */\nexports.generateECPolynomial = function generateECPolynomial (degree) {\n  let poly = new Uint8Array([1])\n  for (let i = 0; i < degree; i++) {\n    poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]))\n  }\n\n  return poly\n}\n","const Polynomial = require('./polynomial')\n\nfunction ReedSolomonEncoder (degree) {\n  this.genPoly = undefined\n  this.degree = degree\n\n  if (this.degree) this.initialize(this.degree)\n}\n\n/**\n * Initialize the encoder.\n * The input param should correspond to the number of error correction codewords.\n *\n * @param  {Number} degree\n */\nReedSolomonEncoder.prototype.initialize = function initialize (degree) {\n  // create an irreducible generator polynomial\n  this.degree = degree\n  this.genPoly = Polynomial.generateECPolynomial(this.degree)\n}\n\n/**\n * Encodes a chunk of data\n *\n * @param  {Uint8Array} data Buffer containing input data\n * @return {Uint8Array}      Buffer containing encoded data\n */\nReedSolomonEncoder.prototype.encode = function encode (data) {\n  if (!this.genPoly) {\n    throw new Error('Encoder not initialized')\n  }\n\n  // Calculate EC for this data block\n  // extends data size to data+genPoly size\n  const paddedData = new Uint8Array(data.length + this.degree)\n  paddedData.set(data)\n\n  // The error correction codewords are the remainder after dividing the data codewords\n  // by a generator polynomial\n  const remainder = Polynomial.mod(paddedData, this.genPoly)\n\n  // return EC data blocks (last n byte, where n is the degree of genPoly)\n  // If coefficients number in remainder are less than genPoly degree,\n  // pad with 0s to the left to reach the needed number of coefficients\n  const start = this.degree - remainder.length\n  if (start > 0) {\n    const buff = new Uint8Array(this.degree)\n    buff.set(remainder, start)\n\n    return buff\n  }\n\n  return remainder\n}\n\nmodule.exports = ReedSolomonEncoder\n","/**\n * Check if QR Code version is valid\n *\n * @param  {Number}  version QR Code version\n * @return {Boolean}         true if valid version, false otherwise\n */\nexports.isValid = function isValid (version) {\n  return !isNaN(version) && version >= 1 && version <= 40\n}\n","const numeric = '[0-9]+'\nconst alphanumeric = '[A-Z $%*+\\\\-./:]+'\nlet kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +\n  '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +\n  '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +\n  '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+'\nkanji = kanji.replace(/u/g, '\\\\u')\n\nconst byte = '(?:(?![A-Z0-9 $%*+\\\\-./:]|' + kanji + ')(?:.|[\\r\\n]))+'\n\nexports.KANJI = new RegExp(kanji, 'g')\nexports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\\\-./:]+', 'g')\nexports.BYTE = new RegExp(byte, 'g')\nexports.NUMERIC = new RegExp(numeric, 'g')\nexports.ALPHANUMERIC = new RegExp(alphanumeric, 'g')\n\nconst TEST_KANJI = new RegExp('^' + kanji + '$')\nconst TEST_NUMERIC = new RegExp('^' + numeric + '$')\nconst TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\\\-./:]+$')\n\nexports.testKanji = function testKanji (str) {\n  return TEST_KANJI.test(str)\n}\n\nexports.testNumeric = function testNumeric (str) {\n  return TEST_NUMERIC.test(str)\n}\n\nexports.testAlphanumeric = function testAlphanumeric (str) {\n  return TEST_ALPHANUMERIC.test(str)\n}\n","const VersionCheck = require('./version-check')\nconst Regex = require('./regex')\n\n/**\n * Numeric mode encodes data from the decimal digit set (0 - 9)\n * (byte values 30HEX to 39HEX).\n * Normally, 3 data characters are represented by 10 bits.\n *\n * @type {Object}\n */\nexports.NUMERIC = {\n  id: 'Numeric',\n  bit: 1 << 0,\n  ccBits: [10, 12, 14]\n}\n\n/**\n * Alphanumeric mode encodes data from a set of 45 characters,\n * i.e. 10 numeric digits (0 - 9),\n *      26 alphabetic characters (A - Z),\n *   and 9 symbols (SP, $, %, *, +, -, ., /, :).\n * Normally, two input characters are represented by 11 bits.\n *\n * @type {Object}\n */\nexports.ALPHANUMERIC = {\n  id: 'Alphanumeric',\n  bit: 1 << 1,\n  ccBits: [9, 11, 13]\n}\n\n/**\n * In byte mode, data is encoded at 8 bits per character.\n *\n * @type {Object}\n */\nexports.BYTE = {\n  id: 'Byte',\n  bit: 1 << 2,\n  ccBits: [8, 16, 16]\n}\n\n/**\n * The Kanji mode efficiently encodes Kanji characters in accordance with\n * the Shift JIS system based on JIS X 0208.\n * The Shift JIS values are shifted from the JIS X 0208 values.\n * JIS X 0208 gives details of the shift coded representation.\n * Each two-byte character value is compacted to a 13-bit binary codeword.\n *\n * @type {Object}\n */\nexports.KANJI = {\n  id: 'Kanji',\n  bit: 1 << 3,\n  ccBits: [8, 10, 12]\n}\n\n/**\n * Mixed mode will contain a sequences of data in a combination of any of\n * the modes described above\n *\n * @type {Object}\n */\nexports.MIXED = {\n  bit: -1\n}\n\n/**\n * Returns the number of bits needed to store the data length\n * according to QR Code specifications.\n *\n * @param  {Mode}   mode    Data mode\n * @param  {Number} version QR Code version\n * @return {Number}         Number of bits\n */\nexports.getCharCountIndicator = function getCharCountIndicator (mode, version) {\n  if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)\n\n  if (!VersionCheck.isValid(version)) {\n    throw new Error('Invalid version: ' + version)\n  }\n\n  if (version >= 1 && version < 10) return mode.ccBits[0]\n  else if (version < 27) return mode.ccBits[1]\n  return mode.ccBits[2]\n}\n\n/**\n * Returns the most efficient mode to store the specified data\n *\n * @param  {String} dataStr Input data string\n * @return {Mode}           Best mode\n */\nexports.getBestModeForData = function getBestModeForData (dataStr) {\n  if (Regex.testNumeric(dataStr)) return exports.NUMERIC\n  else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC\n  else if (Regex.testKanji(dataStr)) return exports.KANJI\n  else return exports.BYTE\n}\n\n/**\n * Return mode name as string\n *\n * @param {Mode} mode Mode object\n * @returns {String}  Mode name\n */\nexports.toString = function toString (mode) {\n  if (mode && mode.id) return mode.id\n  throw new Error('Invalid mode')\n}\n\n/**\n * Check if input param is a valid mode object\n *\n * @param   {Mode}    mode Mode object\n * @returns {Boolean} True if valid mode, false otherwise\n */\nexports.isValid = function isValid (mode) {\n  return mode && mode.bit && mode.ccBits\n}\n\n/**\n * Get mode object from its name\n *\n * @param   {String} string Mode name\n * @returns {Mode}          Mode object\n */\nfunction fromString (string) {\n  if (typeof string !== 'string') {\n    throw new Error('Param is not a string')\n  }\n\n  const lcStr = string.toLowerCase()\n\n  switch (lcStr) {\n    case 'numeric':\n      return exports.NUMERIC\n    case 'alphanumeric':\n      return exports.ALPHANUMERIC\n    case 'kanji':\n      return exports.KANJI\n    case 'byte':\n      return exports.BYTE\n    default:\n      throw new Error('Unknown mode: ' + string)\n  }\n}\n\n/**\n * Returns mode from a value.\n * If value is not a valid mode, returns defaultValue\n *\n * @param  {Mode|String} value        Encoding mode\n * @param  {Mode}        defaultValue Fallback value\n * @return {Mode}                     Encoding mode\n */\nexports.from = function from (value, defaultValue) {\n  if (exports.isValid(value)) {\n    return value\n  }\n\n  try {\n    return fromString(value)\n  } catch (e) {\n    return defaultValue\n  }\n}\n","const Utils = require('./utils')\nconst ECCode = require('./error-correction-code')\nconst ECLevel = require('./error-correction-level')\nconst Mode = require('./mode')\nconst VersionCheck = require('./version-check')\n\n// Generator polynomial used to encode version information\nconst G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)\nconst G18_BCH = Utils.getBCHDigit(G18)\n\nfunction getBestVersionForDataLength (mode, length, errorCorrectionLevel) {\n  for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {\n    if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {\n      return currentVersion\n    }\n  }\n\n  return undefined\n}\n\nfunction getReservedBitsCount (mode, version) {\n  // Character count indicator + mode indicator bits\n  return Mode.getCharCountIndicator(mode, version) + 4\n}\n\nfunction getTotalBitsFromDataArray (segments, version) {\n  let totalBits = 0\n\n  segments.forEach(function (data) {\n    const reservedBits = getReservedBitsCount(data.mode, version)\n    totalBits += reservedBits + data.getBitsLength()\n  })\n\n  return totalBits\n}\n\nfunction getBestVersionForMixedData (segments, errorCorrectionLevel) {\n  for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {\n    const length = getTotalBitsFromDataArray(segments, currentVersion)\n    if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {\n      return currentVersion\n    }\n  }\n\n  return undefined\n}\n\n/**\n * Returns version number from a value.\n * If value is not a valid version, returns defaultValue\n *\n * @param  {Number|String} value        QR Code version\n * @param  {Number}        defaultValue Fallback value\n * @return {Number}                     QR Code version number\n */\nexports.from = function from (value, defaultValue) {\n  if (VersionCheck.isValid(value)) {\n    return parseInt(value, 10)\n  }\n\n  return defaultValue\n}\n\n/**\n * Returns how much data can be stored with the specified QR code version\n * and error correction level\n *\n * @param  {Number} version              QR Code version (1-40)\n * @param  {Number} errorCorrectionLevel Error correction level\n * @param  {Mode}   mode                 Data mode\n * @return {Number}                      Quantity of storable data\n */\nexports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {\n  if (!VersionCheck.isValid(version)) {\n    throw new Error('Invalid QR Code version')\n  }\n\n  // Use Byte mode as default\n  if (typeof mode === 'undefined') mode = Mode.BYTE\n\n  // Total codewords for this QR code version (Data + Error correction)\n  const totalCodewords = Utils.getSymbolTotalCodewords(version)\n\n  // Total number of error correction codewords\n  const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)\n\n  // Total number of data codewords\n  const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8\n\n  if (mode === Mode.MIXED) return dataTotalCodewordsBits\n\n  const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version)\n\n  // Return max number of storable codewords\n  switch (mode) {\n    case Mode.NUMERIC:\n      return Math.floor((usableBits / 10) * 3)\n\n    case Mode.ALPHANUMERIC:\n      return Math.floor((usableBits / 11) * 2)\n\n    case Mode.KANJI:\n      return Math.floor(usableBits / 13)\n\n    case Mode.BYTE:\n    default:\n      return Math.floor(usableBits / 8)\n  }\n}\n\n/**\n * Returns the minimum version needed to contain the amount of data\n *\n * @param  {Segment} data                    Segment of data\n * @param  {Number} [errorCorrectionLevel=H] Error correction level\n * @param  {Mode} mode                       Data mode\n * @return {Number}                          QR Code version\n */\nexports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {\n  let seg\n\n  const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M)\n\n  if (Array.isArray(data)) {\n    if (data.length > 1) {\n      return getBestVersionForMixedData(data, ecl)\n    }\n\n    if (data.length === 0) {\n      return 1\n    }\n\n    seg = data[0]\n  } else {\n    seg = data\n  }\n\n  return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)\n}\n\n/**\n * Returns version information with relative error correction bits\n *\n * The version information is included in QR Code symbols of version 7 or larger.\n * It consists of an 18-bit sequence containing 6 data bits,\n * with 12 error correction bits calculated using the (18, 6) Golay code.\n *\n * @param  {Number} version QR Code version\n * @return {Number}         Encoded version info bits\n */\nexports.getEncodedBits = function getEncodedBits (version) {\n  if (!VersionCheck.isValid(version) || version < 7) {\n    throw new Error('Invalid QR Code version')\n  }\n\n  let d = version << 12\n\n  while (Utils.getBCHDigit(d) - G18_BCH >= 0) {\n    d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH))\n  }\n\n  return (version << 12) | d\n}\n","const Utils = require('./utils')\n\nconst G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)\nconst G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)\nconst G15_BCH = Utils.getBCHDigit(G15)\n\n/**\n * Returns format information with relative error correction bits\n *\n * The format information is a 15-bit sequence containing 5 data bits,\n * with 10 error correction bits calculated using the (15, 5) BCH code.\n *\n * @param  {Number} errorCorrectionLevel Error correction level\n * @param  {Number} mask                 Mask pattern\n * @return {Number}                      Encoded format information bits\n */\nexports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {\n  const data = ((errorCorrectionLevel.bit << 3) | mask)\n  let d = data << 10\n\n  while (Utils.getBCHDigit(d) - G15_BCH >= 0) {\n    d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH))\n  }\n\n  // xor final data with mask pattern in order to ensure that\n  // no combination of Error Correction Level and data mask pattern\n  // will result in an all-zero data string\n  return ((data << 10) | d) ^ G15_MASK\n}\n","const Mode = require('./mode')\n\nfunction NumericData (data) {\n  this.mode = Mode.NUMERIC\n  this.data = data.toString()\n}\n\nNumericData.getBitsLength = function getBitsLength (length) {\n  return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)\n}\n\nNumericData.prototype.getLength = function getLength () {\n  return this.data.length\n}\n\nNumericData.prototype.getBitsLength = function getBitsLength () {\n  return NumericData.getBitsLength(this.data.length)\n}\n\nNumericData.prototype.write = function write (bitBuffer) {\n  let i, group, value\n\n  // The input data string is divided into groups of three digits,\n  // and each group is converted to its 10-bit binary equivalent.\n  for (i = 0; i + 3 <= this.data.length; i += 3) {\n    group = this.data.substr(i, 3)\n    value = parseInt(group, 10)\n\n    bitBuffer.put(value, 10)\n  }\n\n  // If the number of input digits is not an exact multiple of three,\n  // the final one or two digits are converted to 4 or 7 bits respectively.\n  const remainingNum = this.data.length - i\n  if (remainingNum > 0) {\n    group = this.data.substr(i)\n    value = parseInt(group, 10)\n\n    bitBuffer.put(value, remainingNum * 3 + 1)\n  }\n}\n\nmodule.exports = NumericData\n","const Mode = require('./mode')\n\n/**\n * Array of characters available in alphanumeric mode\n *\n * As per QR Code specification, to each character\n * is assigned a value from 0 to 44 which in this case coincides\n * with the array index\n *\n * @type {Array}\n */\nconst ALPHA_NUM_CHARS = [\n  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n  'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',\n  'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n  ' ', '$', '%', '*', '+', '-', '.', '/', ':'\n]\n\nfunction AlphanumericData (data) {\n  this.mode = Mode.ALPHANUMERIC\n  this.data = data\n}\n\nAlphanumericData.getBitsLength = function getBitsLength (length) {\n  return 11 * Math.floor(length / 2) + 6 * (length % 2)\n}\n\nAlphanumericData.prototype.getLength = function getLength () {\n  return this.data.length\n}\n\nAlphanumericData.prototype.getBitsLength = function getBitsLength () {\n  return AlphanumericData.getBitsLength(this.data.length)\n}\n\nAlphanumericData.prototype.write = function write (bitBuffer) {\n  let i\n\n  // Input data characters are divided into groups of two characters\n  // and encoded as 11-bit binary codes.\n  for (i = 0; i + 2 <= this.data.length; i += 2) {\n    // The character value of the first character is multiplied by 45\n    let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45\n\n    // The character value of the second digit is added to the product\n    value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])\n\n    // The sum is then stored as 11-bit binary number\n    bitBuffer.put(value, 11)\n  }\n\n  // If the number of input data characters is not a multiple of two,\n  // the character value of the final character is encoded as a 6-bit binary number.\n  if (this.data.length % 2) {\n    bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)\n  }\n}\n\nmodule.exports = AlphanumericData\n","const Mode = require('./mode')\n\nfunction ByteData (data) {\n  this.mode = Mode.BYTE\n  if (typeof (data) === 'string') {\n    this.data = new TextEncoder().encode(data)\n  } else {\n    this.data = new Uint8Array(data)\n  }\n}\n\nByteData.getBitsLength = function getBitsLength (length) {\n  return length * 8\n}\n\nByteData.prototype.getLength = function getLength () {\n  return this.data.length\n}\n\nByteData.prototype.getBitsLength = function getBitsLength () {\n  return ByteData.getBitsLength(this.data.length)\n}\n\nByteData.prototype.write = function (bitBuffer) {\n  for (let i = 0, l = this.data.length; i < l; i++) {\n    bitBuffer.put(this.data[i], 8)\n  }\n}\n\nmodule.exports = ByteData\n","const Mode = require('./mode')\nconst Utils = require('./utils')\n\nfunction KanjiData (data) {\n  this.mode = Mode.KANJI\n  this.data = data\n}\n\nKanjiData.getBitsLength = function getBitsLength (length) {\n  return length * 13\n}\n\nKanjiData.prototype.getLength = function getLength () {\n  return this.data.length\n}\n\nKanjiData.prototype.getBitsLength = function getBitsLength () {\n  return KanjiData.getBitsLength(this.data.length)\n}\n\nKanjiData.prototype.write = function (bitBuffer) {\n  let i\n\n  // In the Shift JIS system, Kanji characters are represented by a two byte combination.\n  // These byte values are shifted from the JIS X 0208 values.\n  // JIS X 0208 gives details of the shift coded representation.\n  for (i = 0; i < this.data.length; i++) {\n    let value = Utils.toSJIS(this.data[i])\n\n    // For characters with Shift JIS values from 0x8140 to 0x9FFC:\n    if (value >= 0x8140 && value <= 0x9FFC) {\n      // Subtract 0x8140 from Shift JIS value\n      value -= 0x8140\n\n    // For characters with Shift JIS values from 0xE040 to 0xEBBF\n    } else if (value >= 0xE040 && value <= 0xEBBF) {\n      // Subtract 0xC140 from Shift JIS value\n      value -= 0xC140\n    } else {\n      throw new Error(\n        'Invalid SJIS character: ' + this.data[i] + '\\n' +\n        'Make sure your charset is UTF-8')\n    }\n\n    // Multiply most significant byte of result by 0xC0\n    // and add least significant byte to product\n    value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff)\n\n    // Convert result to a 13-bit binary string\n    bitBuffer.put(value, 13)\n  }\n}\n\nmodule.exports = KanjiData\n","'use strict';\n\n/******************************************************************************\n * Created 2008-08-19.\n *\n * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.\n *\n * Copyright (C) 2008\n *   Wyatt Baldwin <self@wyattbaldwin.com>\n *   All rights reserved\n *\n * Licensed under the MIT license.\n *\n *   http://www.opensource.org/licenses/mit-license.php\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *****************************************************************************/\nvar dijkstra = {\n  single_source_shortest_paths: function(graph, s, d) {\n    // Predecessor map for each node that has been encountered.\n    // node ID => predecessor node ID\n    var predecessors = {};\n\n    // Costs of shortest paths from s to all nodes encountered.\n    // node ID => cost\n    var costs = {};\n    costs[s] = 0;\n\n    // Costs of shortest paths from s to all nodes encountered; differs from\n    // `costs` in that it provides easy access to the node that currently has\n    // the known shortest path from s.\n    // XXX: Do we actually need both `costs` and `open`?\n    var open = dijkstra.PriorityQueue.make();\n    open.push(s, 0);\n\n    var closest,\n        u, v,\n        cost_of_s_to_u,\n        adjacent_nodes,\n        cost_of_e,\n        cost_of_s_to_u_plus_cost_of_e,\n        cost_of_s_to_v,\n        first_visit;\n    while (!open.empty()) {\n      // In the nodes remaining in graph that have a known cost from s,\n      // find the node, u, that currently has the shortest path from s.\n      closest = open.pop();\n      u = closest.value;\n      cost_of_s_to_u = closest.cost;\n\n      // Get nodes adjacent to u...\n      adjacent_nodes = graph[u] || {};\n\n      // ...and explore the edges that connect u to those nodes, updating\n      // the cost of the shortest paths to any or all of those nodes as\n      // necessary. v is the node across the current edge from u.\n      for (v in adjacent_nodes) {\n        if (adjacent_nodes.hasOwnProperty(v)) {\n          // Get the cost of the edge running from u to v.\n          cost_of_e = adjacent_nodes[v];\n\n          // Cost of s to u plus the cost of u to v across e--this is *a*\n          // cost from s to v that may or may not be less than the current\n          // known cost to v.\n          cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;\n\n          // If we haven't visited v yet OR if the current known cost from s to\n          // v is greater than the new cost we just found (cost of s to u plus\n          // cost of u to v across e), update v's cost in the cost list and\n          // update v's predecessor in the predecessor list (it's now u).\n          cost_of_s_to_v = costs[v];\n          first_visit = (typeof costs[v] === 'undefined');\n          if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {\n            costs[v] = cost_of_s_to_u_plus_cost_of_e;\n            open.push(v, cost_of_s_to_u_plus_cost_of_e);\n            predecessors[v] = u;\n          }\n        }\n      }\n    }\n\n    if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {\n      var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');\n      throw new Error(msg);\n    }\n\n    return predecessors;\n  },\n\n  extract_shortest_path_from_predecessor_list: function(predecessors, d) {\n    var nodes = [];\n    var u = d;\n    var predecessor;\n    while (u) {\n      nodes.push(u);\n      predecessor = predecessors[u];\n      u = predecessors[u];\n    }\n    nodes.reverse();\n    return nodes;\n  },\n\n  find_path: function(graph, s, d) {\n    var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);\n    return dijkstra.extract_shortest_path_from_predecessor_list(\n      predecessors, d);\n  },\n\n  /**\n   * A very naive priority queue implementation.\n   */\n  PriorityQueue: {\n    make: function (opts) {\n      var T = dijkstra.PriorityQueue,\n          t = {},\n          key;\n      opts = opts || {};\n      for (key in T) {\n        if (T.hasOwnProperty(key)) {\n          t[key] = T[key];\n        }\n      }\n      t.queue = [];\n      t.sorter = opts.sorter || T.default_sorter;\n      return t;\n    },\n\n    default_sorter: function (a, b) {\n      return a.cost - b.cost;\n    },\n\n    /**\n     * Add a new item to the queue and ensure the highest priority element\n     * is at the front of the queue.\n     */\n    push: function (value, cost) {\n      var item = {value: value, cost: cost};\n      this.queue.push(item);\n      this.queue.sort(this.sorter);\n    },\n\n    /**\n     * Return the highest priority element in the queue.\n     */\n    pop: function () {\n      return this.queue.shift();\n    },\n\n    empty: function () {\n      return this.queue.length === 0;\n    }\n  }\n};\n\n\n// node.js module exports\nif (typeof module !== 'undefined') {\n  module.exports = dijkstra;\n}\n","const Mode = require('./mode')\nconst NumericData = require('./numeric-data')\nconst AlphanumericData = require('./alphanumeric-data')\nconst ByteData = require('./byte-data')\nconst KanjiData = require('./kanji-data')\nconst Regex = require('./regex')\nconst Utils = require('./utils')\nconst dijkstra = require('dijkstrajs')\n\n/**\n * Returns UTF8 byte length\n *\n * @param  {String} str Input string\n * @return {Number}     Number of byte\n */\nfunction getStringByteLength (str) {\n  return unescape(encodeURIComponent(str)).length\n}\n\n/**\n * Get a list of segments of the specified mode\n * from a string\n *\n * @param  {Mode}   mode Segment mode\n * @param  {String} str  String to process\n * @return {Array}       Array of object with segments data\n */\nfunction getSegments (regex, mode, str) {\n  const segments = []\n  let result\n\n  while ((result = regex.exec(str)) !== null) {\n    segments.push({\n      data: result[0],\n      index: result.index,\n      mode: mode,\n      length: result[0].length\n    })\n  }\n\n  return segments\n}\n\n/**\n * Extracts a series of segments with the appropriate\n * modes from a string\n *\n * @param  {String} dataStr Input string\n * @return {Array}          Array of object with segments data\n */\nfunction getSegmentsFromString (dataStr) {\n  const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr)\n  const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr)\n  let byteSegs\n  let kanjiSegs\n\n  if (Utils.isKanjiModeEnabled()) {\n    byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr)\n    kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr)\n  } else {\n    byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr)\n    kanjiSegs = []\n  }\n\n  const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs)\n\n  return segs\n    .sort(function (s1, s2) {\n      return s1.index - s2.index\n    })\n    .map(function (obj) {\n      return {\n        data: obj.data,\n        mode: obj.mode,\n        length: obj.length\n      }\n    })\n}\n\n/**\n * Returns how many bits are needed to encode a string of\n * specified length with the specified mode\n *\n * @param  {Number} length String length\n * @param  {Mode} mode     Segment mode\n * @return {Number}        Bit length\n */\nfunction getSegmentBitsLength (length, mode) {\n  switch (mode) {\n    case Mode.NUMERIC:\n      return NumericData.getBitsLength(length)\n    case Mode.ALPHANUMERIC:\n      return AlphanumericData.getBitsLength(length)\n    case Mode.KANJI:\n      return KanjiData.getBitsLength(length)\n    case Mode.BYTE:\n      return ByteData.getBitsLength(length)\n  }\n}\n\n/**\n * Merges adjacent segments which have the same mode\n *\n * @param  {Array} segs Array of object with segments data\n * @return {Array}      Array of object with segments data\n */\nfunction mergeSegments (segs) {\n  return segs.reduce(function (acc, curr) {\n    const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null\n    if (prevSeg && prevSeg.mode === curr.mode) {\n      acc[acc.length - 1].data += curr.data\n      return acc\n    }\n\n    acc.push(curr)\n    return acc\n  }, [])\n}\n\n/**\n * Generates a list of all possible nodes combination which\n * will be used to build a segments graph.\n *\n * Nodes are divided by groups. Each group will contain a list of all the modes\n * in which is possible to encode the given text.\n *\n * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.\n * The group for '12345' will contain then 3 objects, one for each\n * possible encoding mode.\n *\n * Each node represents a possible segment.\n *\n * @param  {Array} segs Array of object with segments data\n * @return {Array}      Array of object with segments data\n */\nfunction buildNodes (segs) {\n  const nodes = []\n  for (let i = 0; i < segs.length; i++) {\n    const seg = segs[i]\n\n    switch (seg.mode) {\n      case Mode.NUMERIC:\n        nodes.push([seg,\n          { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },\n          { data: seg.data, mode: Mode.BYTE, length: seg.length }\n        ])\n        break\n      case Mode.ALPHANUMERIC:\n        nodes.push([seg,\n          { data: seg.data, mode: Mode.BYTE, length: seg.length }\n        ])\n        break\n      case Mode.KANJI:\n        nodes.push([seg,\n          { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }\n        ])\n        break\n      case Mode.BYTE:\n        nodes.push([\n          { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }\n        ])\n    }\n  }\n\n  return nodes\n}\n\n/**\n * Builds a graph from a list of nodes.\n * All segments in each node group will be connected with all the segments of\n * the next group and so on.\n *\n * At each connection will be assigned a weight depending on the\n * segment's byte length.\n *\n * @param  {Array} nodes    Array of object with segments data\n * @param  {Number} version QR Code version\n * @return {Object}         Graph of all possible segments\n */\nfunction buildGraph (nodes, version) {\n  const table = {}\n  const graph = { start: {} }\n  let prevNodeIds = ['start']\n\n  for (let i = 0; i < nodes.length; i++) {\n    const nodeGroup = nodes[i]\n    const currentNodeIds = []\n\n    for (let j = 0; j < nodeGroup.length; j++) {\n      const node = nodeGroup[j]\n      const key = '' + i + j\n\n      currentNodeIds.push(key)\n      table[key] = { node: node, lastCount: 0 }\n      graph[key] = {}\n\n      for (let n = 0; n < prevNodeIds.length; n++) {\n        const prevNodeId = prevNodeIds[n]\n\n        if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {\n          graph[prevNodeId][key] =\n            getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -\n            getSegmentBitsLength(table[prevNodeId].lastCount, node.mode)\n\n          table[prevNodeId].lastCount += node.length\n        } else {\n          if (table[prevNodeId]) table[prevNodeId].lastCount = node.length\n\n          graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +\n            4 + Mode.getCharCountIndicator(node.mode, version) // switch cost\n        }\n      }\n    }\n\n    prevNodeIds = currentNodeIds\n  }\n\n  for (let n = 0; n < prevNodeIds.length; n++) {\n    graph[prevNodeIds[n]].end = 0\n  }\n\n  return { map: graph, table: table }\n}\n\n/**\n * Builds a segment from a specified data and mode.\n * If a mode is not specified, the more suitable will be used.\n *\n * @param  {String} data             Input data\n * @param  {Mode | String} modesHint Data mode\n * @return {Segment}                 Segment\n */\nfunction buildSingleSegment (data, modesHint) {\n  let mode\n  const bestMode = Mode.getBestModeForData(data)\n\n  mode = Mode.from(modesHint, bestMode)\n\n  // Make sure data can be encoded\n  if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {\n    throw new Error('\"' + data + '\"' +\n      ' cannot be encoded with mode ' + Mode.toString(mode) +\n      '.\\n Suggested mode is: ' + Mode.toString(bestMode))\n  }\n\n  // Use Mode.BYTE if Kanji support is disabled\n  if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {\n    mode = Mode.BYTE\n  }\n\n  switch (mode) {\n    case Mode.NUMERIC:\n      return new NumericData(data)\n\n    case Mode.ALPHANUMERIC:\n      return new AlphanumericData(data)\n\n    case Mode.KANJI:\n      return new KanjiData(data)\n\n    case Mode.BYTE:\n      return new ByteData(data)\n  }\n}\n\n/**\n * Builds a list of segments from an array.\n * Array can contain Strings or Objects with segment's info.\n *\n * For each item which is a string, will be generated a segment with the given\n * string and the more appropriate encoding mode.\n *\n * For each item which is an object, will be generated a segment with the given\n * data and mode.\n * Objects must contain at least the property \"data\".\n * If property \"mode\" is not present, the more suitable mode will be used.\n *\n * @param  {Array} array Array of objects with segments data\n * @return {Array}       Array of Segments\n */\nexports.fromArray = function fromArray (array) {\n  return array.reduce(function (acc, seg) {\n    if (typeof seg === 'string') {\n      acc.push(buildSingleSegment(seg, null))\n    } else if (seg.data) {\n      acc.push(buildSingleSegment(seg.data, seg.mode))\n    }\n\n    return acc\n  }, [])\n}\n\n/**\n * Builds an optimized sequence of segments from a string,\n * which will produce the shortest possible bitstream.\n *\n * @param  {String} data    Input string\n * @param  {Number} version QR Code version\n * @return {Array}          Array of segments\n */\nexports.fromString = function fromString (data, version) {\n  const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled())\n\n  const nodes = buildNodes(segs)\n  const graph = buildGraph(nodes, version)\n  const path = dijkstra.find_path(graph.map, 'start', 'end')\n\n  const optimizedSegs = []\n  for (let i = 1; i < path.length - 1; i++) {\n    optimizedSegs.push(graph.table[path[i]].node)\n  }\n\n  return exports.fromArray(mergeSegments(optimizedSegs))\n}\n\n/**\n * Splits a string in various segments with the modes which\n * best represent their content.\n * The produced segments are far from being optimized.\n * The output of this function is only used to estimate a QR Code version\n * which may contain the data.\n *\n * @param  {string} data Input string\n * @return {Array}       Array of segments\n */\nexports.rawSplit = function rawSplit (data) {\n  return exports.fromArray(\n    getSegmentsFromString(data, Utils.isKanjiModeEnabled())\n  )\n}\n","const Utils = require('./utils')\nconst ECLevel = require('./error-correction-level')\nconst BitBuffer = require('./bit-buffer')\nconst BitMatrix = require('./bit-matrix')\nconst AlignmentPattern = require('./alignment-pattern')\nconst FinderPattern = require('./finder-pattern')\nconst MaskPattern = require('./mask-pattern')\nconst ECCode = require('./error-correction-code')\nconst ReedSolomonEncoder = require('./reed-solomon-encoder')\nconst Version = require('./version')\nconst FormatInfo = require('./format-info')\nconst Mode = require('./mode')\nconst Segments = require('./segments')\n\n/**\n * QRCode for JavaScript\n *\n * modified by Ryan Day for nodejs support\n * Copyright (c) 2011 Ryan Day\n *\n * Licensed under the MIT license:\n *   http://www.opensource.org/licenses/mit-license.php\n *\n//---------------------------------------------------------------------\n// QRCode for JavaScript\n//\n// Copyright (c) 2009 Kazuhiko Arase\n//\n// URL: http://www.d-project.com/\n//\n// Licensed under the MIT license:\n//   http://www.opensource.org/licenses/mit-license.php\n//\n// The word \"QR Code\" is registered trademark of\n// DENSO WAVE INCORPORATED\n//   http://www.denso-wave.com/qrcode/faqpatent-e.html\n//\n//---------------------------------------------------------------------\n*/\n\n/**\n * Add finder patterns bits to matrix\n *\n * @param  {BitMatrix} matrix  Modules matrix\n * @param  {Number}    version QR Code version\n */\nfunction setupFinderPattern (matrix, version) {\n  const size = matrix.size\n  const pos = FinderPattern.getPositions(version)\n\n  for (let i = 0; i < pos.length; i++) {\n    const row = pos[i][0]\n    const col = pos[i][1]\n\n    for (let r = -1; r <= 7; r++) {\n      if (row + r <= -1 || size <= row + r) continue\n\n      for (let c = -1; c <= 7; c++) {\n        if (col + c <= -1 || size <= col + c) continue\n\n        if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||\n          (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||\n          (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {\n          matrix.set(row + r, col + c, true, true)\n        } else {\n          matrix.set(row + r, col + c, false, true)\n        }\n      }\n    }\n  }\n}\n\n/**\n * Add timing pattern bits to matrix\n *\n * Note: this function must be called before {@link setupAlignmentPattern}\n *\n * @param  {BitMatrix} matrix Modules matrix\n */\nfunction setupTimingPattern (matrix) {\n  const size = matrix.size\n\n  for (let r = 8; r < size - 8; r++) {\n    const value = r % 2 === 0\n    matrix.set(r, 6, value, true)\n    matrix.set(6, r, value, true)\n  }\n}\n\n/**\n * Add alignment patterns bits to matrix\n *\n * Note: this function must be called after {@link setupTimingPattern}\n *\n * @param  {BitMatrix} matrix  Modules matrix\n * @param  {Number}    version QR Code version\n */\nfunction setupAlignmentPattern (matrix, version) {\n  const pos = AlignmentPattern.getPositions(version)\n\n  for (let i = 0; i < pos.length; i++) {\n    const row = pos[i][0]\n    const col = pos[i][1]\n\n    for (let r = -2; r <= 2; r++) {\n      for (let c = -2; c <= 2; c++) {\n        if (r === -2 || r === 2 || c === -2 || c === 2 ||\n          (r === 0 && c === 0)) {\n          matrix.set(row + r, col + c, true, true)\n        } else {\n          matrix.set(row + r, col + c, false, true)\n        }\n      }\n    }\n  }\n}\n\n/**\n * Add version info bits to matrix\n *\n * @param  {BitMatrix} matrix  Modules matrix\n * @param  {Number}    version QR Code version\n */\nfunction setupVersionInfo (matrix, version) {\n  const size = matrix.size\n  const bits = Version.getEncodedBits(version)\n  let row, col, mod\n\n  for (let i = 0; i < 18; i++) {\n    row = Math.floor(i / 3)\n    col = i % 3 + size - 8 - 3\n    mod = ((bits >> i) & 1) === 1\n\n    matrix.set(row, col, mod, true)\n    matrix.set(col, row, mod, true)\n  }\n}\n\n/**\n * Add format info bits to matrix\n *\n * @param  {BitMatrix} matrix               Modules matrix\n * @param  {ErrorCorrectionLevel}    errorCorrectionLevel Error correction level\n * @param  {Number}    maskPattern          Mask pattern reference value\n */\nfunction setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {\n  const size = matrix.size\n  const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern)\n  let i, mod\n\n  for (i = 0; i < 15; i++) {\n    mod = ((bits >> i) & 1) === 1\n\n    // vertical\n    if (i < 6) {\n      matrix.set(i, 8, mod, true)\n    } else if (i < 8) {\n      matrix.set(i + 1, 8, mod, true)\n    } else {\n      matrix.set(size - 15 + i, 8, mod, true)\n    }\n\n    // horizontal\n    if (i < 8) {\n      matrix.set(8, size - i - 1, mod, true)\n    } else if (i < 9) {\n      matrix.set(8, 15 - i - 1 + 1, mod, true)\n    } else {\n      matrix.set(8, 15 - i - 1, mod, true)\n    }\n  }\n\n  // fixed module\n  matrix.set(size - 8, 8, 1, true)\n}\n\n/**\n * Add encoded data bits to matrix\n *\n * @param  {BitMatrix}  matrix Modules matrix\n * @param  {Uint8Array} data   Data codewords\n */\nfunction setupData (matrix, data) {\n  const size = matrix.size\n  let inc = -1\n  let row = size - 1\n  let bitIndex = 7\n  let byteIndex = 0\n\n  for (let col = size - 1; col > 0; col -= 2) {\n    if (col === 6) col--\n\n    while (true) {\n      for (let c = 0; c < 2; c++) {\n        if (!matrix.isReserved(row, col - c)) {\n          let dark = false\n\n          if (byteIndex < data.length) {\n            dark = (((data[byteIndex] >>> bitIndex) & 1) === 1)\n          }\n\n          matrix.set(row, col - c, dark)\n          bitIndex--\n\n          if (bitIndex === -1) {\n            byteIndex++\n            bitIndex = 7\n          }\n        }\n      }\n\n      row += inc\n\n      if (row < 0 || size <= row) {\n        row -= inc\n        inc = -inc\n        break\n      }\n    }\n  }\n}\n\n/**\n * Create encoded codewords from data input\n *\n * @param  {Number}   version              QR Code version\n * @param  {ErrorCorrectionLevel}   errorCorrectionLevel Error correction level\n * @param  {ByteData} data                 Data input\n * @return {Uint8Array}                    Buffer containing encoded codewords\n */\nfunction createData (version, errorCorrectionLevel, segments) {\n  // Prepare data buffer\n  const buffer = new BitBuffer()\n\n  segments.forEach(function (data) {\n    // prefix data with mode indicator (4 bits)\n    buffer.put(data.mode.bit, 4)\n\n    // Prefix data with character count indicator.\n    // The character count indicator is a string of bits that represents the\n    // number of characters that are being encoded.\n    // The character count indicator must be placed after the mode indicator\n    // and must be a certain number of bits long, depending on the QR version\n    // and data mode\n    // @see {@link Mode.getCharCountIndicator}.\n    buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version))\n\n    // add binary data sequence to buffer\n    data.write(buffer)\n  })\n\n  // Calculate required number of bits\n  const totalCodewords = Utils.getSymbolTotalCodewords(version)\n  const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)\n  const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8\n\n  // Add a terminator.\n  // If the bit string is shorter than the total number of required bits,\n  // a terminator of up to four 0s must be added to the right side of the string.\n  // If the bit string is more than four bits shorter than the required number of bits,\n  // add four 0s to the end.\n  if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {\n    buffer.put(0, 4)\n  }\n\n  // If the bit string is fewer than four bits shorter, add only the number of 0s that\n  // are needed to reach the required number of bits.\n\n  // After adding the terminator, if the number of bits in the string is not a multiple of 8,\n  // pad the string on the right with 0s to make the string's length a multiple of 8.\n  while (buffer.getLengthInBits() % 8 !== 0) {\n    buffer.putBit(0)\n  }\n\n  // Add pad bytes if the string is still shorter than the total number of required bits.\n  // Extend the buffer to fill the data capacity of the symbol corresponding to\n  // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)\n  // and 00010001 (0x11) alternately.\n  const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8\n  for (let i = 0; i < remainingByte; i++) {\n    buffer.put(i % 2 ? 0x11 : 0xEC, 8)\n  }\n\n  return createCodewords(buffer, version, errorCorrectionLevel)\n}\n\n/**\n * Encode input data with Reed-Solomon and return codewords with\n * relative error correction bits\n *\n * @param  {BitBuffer} bitBuffer            Data to encode\n * @param  {Number}    version              QR Code version\n * @param  {ErrorCorrectionLevel} errorCorrectionLevel Error correction level\n * @return {Uint8Array}                     Buffer containing encoded codewords\n */\nfunction createCodewords (bitBuffer, version, errorCorrectionLevel) {\n  // Total codewords for this QR code version (Data + Error correction)\n  const totalCodewords = Utils.getSymbolTotalCodewords(version)\n\n  // Total number of error correction codewords\n  const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)\n\n  // Total number of data codewords\n  const dataTotalCodewords = totalCodewords - ecTotalCodewords\n\n  // Total number of blocks\n  const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel)\n\n  // Calculate how many blocks each group should contain\n  const blocksInGroup2 = totalCodewords % ecTotalBlocks\n  const blocksInGroup1 = ecTotalBlocks - blocksInGroup2\n\n  const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks)\n\n  const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks)\n  const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1\n\n  // Number of EC codewords is the same for both groups\n  const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1\n\n  // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount\n  const rs = new ReedSolomonEncoder(ecCount)\n\n  let offset = 0\n  const dcData = new Array(ecTotalBlocks)\n  const ecData = new Array(ecTotalBlocks)\n  let maxDataSize = 0\n  const buffer = new Uint8Array(bitBuffer.buffer)\n\n  // Divide the buffer into the required number of blocks\n  for (let b = 0; b < ecTotalBlocks; b++) {\n    const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2\n\n    // extract a block of data from buffer\n    dcData[b] = buffer.slice(offset, offset + dataSize)\n\n    // Calculate EC codewords for this data block\n    ecData[b] = rs.encode(dcData[b])\n\n    offset += dataSize\n    maxDataSize = Math.max(maxDataSize, dataSize)\n  }\n\n  // Create final data\n  // Interleave the data and error correction codewords from each block\n  const data = new Uint8Array(totalCodewords)\n  let index = 0\n  let i, r\n\n  // Add data codewords\n  for (i = 0; i < maxDataSize; i++) {\n    for (r = 0; r < ecTotalBlocks; r++) {\n      if (i < dcData[r].length) {\n        data[index++] = dcData[r][i]\n      }\n    }\n  }\n\n  // Apped EC codewords\n  for (i = 0; i < ecCount; i++) {\n    for (r = 0; r < ecTotalBlocks; r++) {\n      data[index++] = ecData[r][i]\n    }\n  }\n\n  return data\n}\n\n/**\n * Build QR Code symbol\n *\n * @param  {String} data                 Input string\n * @param  {Number} version              QR Code version\n * @param  {ErrorCorretionLevel} errorCorrectionLevel Error level\n * @param  {MaskPattern} maskPattern     Mask pattern\n * @return {Object}                      Object containing symbol data\n */\nfunction createSymbol (data, version, errorCorrectionLevel, maskPattern) {\n  let segments\n\n  if (Array.isArray(data)) {\n    segments = Segments.fromArray(data)\n  } else if (typeof data === 'string') {\n    let estimatedVersion = version\n\n    if (!estimatedVersion) {\n      const rawSegments = Segments.rawSplit(data)\n\n      // Estimate best version that can contain raw splitted segments\n      estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel)\n    }\n\n    // Build optimized segments\n    // If estimated version is undefined, try with the highest version\n    segments = Segments.fromString(data, estimatedVersion || 40)\n  } else {\n    throw new Error('Invalid data')\n  }\n\n  // Get the min version that can contain data\n  const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel)\n\n  // If no version is found, data cannot be stored\n  if (!bestVersion) {\n    throw new Error('The amount of data is too big to be stored in a QR Code')\n  }\n\n  // If not specified, use min version as default\n  if (!version) {\n    version = bestVersion\n\n  // Check if the specified version can contain the data\n  } else if (version < bestVersion) {\n    throw new Error('\\n' +\n      'The chosen QR Code version cannot contain this amount of data.\\n' +\n      'Minimum version required to store current data is: ' + bestVersion + '.\\n'\n    )\n  }\n\n  const dataBits = createData(version, errorCorrectionLevel, segments)\n\n  // Allocate matrix buffer\n  const moduleCount = Utils.getSymbolSize(version)\n  const modules = new BitMatrix(moduleCount)\n\n  // Add function modules\n  setupFinderPattern(modules, version)\n  setupTimingPattern(modules)\n  setupAlignmentPattern(modules, version)\n\n  // Add temporary dummy bits for format info just to set them as reserved.\n  // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}\n  // since the masking operation must be performed only on the encoding region.\n  // These blocks will be replaced with correct values later in code.\n  setupFormatInfo(modules, errorCorrectionLevel, 0)\n\n  if (version >= 7) {\n    setupVersionInfo(modules, version)\n  }\n\n  // Add data codewords\n  setupData(modules, dataBits)\n\n  if (isNaN(maskPattern)) {\n    // Find best mask pattern\n    maskPattern = MaskPattern.getBestMask(modules,\n      setupFormatInfo.bind(null, modules, errorCorrectionLevel))\n  }\n\n  // Apply mask pattern\n  MaskPattern.applyMask(maskPattern, modules)\n\n  // Replace format info bits with correct values\n  setupFormatInfo(modules, errorCorrectionLevel, maskPattern)\n\n  return {\n    modules: modules,\n    version: version,\n    errorCorrectionLevel: errorCorrectionLevel,\n    maskPattern: maskPattern,\n    segments: segments\n  }\n}\n\n/**\n * QR Code\n *\n * @param {String | Array} data                 Input data\n * @param {Object} options                      Optional configurations\n * @param {Number} options.version              QR Code version\n * @param {String} options.errorCorrectionLevel Error correction level\n * @param {Function} options.toSJISFunc         Helper func to convert utf8 to sjis\n */\nexports.create = function create (data, options) {\n  if (typeof data === 'undefined' || data === '') {\n    throw new Error('No input text')\n  }\n\n  let errorCorrectionLevel = ECLevel.M\n  let version\n  let mask\n\n  if (typeof options !== 'undefined') {\n    // Use higher error correction level as default\n    errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M)\n    version = Version.from(options.version)\n    mask = MaskPattern.from(options.maskPattern)\n\n    if (options.toSJISFunc) {\n      Utils.setToSJISFunction(options.toSJISFunc)\n    }\n  }\n\n  return createSymbol(data, version, errorCorrectionLevel, mask)\n}\n","function hex2rgba (hex) {\n  if (typeof hex === 'number') {\n    hex = hex.toString()\n  }\n\n  if (typeof hex !== 'string') {\n    throw new Error('Color should be defined as hex string')\n  }\n\n  let hexCode = hex.slice().replace('#', '').split('')\n  if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {\n    throw new Error('Invalid hex color: ' + hex)\n  }\n\n  // Convert from short to long form (fff -> ffffff)\n  if (hexCode.length === 3 || hexCode.length === 4) {\n    hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {\n      return [c, c]\n    }))\n  }\n\n  // Add default alpha value\n  if (hexCode.length === 6) hexCode.push('F', 'F')\n\n  const hexValue = parseInt(hexCode.join(''), 16)\n\n  return {\n    r: (hexValue >> 24) & 255,\n    g: (hexValue >> 16) & 255,\n    b: (hexValue >> 8) & 255,\n    a: hexValue & 255,\n    hex: '#' + hexCode.slice(0, 6).join('')\n  }\n}\n\nexports.getOptions = function getOptions (options) {\n  if (!options) options = {}\n  if (!options.color) options.color = {}\n\n  const margin = typeof options.margin === 'undefined' ||\n    options.margin === null ||\n    options.margin < 0\n    ? 4\n    : options.margin\n\n  const width = options.width && options.width >= 21 ? options.width : undefined\n  const scale = options.scale || 4\n\n  return {\n    width: width,\n    scale: width ? 4 : scale,\n    margin: margin,\n    color: {\n      dark: hex2rgba(options.color.dark || '#000000ff'),\n      light: hex2rgba(options.color.light || '#ffffffff')\n    },\n    type: options.type,\n    rendererOpts: options.rendererOpts || {}\n  }\n}\n\nexports.getScale = function getScale (qrSize, opts) {\n  return opts.width && opts.width >= qrSize + opts.margin * 2\n    ? opts.width / (qrSize + opts.margin * 2)\n    : opts.scale\n}\n\nexports.getImageWidth = function getImageWidth (qrSize, opts) {\n  const scale = exports.getScale(qrSize, opts)\n  return Math.floor((qrSize + opts.margin * 2) * scale)\n}\n\nexports.qrToImageData = function qrToImageData (imgData, qr, opts) {\n  const size = qr.modules.size\n  const data = qr.modules.data\n  const scale = exports.getScale(size, opts)\n  const symbolSize = Math.floor((size + opts.margin * 2) * scale)\n  const scaledMargin = opts.margin * scale\n  const palette = [opts.color.light, opts.color.dark]\n\n  for (let i = 0; i < symbolSize; i++) {\n    for (let j = 0; j < symbolSize; j++) {\n      let posDst = (i * symbolSize + j) * 4\n      let pxColor = opts.color.light\n\n      if (i >= scaledMargin && j >= scaledMargin &&\n        i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {\n        const iSrc = Math.floor((i - scaledMargin) / scale)\n        const jSrc = Math.floor((j - scaledMargin) / scale)\n        pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]\n      }\n\n      imgData[posDst++] = pxColor.r\n      imgData[posDst++] = pxColor.g\n      imgData[posDst++] = pxColor.b\n      imgData[posDst] = pxColor.a\n    }\n  }\n}\n","const Utils = require('./utils')\n\nfunction clearCanvas (ctx, canvas, size) {\n  ctx.clearRect(0, 0, canvas.width, canvas.height)\n\n  if (!canvas.style) canvas.style = {}\n  canvas.height = size\n  canvas.width = size\n  canvas.style.height = size + 'px'\n  canvas.style.width = size + 'px'\n}\n\nfunction getCanvasElement () {\n  try {\n    return document.createElement('canvas')\n  } catch (e) {\n    throw new Error('You need to specify a canvas element')\n  }\n}\n\nexports.render = function render (qrData, canvas, options) {\n  let opts = options\n  let canvasEl = canvas\n\n  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {\n    opts = canvas\n    canvas = undefined\n  }\n\n  if (!canvas) {\n    canvasEl = getCanvasElement()\n  }\n\n  opts = Utils.getOptions(opts)\n  const size = Utils.getImageWidth(qrData.modules.size, opts)\n\n  const ctx = canvasEl.getContext('2d')\n  const image = ctx.createImageData(size, size)\n  Utils.qrToImageData(image.data, qrData, opts)\n\n  clearCanvas(ctx, canvasEl, size)\n  ctx.putImageData(image, 0, 0)\n\n  return canvasEl\n}\n\nexports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {\n  let opts = options\n\n  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {\n    opts = canvas\n    canvas = undefined\n  }\n\n  if (!opts) opts = {}\n\n  const canvasEl = exports.render(qrData, canvas, opts)\n\n  const type = opts.type || 'image/png'\n  const rendererOpts = opts.rendererOpts || {}\n\n  return canvasEl.toDataURL(type, rendererOpts.quality)\n}\n","const Utils = require('./utils')\n\nfunction getColorAttrib (color, attrib) {\n  const alpha = color.a / 255\n  const str = attrib + '=\"' + color.hex + '\"'\n\n  return alpha < 1\n    ? str + ' ' + attrib + '-opacity=\"' + alpha.toFixed(2).slice(1) + '\"'\n    : str\n}\n\nfunction svgCmd (cmd, x, y) {\n  let str = cmd + x\n  if (typeof y !== 'undefined') str += ' ' + y\n\n  return str\n}\n\nfunction qrToPath (data, size, margin) {\n  let path = ''\n  let moveBy = 0\n  let newRow = false\n  let lineLength = 0\n\n  for (let i = 0; i < data.length; i++) {\n    const col = Math.floor(i % size)\n    const row = Math.floor(i / size)\n\n    if (!col && !newRow) newRow = true\n\n    if (data[i]) {\n      lineLength++\n\n      if (!(i > 0 && col > 0 && data[i - 1])) {\n        path += newRow\n          ? svgCmd('M', col + margin, 0.5 + row + margin)\n          : svgCmd('m', moveBy, 0)\n\n        moveBy = 0\n        newRow = false\n      }\n\n      if (!(col + 1 < size && data[i + 1])) {\n        path += svgCmd('h', lineLength)\n        lineLength = 0\n      }\n    } else {\n      moveBy++\n    }\n  }\n\n  return path\n}\n\nexports.render = function render (qrData, options, cb) {\n  const opts = Utils.getOptions(options)\n  const size = qrData.modules.size\n  const data = qrData.modules.data\n  const qrcodesize = size + opts.margin * 2\n\n  const bg = !opts.color.light.a\n    ? ''\n    : '<path ' + getColorAttrib(opts.color.light, 'fill') +\n      ' d=\"M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z\"/>'\n\n  const path =\n    '<path ' + getColorAttrib(opts.color.dark, 'stroke') +\n    ' d=\"' + qrToPath(data, size, opts.margin) + '\"/>'\n\n  const viewBox = 'viewBox=\"' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '\"'\n\n  const width = !opts.width ? '' : 'width=\"' + opts.width + '\" height=\"' + opts.width + '\" '\n\n  const svgTag = '<svg xmlns=\"http://www.w3.org/2000/svg\" ' + width + viewBox + ' shape-rendering=\"crispEdges\">' + bg + path + '</svg>\\n'\n\n  if (typeof cb === 'function') {\n    cb(null, svgTag)\n  }\n\n  return svgTag\n}\n","\nconst canPromise = require('./can-promise')\n\nconst QRCode = require('./core/qrcode')\nconst CanvasRenderer = require('./renderer/canvas')\nconst SvgRenderer = require('./renderer/svg-tag.js')\n\nfunction renderCanvas (renderFunc, canvas, text, opts, cb) {\n  const args = [].slice.call(arguments, 1)\n  const argsNum = args.length\n  const isLastArgCb = typeof args[argsNum - 1] === 'function'\n\n  if (!isLastArgCb && !canPromise()) {\n    throw new Error('Callback required as last argument')\n  }\n\n  if (isLastArgCb) {\n    if (argsNum < 2) {\n      throw new Error('Too few arguments provided')\n    }\n\n    if (argsNum === 2) {\n      cb = text\n      text = canvas\n      canvas = opts = undefined\n    } else if (argsNum === 3) {\n      if (canvas.getContext && typeof cb === 'undefined') {\n        cb = opts\n        opts = undefined\n      } else {\n        cb = opts\n        opts = text\n        text = canvas\n        canvas = undefined\n      }\n    }\n  } else {\n    if (argsNum < 1) {\n      throw new Error('Too few arguments provided')\n    }\n\n    if (argsNum === 1) {\n      text = canvas\n      canvas = opts = undefined\n    } else if (argsNum === 2 && !canvas.getContext) {\n      opts = text\n      text = canvas\n      canvas = undefined\n    }\n\n    return new Promise(function (resolve, reject) {\n      try {\n        const data = QRCode.create(text, opts)\n        resolve(renderFunc(data, canvas, opts))\n      } catch (e) {\n        reject(e)\n      }\n    })\n  }\n\n  try {\n    const data = QRCode.create(text, opts)\n    cb(null, renderFunc(data, canvas, opts))\n  } catch (e) {\n    cb(e)\n  }\n}\n\nexports.create = QRCode.create\nexports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render)\nexports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL)\n\n// only svg for now.\nexports.toString = renderCanvas.bind(null, function (data, _, opts) {\n  return SvgRenderer.render(data, opts)\n})\n","<script>\n  import { _ } from '@sveltia/i18n';\n  import { Dialog } from '@sveltia/ui';\n  import { toCanvas } from 'qrcode';\n\n  import { showMobileSignInDialog } from '$lib/services/app/onboarding';\n  import { user } from '$lib/services/user/account.svelte';\n  import { prefs } from '$lib/services/user/prefs.svelte';\n\n  /** @type {HTMLCanvasElement | undefined} */\n  let canvas = $state();\n\n  $effect(() => {\n    if (canvas && showMobileSignInDialog.current) {\n      const { origin, pathname } = window.location;\n      const snapshot = $state.snapshot(prefs);\n      const encodedData = btoa(JSON.stringify({ token: user.account?.token, prefs: snapshot }));\n      const url = `${origin}${pathname}#/signin/${encodedData}`;\n\n      toCanvas(canvas, url);\n\n      if (prefs.devModeEnabled) {\n        // eslint-disable-next-line no-console\n        console.info('Mobile sign-in URL:', url);\n      }\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, enabled = true } (key)}\n                {#if enabled}\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                {/if}\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  /**\n   * @import { DeployState } 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 {\n    /* eslint-disable prefer-const */\n    state,\n    /* eslint-enable prefer-const */\n  } = $props();\n\n  /**\n   * Labels for the states worth showing. A finished build needs no badge, because the preview link\n   * itself says the preview is available, and an unknown state has nothing to report. Neither does\n   * a lookup in flight, which is over in moments — a pill that flashed up on every card as the\n   * board opened would be noise rather than information.\n   * @type {Record<string, string>}\n   */\n  const LABELS = {\n    pending: 'deploy_preview.short.building',\n    error: 'deploy_preview.short.failed',\n  };\n\n  const label = $derived(LABELS[state]);\n</script>\n\n{#if label}\n  <span role=\"none\" class=\"deploy-status-badge {state}\">\n    {_(label)}\n  </span>\n{/if}\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  .deploy-status-badge {\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    &.pending {\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    &.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  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 { encodeRoutePath, 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 {\n    getCollectionFile,\n    getCollectionFileLabel,\n  } from '$lib/services/contents/collection/files';\n  import { getEntrySummary } from '$lib/services/contents/entry/summary';\n  import { deployments, productionSHA } from '$lib/services/deployments';\n  import { checkPublishedVersion, isPublishAllowed } from '$lib/services/workflow';\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    /* eslint-disable prefer-const */\n    entry,\n    dragging = false,\n    busy = false,\n    deploying = false,\n    onDragStart = undefined,\n    onDragEnd = undefined,\n    onDelete = undefined,\n    onPublish = undefined,\n    /* eslint-enable prefer-const */\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  // 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  const summary = $derived.by(() => {\n    // `appLocale.current` is a key, because the labels can be localized\n    if (!appLocale.current || !collection) {\n      return entry.slug;\n    }\n\n    return collectionFile\n      ? getCollectionFileLabel(collectionFile)\n      : getEntrySummary(collection, entry);\n  });\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\n  const canPublish = $derived(!deploying && !readonly && isPublishAllowed(entry, collection));\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 -->\n<div\n  role=\"listitem\"\n  class=\"card\"\n  class:dragging\n  class:static={deletion || deploying || readonly}\n  draggable={!busy && !deletion && !deploying && !readonly}\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      // A collection file is addressed by its name, while its `subPath` is the whole file path\n      goto(encodeRoutePath(`/collections/${collectionName}/entries/${fileName ?? entry.subPath}`), {\n        transitionType: 'forwards',\n      });\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  <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 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 canPublish}\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      {/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  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 { Alert, ConfirmationDialog, EmptyState, Group, Toast } from '@sveltia/ui';\n\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    checkPublishedVersion,\n    publishingBranches,\n    unpublishedEntries,\n    workflowDataReady,\n  } from '$lib/services/workflow';\n  import { WORKFLOW_STATUS_LABELS } from '$lib/services/workflow/constants';\n  import { deployingEntries } from '$lib/services/workflow/deploy';\n  import { getDiscardDialogStrings, getPublishDialogStrings } from '$lib/services/workflow/dialogs';\n  import { openAuthoring, workflowStages } from '$lib/services/workflow/open-authoring';\n  import {\n    discardWorkflowEntry,\n    publishWorkflowEntry,\n    updateWorkflowStatus,\n  } from '$lib/services/workflow/save';\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   */\n\n  /**\n   * Column headings. The `drafts` heading is plural, unlike the singular status label used in the\n   * entry editor’s status button.\n   * @type {Record<WorkflowStatus, string>}\n   */\n  const COLUMN_LABELS = { ...WORKFLOW_STATUS_LABELS, draft: 'status.drafts' };\n\n  /**\n   * @typedef {object} ToastMessages\n   * @property {string} info I18n string key shown while the action is in progress.\n   * @property {string} success I18n string key shown once the action has completed.\n   * @property {string} error I18n string key shown when the action has failed.\n   */\n\n  /** @type {ToastMessages} */\n  const STATUS_UPDATE_MESSAGES = {\n    info: 'workflow.updating_status',\n    success: 'workflow.status_updated',\n    error: 'workflow.status_change_failed',\n  };\n\n  /** @type {ToastMessages} */\n  const DELETION_MESSAGES = {\n    info: 'workflow.deleting_entry',\n    success: 'workflow.entry_deleted',\n    error: 'deleting_entry_failed',\n  };\n\n  /** @type {ToastMessages} */\n  const CANCELLATION_MESSAGES = {\n    info: 'workflow.cancelling_deletion',\n    success: 'workflow.deletion_cancelled',\n    error: 'workflow.cancelling_deletion_failed',\n  };\n\n  /** @type {ToastMessages} */\n  const PUBLISHING_MESSAGES = {\n    info: 'workflow.publishing_entry',\n    success: 'workflow.entry_published',\n    error: 'workflow.publishing_entry_failed',\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\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 = $derived(\n    workflowStages.current.map((status) => ({\n      status,\n      entries: unpublishedEntries.current.filter((entry) => entry.workflow.status === status),\n    })),\n  );\n  const pendingDeletions = $derived(\n    unpublishedEntries.current.filter(({ workflow }) => workflow.status === 'pending_deletion'),\n  );\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   * 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    toastStatus = 'info';\n    toastMessage = _(messages.info);\n    showToast = true;\n\n    try {\n      await request;\n      toastStatus = 'success';\n      toastMessage = _(messages.success);\n    } catch (/** @type {any} */ ex) {\n      toastStatus = 'error';\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      toastMessage = getWorkflowErrorMessage(ex, messages.error);\n      // eslint-disable-next-line no-console\n      console.error(ex);\n    } finally {\n      busyBranches = busyBranches.filter((_branch) => _branch !== branch);\n    }\n\n    // Show the toast again in case it has already been dismissed while the request was in flight\n    showToast = true;\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    toastStatus = 'error';\n    toastMessage = _(messageKey);\n    showToast = true;\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 = draggedEntry;\n\n    draggedEntry = undefined;\n    dropTarget = undefined;\n\n    if (!entry || entry.workflow.status === 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 [draft, review, ready = 0] = columns.map(({ entries }) => entries.length);\n    const deletion = pendingDeletions.length;\n\n    // The board has no Ready column for an Open Authoring contributor, so its count is left out of\n    // the announcement rather than reported as zero\n    announcedPageStatus.current = openAuthoring.current\n      ? _('viewing_open_authoring_workflow', { values: { draft, review, deletion } })\n      : _('viewing_editorial_workflow', { values: { draft, review, ready, deletion } });\n  });\n</script>\n\n<PageContainer aria-label={_('editorial_workflow')}>\n  {#snippet main()}\n    {#if !workflowDataReady.current}\n      <EmptyState>\n        <span role=\"none\">{_('loading_entries', { values: { count: 2 } })}</span>\n      </EmptyState>\n    {:else}\n      <!-- The page container lays its children out in a row, so the board and the list below it\n      need a column wrapper of their own -->\n      <!-- The column count varies: an Open Authoring contributor can’t publish, so the board\n      leaves out the stage that says an entry is ready to go live -->\n      <div role=\"none\" class=\"board\" style:--column-count={columns.length}>\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) {\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 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 entry\n        list once merged, so this is the only place left to say the site still has it -->\n        {#if deployingEntries.current.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 deployingEntries.current 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</PageContainer>\n\n<ConfirmationDialog\n  bind:open={showDeleteDialog}\n  title={discardDialogStrings.title}\n  okLabel={discardDialogStrings.label}\n  onOk={async () => {\n    const entry = targetEntry;\n\n    /* v8 ignore next 7 -- the dialog is only opened for an entry */\n    if (entry) {\n      await runAction(\n        entry,\n        discardWorkflowEntry(entry),\n        targetIsDeletion ? CANCELLATION_MESSAGES : DELETION_MESSAGES,\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 = targetEntry;\n\n    /* v8 ignore next 3 -- the dialog is only opened for an entry */\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      publishWorkflowEntry(entry),\n      targetIsDeletion ? DELETION_MESSAGES : PUBLISHING_MESSAGES,\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  .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 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 ConfigPage from '$lib/components/config/config-page.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 MobilePromoInfobar from '$lib/components/global/infobars/mobile-promo-infobar.svelte';\n  import NewLanguageInfobar from '$lib/components/global/infobars/new-language-infobar.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 {\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    config: ConfigPage,\n    // For small screens\n    menu: MenuPage,\n    settings: SettingsPage,\n  });\n\n  const SelectedPage = $derived(\n    selectedPageName.current === NOT_FOUND_PAGE_NAME\n      ? NotFoundPage\n      : pages[selectedPageName.current],\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 route = resolveRoute(parseLocation().path, Object.keys(pages));\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</script>\n\n<svelte:window\n  onhashchange={() => {\n    selectPage();\n  }}\n/>\n\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<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\nvar isMergeableObject = function isMergeableObject(value) {\n\treturn isNonNullObject(value)\n\t\t&& !isSpecial(value)\n};\n\nfunction isNonNullObject(value) {\n\treturn !!value && typeof value === 'object'\n}\n\nfunction isSpecial(value) {\n\tvar stringValue = Object.prototype.toString.call(value);\n\n\treturn stringValue === '[object RegExp]'\n\t\t|| stringValue === '[object Date]'\n\t\t|| isReactElement(value)\n}\n\n// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25\nvar canUseSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;\n\nfunction isReactElement(value) {\n\treturn value.$$typeof === REACT_ELEMENT_TYPE\n}\n\nfunction emptyTarget(val) {\n\treturn Array.isArray(val) ? [] : {}\n}\n\nfunction cloneUnlessOtherwiseSpecified(value, options) {\n\treturn (options.clone !== false && options.isMergeableObject(value))\n\t\t? deepmerge(emptyTarget(value), value, options)\n\t\t: value\n}\n\nfunction defaultArrayMerge(target, source, options) {\n\treturn target.concat(source).map(function(element) {\n\t\treturn cloneUnlessOtherwiseSpecified(element, options)\n\t})\n}\n\nfunction getMergeFunction(key, options) {\n\tif (!options.customMerge) {\n\t\treturn deepmerge\n\t}\n\tvar customMerge = options.customMerge(key);\n\treturn typeof customMerge === 'function' ? customMerge : deepmerge\n}\n\nfunction getEnumerableOwnPropertySymbols(target) {\n\treturn Object.getOwnPropertySymbols\n\t\t? Object.getOwnPropertySymbols(target).filter(function(symbol) {\n\t\t\treturn Object.propertyIsEnumerable.call(target, symbol)\n\t\t})\n\t\t: []\n}\n\nfunction getKeys(target) {\n\treturn Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))\n}\n\nfunction propertyIsOnObject(object, property) {\n\ttry {\n\t\treturn property in object\n\t} catch(_) {\n\t\treturn false\n\t}\n}\n\n// Protects from prototype poisoning and unexpected merging up the prototype chain.\nfunction propertyIsUnsafe(target, key) {\n\treturn propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,\n\t\t&& !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,\n\t\t\t&& Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.\n}\n\nfunction mergeObject(target, source, options) {\n\tvar destination = {};\n\tif (options.isMergeableObject(target)) {\n\t\tgetKeys(target).forEach(function(key) {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(target[key], options);\n\t\t});\n\t}\n\tgetKeys(source).forEach(function(key) {\n\t\tif (propertyIsUnsafe(target, key)) {\n\t\t\treturn\n\t\t}\n\n\t\tif (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {\n\t\t\tdestination[key] = getMergeFunction(key, options)(target[key], source[key], options);\n\t\t} else {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(source[key], options);\n\t\t}\n\t});\n\treturn destination\n}\n\nfunction deepmerge(target, source, options) {\n\toptions = options || {};\n\toptions.arrayMerge = options.arrayMerge || defaultArrayMerge;\n\toptions.isMergeableObject = options.isMergeableObject || isMergeableObject;\n\t// cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()\n\t// implementations can use it. The caller may not replace it.\n\toptions.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;\n\n\tvar sourceIsArray = Array.isArray(source);\n\tvar targetIsArray = Array.isArray(target);\n\tvar sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;\n\n\tif (!sourceAndTargetTypesMatch) {\n\t\treturn cloneUnlessOtherwiseSpecified(source, options)\n\t} else if (sourceIsArray) {\n\t\treturn options.arrayMerge(target, source, options)\n\t} else {\n\t\treturn mergeObject(target, source, options)\n\t}\n}\n\ndeepmerge.all = function deepmergeAll(array, options) {\n\tif (!Array.isArray(array)) {\n\t\tthrow new Error('first argument should be an array')\n\t}\n\n\treturn array.reduce(function(prev, next) {\n\t\treturn deepmerge(prev, next, options)\n\t}, {})\n};\n\nvar deepmerge_1 = deepmerge;\n\nmodule.exports = deepmerge_1;\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';\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 * 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 * 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  if (hasTags(mediaFolder)) {\n    // Cannot substitute tags without global folder info\n    if (!globalFolders) {\n      return undefined;\n    }\n\n    mediaFolder = replaceTags(mediaFolder, globalFolders);\n  }\n\n  if (publicFolder === undefined) {\n    publicFolder = mediaFolder;\n  } else if (hasTags(publicFolder)) {\n    // Cannot substitute tags without global folder info\n    if (!globalFolders) {\n      return undefined;\n    }\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    publicFolder = replaceTags(publicFolder, globalFolders).replace(/^\\/@/, '@');\n  }\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 = mediaFolder.replace(/^\\.(?:\\/|$)/, '');\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 `/`. The configuration passed to\n        // the parser still holds the raw value, which field-level folders are resolved against\n        stripSlashes(baseFolder ?? '').replace(/^\\.$/, '')\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)\n      /^($|[.@])/.test(publicFolder) ? publicFolder : `/${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      mediaFolder: `/${stripSlashes(_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 * 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\n  const {\n    media_folder: _globalMediaFolder,\n    public_folder: _globalPublicFolder,\n    collections,\n    singletons,\n    asset_collections: assetCollections,\n  } = config;\n\n  const isGlobalFolderConfigured = _globalMediaFolder !== undefined;\n\n  // Normalize the media folder: an empty string, `/` and `.` are all considered as the root folder\n  const globalMediaFolder = isGlobalFolderConfigured\n    ? stripSlashes(_globalMediaFolder).replace(/^\\.$/, '')\n    : '';\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 = isGlobalFolderConfigured\n    ? _globalPublicFolder\n      ? `/${stripSlashes(_globalPublicFolder)}`.replace(/^\\/@/, '@')\n      : `/${globalMediaFolder}`\n    : '';\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 = isGlobalFolderConfigured\n    ? { ...allAssetsFolder, internalPath: globalMediaFolder, publicPath: globalPublicFolder }\n    : undefined;\n\n  const globalFolders = isGlobalFolderConfigured\n    ? { globalMediaFolder, globalPublicFolder }\n    : undefined;\n\n  const validCollections = getValidCollections({ collections });\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(assetFolders, {\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(assetFolders, {\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(assetFolders, { collectionName: '_singletons', files: singletons, globalFolders });\n  }\n\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  // 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\n  // the collection `folder` option says. The same goes for a `folder` with the `{{locale}}`\n  // placeholder, which names the locale folder in the middle of the path. Record the locale names\n  // so the asset paths can be matched there too; the entry folders already carry the same\n  // information in their `folderPathMap`. The locales are read per collection rather than from the\n  // site configuration, because a collection can define its own, and only the structures that put\n  // the locale in front matter\n  const localeFolderNameMap = 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  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 { 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 { _ } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\nimport merge from 'deepmerge';\n\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 =\n  'https://sveltiacms.app/en/docs/api/initialization#providing-a-full-configuration';\n\nconst SCHEMA_TIP_URL = 'https://sveltiacms.app/en/docs/config-basics#validation-and-autocomplete';\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 merge.all(objects);\n};\n","import { _, locale as appLocale } from '@sveltia/i18n';\n\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\nconst INVALID_FIELD_NAME_DOC_URL =\n  'https://sveltiacms.app/en/docs/troubleshooting#using-proper-naming-conventions';\n\nconst COMPATIBILITY_DOC_URL =\n  'https://sveltiacms.app/en/docs/migration/netlify-decap-cms#features-not-to-be-implemented';\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_DOC_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.\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);\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\n  if (nameCounts[name] === 1) {\n    addMessage({ strKey: `duplicate_${strKeyBase}`, context, values: { name }, collectors });\n\n    return false;\n  }\n\n  nameCounts[name] = (nameCounts[name] ?? 0) + 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 { _ } from '@sveltia/i18n';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { unsupportedBackends, validBackendNames } from '$lib/services/backends';\nimport { gitBackendServices } from '$lib/services/backends/git/services';\nimport { normalizeRootDir } from '$lib/services/backends/root-dir';\nimport { warnDeprecation } from '$lib/services/config/deprecations';\nimport { checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\nimport { makeLink } from '$lib/services/utils/string';\nimport { isWorkflowConfigured } 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_DOC_URL =\n  'https://sveltiacms.app/en/docs/migration/netlify-decap-cms#features-not-to-be-implemented';\n\nconst UNSUPPORTED_BACKEND_SUGGESTION_URL =\n  'https://sveltiacms.app/en/docs/backends#supported-backends';\n\nconst AUTH_DOC_URL = 'https://sveltiacms.app/en/docs/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' };\nconst OPEN_AUTHORING_DOC_URL = 'https://sveltiacms.app/en/docs/workflows/open';\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      UNSUPPORTED_BACKEND_DOC_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 only\n      app_id: appId,\n      open_authoring: openAuthoring,\n      // @ts-ignore GitHub only\n      auth_scope: authScope,\n    } = /** @type {GitBackend} */ (backend);\n\n    if (Array.isArray(authMethods) && !authMethods.length) {\n      errors.add(_('config.error.no_auth_methods'));\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    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    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. The site-level option is what counts here: a\n      // collection can opt out with its own `publish_mode`, but that only affects maintainers, who\n      // write to the configured repository; a contributor’s fork always goes through pull requests\n      if (cmsConfig.publish_mode !== 'editorial_workflow') {\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 (name === 'gitea' && !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    // @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 {\n  ALLOWED_FRONTMATTER_EXTENSIONS,\n  MARKDOWN_EXTENSIONS,\n  TEMPLATE_ENGINE_EXTENSIONS,\n} from '$lib/services/contents/file/constants';\n\n/**\n * @import { Field, FileExtension, FileFormat } from '$lib/types/public';\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\n  if (format === 'raw') {\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  // Check for front-matter format mismatches with non-markdown extensions\n  if (normalizedFormat.endsWith('-frontmatter')) {\n    // Front-matter format: yaml-frontmatter, toml-frontmatter, json-frontmatter\n    const fmFormatType = normalizedFormat.replace('-frontmatter', '');\n\n    // Template engines (njk) work with any front-matter format\n    if (TEMPLATE_ENGINE_EXTENSIONS.includes(normalizedExtension)) {\n      return false;\n    }\n\n    // For other extensions, front-matter only works with matching extension\n    return normalizedExtension !== fmFormatType;\n  }\n\n  // The 'frontmatter' auto-detect format works with markdown extensions and some template engines\n  // (already handled above), so reject it for other extensions\n  if (normalizedFormat === 'frontmatter') {\n    return !ALLOWED_FRONTMATTER_EXTENSIONS.includes(normalizedExtension);\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","import { 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 * 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 * Entry metadata property keys that can be used in the `filter`, `sortable_fields`, `view_groups`\n * and `view_filters` options in place of a field key path. These are resolved by\n * `getPropertyValue()` 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 * 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 * 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.\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\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 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\n    isFirstSegment = false;\n    matches = candidates.filter(({ name }) => name === key);\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","import {\n  DEFAULT_TRANSFORMATION_REGEX,\n  FIELD_TAG_PREFIX_REGEX,\n  TEMPLATE_TAG_REPLACE_REGEX,\n} from '$lib/services/common/template/constants';\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    [...template.matchAll(TEMPLATE_TAG_REPLACE_REGEX)].forEach(([, tag]) => {\n      // A transformation follows the tag name after a pipe. The name itself never contains one,\n      // so the first segment is the key path even when an argument does\n      const keyPath = tag.split('|')[0].trim();\n\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 { isObject } from '@sveltia/utils/object';\n\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\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 {\n    default: defaultValue,\n    output_code_only: outputCodeOnly = false,\n    keys = { code: 'code', lang: 'lang' },\n  } = /** @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  if (outputCodeOnly) {\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 { getRootFields } from '$lib/services/config/parser/utils/fields';\nimport { checkFieldReferences } from '$lib/services/config/parser/utils/references';\n\n/**\n * @import { FieldParserArgs } from '$lib/types/private';\n * @import { ComputeField } from '$lib/types/public';\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.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseComputeFieldConfig = ({ config, context, collectors }) => {\n  const { value } = /** @type {ComputeField} */ (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  if (fields?.length) {\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 { isCustomTimeZone } from '$lib/services/contents/fields/date-time/config';\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 * 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};\n","import { isObject } from '@sveltia/utils/object';\n\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","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 { 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  parseMediaLibraries({ config, context, collectors });\n  checkUnsupportedOptions({ ...args, UNSUPPORTED_OPTIONS });\n};\n","import { replaceTemplateTags } 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.\n * @param {string} template Template.\n * @returns {boolean} Result.\n */\nconst hasLocaleTag = (template) => {\n  let found = false;\n\n  replaceTemplateTags(template, (match, placeholder) => {\n    if (parseTransformations(placeholder).value === 'locale') {\n      found = true;\n    }\n\n    return match;\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 { addMessage, checkRegex } from '$lib/services/config/parser/utils/validator';\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 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.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const checkCommonFieldOptions = ({ config, context, collectors }) => {\n  const { pattern } = /** @type {Record<string, any>} */ (config);\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","/**\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 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 the same way as for a File/Image 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","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 * ListField,\n * ListFieldWithSubField,\n * ListFieldWithSubFields,\n * ListFieldWithTypes,\n * } from '$lib/types/public';\n * @import {\n * ConfigParserCollectors,\n * ConfigParserContext,\n * FieldParserArgs,\n * } from '$lib/types/private';\n */\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 * 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\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';\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\n  const value =\n    typeof defaultValue === 'string'\n      ? (isInteger ? Number.parseInt : Number.parseFloat)(defaultValue)\n      : 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. A value of another\n  // type is reported against the JSON schema\n  if (typeof step === 'number' && step <= 0) {\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 { TEMPLATE_TAG_REPLACE_REGEX } from '$lib/services/common/template/constants';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\nimport { hasLocalePlaceholder } from '$lib/services/contents/i18n/placeholder';\nimport { getPublishMode } 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  [...template.matchAll(TEMPLATE_TAG_REPLACE_REGEX)].some(\n    ([, tag]) => tag.split('|')[0].trim() === 'slug',\n  );\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  // Editorial 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    getPublishMode({ cmsConfig, collection }) === 'editorial_workflow' ||\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 { TEMPLATE_TAG_REPLACE_REGEX } from '$lib/services/common/template/constants';\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 { getCanonicalSlugKey, hasField } from '$lib/services/config/parser/utils/fields';\nimport { addMessage, checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\nimport { getPublishMode } 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 = [...reference.matchAll(TEMPLATE_TAG_REPLACE_REGEX)].map(([, tag]) => tag);\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 {ConfigParserContext} args.context Context.\n * @param {ConfigParserCollectors} args.collectors Collectors.\n */\nconst checkFieldReferences = ({ fieldConfig, fields, canonicalSlugKey, context, collectors }) => {\n  const { filters } = 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  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    getPublishMode({ cmsConfig, collection }) !== 'editorial_workflow'\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  // 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      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 { checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\n\n/**\n * @import { FieldParserArgs, UnsupportedOption } from '$lib/types/private';\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 * Parse and validate a RichText field configuration.\n * @param {FieldParserArgs} args Arguments.\n */\nexport const parseRichTextFieldConfig = (args) => {\n  checkUnsupportedOptions({ ...args, UNSUPPORTED_OPTIONS });\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 { getSubFields } from '$lib/services/config/parser/utils/fields';\nimport { addMessage } from '$lib/services/config/parser/utils/validator';\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 * 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  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  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 { isFormatMismatch } from '$lib/services/config/parser/collections/format';\nimport { checkPreviewPath } from '$lib/services/config/parser/collections/preview';\nimport { parseFields } from '$lib/services/config/parser/fields';\nimport { checkI18nOverrides } from '$lib/services/config/parser/i18n';\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 } = 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  parseFields(fields, context, collectors);\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\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 {\n  getCanonicalSlugKey,\n  hasField,\n  METADATA_KEYS,\n} from '$lib/services/config/parser/utils/fields';\nimport { addMessage, checkRegex } from '$lib/services/config/parser/utils/validator';\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 { 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 * 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 */\nconst DEFAULT_IDENTIFIER_FIELD = 'title';\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  // Without the option, the default is only relied on to make the slug of a new entry, which a\n  // custom slug template, or a slug that has to be typed in, makes its own way. Netlify/Decap CMS\n  // refuses to save such an entry, but its collections can’t be created in by default, so a\n  // configuration that worked there may simply never have needed the field; it’s a warning rather\n  // than an error for that reason\n  if (\n    create &&\n    getConfiguredSlugTemplate(collection) === undefined &&\n    !getSlugOptions(collection).editorRequired &&\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 { 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.\n  // @see https://github.com/decaporg/decap-cms/issues/513\n  if (template?.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 { pattern, i18n } = /** @type {CollectionSlugOptions} */ (slug);\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 { 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 } 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 */\nconst 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 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  checkFieldReferences({\n    ...args,\n    option: 'summary',\n    template: summary,\n    specialTags: SUMMARY_SPECIAL_TAGS,\n  });\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 { hasComparison } from '$lib/services/common/view';\nimport {\n  getCanonicalSlugKey,\n  hasField,\n  METADATA_KEYS,\n} from '$lib/services/config/parser/utils/fields';\nimport { addMessage, checkName } from '$lib/services/config/parser/utils/validator';\nimport {\n  parseCustomSortableFields,\n  parseViewOptions,\n} from '$lib/services/contents/collection/view/options';\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 * Internal sort keys added by `getSortConfig()` that don’t map to a field: `_summary` for the\n * generated entry summary and `_manual` for the reorder field.\n * @type {string[]}\n */\nconst INTERNAL_SORT_KEYS = ['_summary', '_manual'];\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    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 sortKeys = [...specialKeys, ...INTERNAL_SORT_KEYS];\n\n    [...keys, defaultKey].forEach((key) => {\n      if (key && !sortKeys.includes(key) && !hasField(fields, key)) {\n        addMessage({\n          strKey: 'invalid_sortable_field',\n          values: { 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","/* 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 { checkCollectionFilter } from '$lib/services/config/parser/collections/filter';\nimport { 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 { checkCollectionTemplates } 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 {\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    extension,\n    fields,\n    folder,\n    format,\n    index_file,\n    preview_path,\n    preview_path_date_field,\n    reorder,\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\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    parseFields(\n      index_file === true ? fields : (index_file.fields ?? fields),\n      { cmsConfig, collection, isIndexFile: true },\n      collectors,\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 `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  // 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  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","/* eslint-disable camelcase */\n\nimport { _ } from '@sveltia/i18n';\n\nimport { checkName } from '$lib/services/config/parser/utils/validator';\nimport { CLOUD_MEDIA_LIBRARY_NAMES } from '$lib/services/integrations/media-libraries/cloud';\n\n/**\n * @import { CmsConfig } from '$lib/types/public';\n * @import { ConfigParserCollectors } from '$lib/types/private';\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  if (Array.isArray(asset_collections)) {\n    const checkNameArgs = { nameCounts: {}, strKeyBase: 'asset_collection_name', collectors };\n\n    asset_collections.forEach(({ name }, index) => {\n      checkName({ ...checkNameArgs, name, index, context: { cmsConfig } });\n    });\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, e.g. a space, and a slash would even turn the slug into a path. An empty string is\n  // fine; it just joins the words together\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)) {\n    addMessage({\n      strKey: 'invalid_sanitize_replacement',\n      values: { replacement },\n      context: { cmsConfig },\n      collectors,\n    });\n  }\n};\n","import { isURL } from '@sveltia/utils/string';\n\nimport { 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 { 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 { parseSlugConfig } from '$lib/services/config/parser/slug';\nimport { addMessage, checkUnsupportedOptions } from '$lib/services/config/parser/utils/validator';\nimport { 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 * @todo Add more validations.\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) && !isURL(url.trim())) {\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  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(({ fields }, componentName) => {\n    parseFields(fields, { cmsConfig, componentName }, collectors);\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 a\n * nested collection, 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","import { isObject } from '@sveltia/utils/object';\n\nimport { getSegments } 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 = getSegments(current.$ref).reduce(\n      (/** @type {any} */ value, key) => value?.[key],\n      schema,\n    );\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    if (Array.isArray(a)) {\n        if (!Array.isArray(b)) {\n            return false;\n        }\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 (!deepCompareStrict(a[k], b[k])) {\n                return false;\n            }\n        }\n        return true;\n    }\n    return a === b;\n}\n","export function encodePointer(p) {\n    return encodeURI(escapePointer(p));\n}\nexport function escapePointer(p) {\n    return p.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n","import { encodePointer } from './pointer.js';\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    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 = new URL(id, baseURI.href);\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) {\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 = new URL(schema.$ref, baseURI.href);\n        url.hash = url.hash;\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 = new URL(schema.$recursiveRef, baseURI.href);\n        url.hash = url.hash;\n        Object.defineProperty(schema, '__absolute_recursive_ref__', {\n            enumerable: false,\n            value: url.href\n        });\n    }\n    if (schema.$anchor) {\n        const url = new URL('#' + schema.$anchor, baseURI.href);\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","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 = /^(\\d\\d):(\\d\\d):(\\d\\d)(\\.\\d+)?(z|[+-]\\d\\d(?::?\\d\\d)?)?$/i;\nconst HOSTNAME = /^(?=.{1,253}\\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\\.?$/i;\nconst URIREF = /^(?:[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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)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i;\nconst URL_ = /^(?:(?:https?|ftp):\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!10(?:\\.\\d{1,3}){3})(?!127(?:\\.\\d{1,3}){3})(?!169\\.254(?:\\.\\d{1,3}){2})(?!192\\.168(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u{00a1}-\\u{ffff}0-9]+-?)*[a-z\\u{00a1}-\\u{ffff}0-9]+)(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}0-9]+-?)*[a-z\\u{00a1}-\\u{ffff}0-9]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu;\nconst UUID = /^(?:urn: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 = (input) => {\n    if (input[0] === '\"')\n        return false;\n    const [name, host, ...rest] = input.split('@');\n    if (!name ||\n        !host ||\n        rest.length !== 0 ||\n        name.length > 64 ||\n        host.length > 253)\n        return false;\n    if (name[0] === '.' || name.endsWith('.') || name.includes('..'))\n        return false;\n    if (!/^[a-z0-9.-]+$/i.test(host) ||\n        !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name))\n        return false;\n    return host\n        .split('.')\n        .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part));\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) => input.length > 1 &&\n    input.length < 80 &&\n    (/^P\\d+([.,]\\d+)?W$/.test(input) ||\n        (/^P[\\dYMDTHS]*(\\d[.,]\\d+)?[YMDHS]$/.test(input) &&\n            /^P([.,\\d]+Y)?([.,\\d]+M)?([.,\\d]+D)?(T([.,\\d]+H)?([.,\\d]+M)?([.,\\d]+S)?)?$/.test(input)));\nfunction bind(r) {\n    return r.test.bind(r);\n}\nexport const format = {\n    date,\n    time: time.bind(undefined, false),\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 year = +matches[1];\n    const month = +matches[2];\n    const day = +matches[3];\n    return (month >= 1 &&\n        month <= 12 &&\n        day >= 1 &&\n        day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]));\n}\nfunction time(full, str) {\n    const matches = str.match(TIME);\n    if (!matches)\n        return false;\n    const hour = +matches[1];\n    const minute = +matches[2];\n    const second = +matches[3];\n    const timeZone = !!matches[5];\n    return (((hour <= 23 && minute <= 59 && second <= 59) ||\n        (hour == 23 && minute == 59 && second == 60)) &&\n        (!full || timeZone));\n}\nconst DATE_TIME_SEPARATOR = /t|\\s/i;\nfunction date_time(str) {\n    const dateTime = str.split(DATE_TIME_SEPARATOR);\n    return dateTime.length == 2 && date(dateTime[0]) && time(true, dateTime[1]);\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","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","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';\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 (let i = 0; i < $anyOf.length; i++) {\n            const subSchema = $anyOf[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            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 (let i = 0; i < $allOf.length; i++) {\n            const subSchema = $allOf[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            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 conditionResult = validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid;\n        if (conditionResult) {\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 (!(key in instance)) {\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 (key in instance) {\n                    const required = $dependentRequired[key];\n                    for (const dependantKey of required) {\n                        if (!(dependantKey in instance)) {\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 in $dependentSchemas) {\n                const keywordLocation = `${schemaLocation}/dependentSchemas`;\n                if (key in instance) {\n                    const result = validate(instance, $dependentSchemas[key], 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 (key in instance) {\n                    const propsOrSchema = $dependencies[key];\n                    if (Array.isArray(propsOrSchema)) {\n                        for (const dependantKey of propsOrSchema) {\n                            if (!(dependantKey in instance)) {\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 in $properties) {\n                if (!(key in instance)) {\n                    continue;\n                }\n                const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`;\n                const result = validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`);\n                if (result.valid) {\n                    evaluated[key] = thisEvaluated[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 in $patternProperties) {\n                const regex = new RegExp(pattern, 'u');\n                const subSchema = $patternProperties[pattern];\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                    if (result.valid) {\n                        evaluated[key] = thisEvaluated[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 &&\n                    $maxContains === undefined &&\n                    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            const remainder = instance % $multipleOf;\n            if (Math.abs(0 - remainder) >= 1.1920929e-7 &&\n                Math.abs($multipleOf - remainder) >= 1.1920929e-7) {\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","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","import { Validator } from '@cfworker/json-schema';\nimport { isObject } from '@sveltia/utils/object';\n\nimport { decodeSegment, getSegments } 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 getSegments(node.$ref).reduce(\n        (/** @type {any} */ target, key) => target?.[key],\n        schema,\n      );\n    }\n\n    return node?.[segment];\n  }, schema);\n\n/**\n * Resolve an instance location within the configuration.\n * @param {any} config Raw CMS configuration.\n * @param {string} location Instance location.\n * @returns {any} Value at that location.\n */\nconst resolveInstance = (config, location) =>\n  getSegments(location).reduce((/** @type {any} */ value, segment) => value?.[segment], config);\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 = resolveInstance(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 { _ } from '@sveltia/i18n';\nimport { getHash } from '@sveltia/utils/crypto';\nimport { isObject } from '@sveltia/utils/object';\nimport { isURL } from '@sveltia/utils/string';\nimport merge from 'deepmerge';\nimport { stringify } from 'yaml';\n\nimport { allAssetFolders } from '$lib/services/assets/folders';\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 { allEntryFolders } from '$lib/services/contents';\nimport { prefs } from '$lib/services/user/prefs.svelte';\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/**\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 * @todo Normalize configuration object.\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  });\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 parser and config viewer\n    Object.assign(rawCmsConfig, rawConfig);\n\n    validateConfigSchema({ config: rawConfig, schemas: getConfigSchemas(), collectors });\n    parseCmsConfig(rawConfig, 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    /** @type {InternalCmsConfig} */\n    const config = structuredClone(rawConfig);\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\n    config.collections?.forEach((collection) => {\n      if ('folder' in collection && (collection.folder === '.' || collection.folder === '/')) {\n        collection.folder = '';\n      }\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    cmsConfigVersion.current = await getHash(stringify(config));\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 EntrancePage from '$lib/components/entrance/entrance-page.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 { initAppLocale } from '$lib/services/app/i18n';\n  import {\n    announcedPageStatus,\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 {\n    /* eslint-disable prefer-const */\n    config,\n    /* eslint-enable prefer-const */\n  } = $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    initCmsConfig(config);\n  });\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    <LocaleLoadErrorToast />\n    <UpdateNotification />\n    <ForkPermissionDialog />\n    {#if backend.current}\n      <BackendStatusIndicator />\n    {/if}\n    {#if user.account && dataLoaded.current}\n      <OpenAuthoringIndicator />\n    {/if}\n    <div role=\"none\" class=\"main\">\n      {#if user.account && dataLoaded.current && transitioned}\n        <MainRouter />\n      {:else}\n        <EntrancePage />\n      {/if}\n    </div>\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    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\n          &::view-transition-new(page-root) {\n            animation: 100ms ease-in both slide-in-from-left-rtl;\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\n          &::view-transition-new(page-root) {\n            animation: 100ms ease-in both slide-in-from-right-rtl;\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  .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","/**\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 =\n  'https://sveltiacms.app/en/docs/migration/netlify-decap-cms#features-not-to-be-implemented';\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","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';\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 { name, label, required: requiredOption } = normalizeFieldConfig(field);\n\n  return {\n    locale: locale ?? fieldState.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: label || name || '',\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, schema } = customFieldType;\n\n  if (typeof control !== 'string') {\n    return { control, preview, 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    schema,\n  };\n};\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';\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  if (!(target instanceof Element)) {\n    throw new TypeError('The `target` option for `CMS.renderRichText()` must be an element');\n  }\n\n  if (typeof value !== 'string') {\n    throw new TypeError('The `value` option for `CMS.renderRichText()` must be a string');\n  }\n\n  if (fieldConfig !== undefined && !isObject(fieldConfig)) {\n    throw new TypeError('The `fieldConfig` option for `CMS.renderRichText()` must be 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 `rich-text.d.ts` file\nexport { renderRichText };\n","import { isObject } from '@sveltia/utils/object';\nimport BundledReact from 'react';\nimport { mount } from 'svelte';\n\nimport App from '$lib/components/app.svelte';\nimport { COMPATIBILITY_URL, UNSUPPORTED_FUNC_NAMES } from '$lib/services/api/compatibility';\nimport { SUPPORTED_EVENT_TYPES } from '$lib/services/api/events';\nimport { getFieldTypeDefinition } from '$lib/services/api/field-types';\nimport { preloadImmutable } from '$lib/services/api/immutable';\nimport { isReactComponent } from '$lib/services/api/react';\nimport { preloadReactDom } from '$lib/services/api/react-dom';\nimport {\n  customComponentRegistry,\n  customFieldTypeRegistry,\n  customFileFormatRegistry,\n  customPreviewStyleRegistry,\n  customPreviewTemplateRegistry,\n  eventHookRegistry,\n} from '$lib/services/api/registries';\nimport { prefetchCmsConfig } from '$lib/services/config/loader';\nimport { BUILTIN_FIELD_TYPES } from '$lib/services/contents/fields';\nimport {\n  getSelectorTagNames,\n  isValidSelector,\n} from '$lib/services/contents/fields/rich-text/components/utils';\nimport { BUILTIN_FILE_FORMATS } from '$lib/services/contents/file/constants';\nimport { isNonEmptyString } from '$lib/services/utils/string';\n\nimport { renderRichText } from './rich-text';\n// Don’t use `$lib` above, or the function will not be declared in the generated `index.d.ts` file\n\n/**\n * @import {\n * AppEventListener,\n * CmsConfig,\n * CustomFieldControl,\n * CustomFieldPreview,\n * CustomFieldSchema,\n * CustomPreviewTemplate,\n * EditorComponentDefinition,\n * FieldTypeDefinition,\n * FileFormatter,\n * FileParser,\n * } from '../../types/public';\n */\n// Don’t use `$lib` in `from` above, or type declarations will not be exported\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;\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  if (config !== undefined && !isObject(config)) {\n    throw new TypeError('The `config` option for `CMS.init()` must be an object');\n  }\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/**\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  if (!isNonEmptyString(name)) {\n    throw new TypeError('The `name` option for `CMS.getFieldType()` must be a non-empty string');\n  }\n\n  return getFieldTypeDefinition(name);\n};\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.\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  if (!isNonEmptyString(name)) {\n    throw new TypeError(\n      'The `name` option for `CMS.registerCustomFormat()` must be a non-empty string',\n    );\n  }\n\n  if (!isNonEmptyString(extension)) {\n    throw new TypeError(\n      'The `extension` option for `CMS.registerCustomFormat()` must be a non-empty string',\n    );\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  if (typeof fromFile !== 'undefined' && typeof fromFile !== 'function') {\n    throw new TypeError(\n      'The `fromFile` option for `CMS.registerCustomFormat()` must be a function',\n    );\n  }\n\n  if (typeof toFile !== 'undefined' && typeof toFile !== 'function') {\n    throw new TypeError('The `toFile` option for `CMS.registerCustomFormat()` must be 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/**\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.\n * @param {EditorComponentDefinition} 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, `toBlock` is not a\n * function, `toPreview` is given but not a function, `fields` is not an array, or the HTML options\n * are invalid: `htmlSelector`, `fromBlockHTML` and `toBlockHTML` must be given together, and\n * `htmlSelector` must be a valid CSS selector naming the element types it matches.\n * @see https://decapcms.org/docs/custom-widgets/#registereditorcomponent\n * @see https://sveltiacms.app/en/docs/api/editor-components\n */\nconst registerEditorComponent = (definition) => {\n  if (!definition || typeof definition !== 'object') {\n    throw new TypeError(\n      'The `definition` option for `CMS.registerEditorComponent()` must be an object',\n    );\n  }\n\n  if (!isNonEmptyString(definition.id)) {\n    throw new TypeError('The `definition.id` must be a non-empty string');\n  }\n\n  if (definition.label !== undefined && !isNonEmptyString(definition.label)) {\n    throw new TypeError('The `definition.label` must be a non-empty string');\n  }\n\n  if (typeof definition.pattern !== 'object' || !(definition.pattern instanceof RegExp)) {\n    throw new TypeError('The `definition.pattern` must be a RegExp');\n  }\n\n  if (typeof definition.toBlock !== 'function') {\n    throw new TypeError('The `definition.toBlock` must be a function');\n  }\n\n  if (definition.toPreview !== undefined && typeof definition.toPreview !== 'function') {\n    throw new TypeError('The `definition.toPreview` must be a function');\n  }\n\n  if (!Array.isArray(definition.fields)) {\n    throw new TypeError('The `definition.fields` must be an array');\n  }\n\n  const { htmlSelector, fromBlockHTML, toBlockHTML } = definition;\n  const htmlOptions = [htmlSelector, fromBlockHTML, toBlockHTML];\n\n  if (htmlOptions.some((option) => option !== undefined)) {\n    if (htmlOptions.includes(undefined)) {\n      throw new TypeError(\n        'The `definition.htmlSelector`, `definition.fromBlockHTML` and `definition.toBlockHTML` ' +\n          'must be given together',\n      );\n    }\n\n    if (!isNonEmptyString(htmlSelector) || !isValidSelector(htmlSelector)) {\n      throw new TypeError('The `definition.htmlSelector` must be a valid CSS selector');\n    }\n\n    if (!getSelectorTagNames(htmlSelector)) {\n      throw new TypeError(\n        'Each selector in the `definition.htmlSelector` must name the element type it matches',\n      );\n    }\n\n    if (typeof fromBlockHTML !== 'function') {\n      throw new TypeError('The `definition.fromBlockHTML` must be a function');\n    }\n\n    if (typeof toBlockHTML !== 'function') {\n      throw new TypeError('The `definition.toBlockHTML` must be a function');\n    }\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/**\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/**\n * Register a custom stylesheet to be applied to the entry preview pane. Multiple stylesheets can\n * be registered.\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 * @throws {TypeError} If `style` is not a non-empty string, `raw` is not a boolean, or `style` is\n * not a valid URL or file path when `raw` is `false`.\n * @see https://decapcms.org/docs/customization/#registerpreviewstyle\n * @see https://sveltiacms.app/en/docs/api/preview-styles\n */\nconst registerPreviewStyle = (style, { raw = false } = {}) => {\n  if (!isNonEmptyString(style)) {\n    throw new TypeError(\n      'The `style` option for `CMS.registerPreviewStyle()` must be a non-empty string',\n    );\n  }\n\n  if (typeof raw !== 'boolean') {\n    throw new TypeError('The `raw` option for `CMS.registerPreviewStyle()` must be a boolean');\n  }\n\n  const base = window.location.href;\n\n  if (!raw && !URL.canParse(style, base)) {\n    throw new TypeError(\n      'The `style` option for `CMS.registerPreviewStyle()` must be a valid URL or file path ' +\n        'when `raw` is false',\n    );\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    : // Convert relative URLs to absolute to ensure they work in the preview iframe, which has a\n      // unique blob URL as its origin\n      new URL(style, base).href;\n\n  customPreviewStyleRegistry.add(url);\n};\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  if (!isNonEmptyString(name)) {\n    throw new TypeError(\n      'The `name` option for `CMS.registerPreviewTemplate()` must be a non-empty string',\n    );\n  }\n\n  if (!isReactComponent(component)) {\n    throw new TypeError(\n      'The `component` option for `CMS.registerPreviewTemplate()` must be a React component',\n    );\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/**\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.\n * @param {string} name Field type name, which cannot be the name of a built-in field type.\n * @param {CustomFieldControl | string} control React component for the edit pane, or the name of\n * another custom field type whose control is reused.\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 not a non-empty string, `control` is neither a React component\n * nor a string, `preview` is given but not a React component, or `schema` is given but not an\n * 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  if (!isNonEmptyString(name)) {\n    throw new TypeError(\n      'The `name` option for `CMS.registerFieldType()` must be a non-empty string',\n    );\n  }\n\n  if (/** @type {string[]} */ (BUILTIN_FIELD_TYPES).includes(name)) {\n    throw new Error(\n      `The field type name \"${name}\" is reserved for a built-in field type. ` +\n        'Choose a different name for your custom field type.',\n    );\n  }\n\n  if (!isReactComponent(control) && typeof control !== 'string') {\n    throw new TypeError(\n      'The `control` option for `CMS.registerFieldType()` must be a React component or a string',\n    );\n  }\n\n  if (preview !== undefined && !isReactComponent(preview)) {\n    throw new TypeError(\n      'The `preview` option for `CMS.registerFieldType()` must be a React component',\n    );\n  }\n\n  if (schema !== undefined && !isObject(schema)) {\n    throw new TypeError('The `schema` option for `CMS.registerFieldType()` must be an object');\n  }\n\n  customFieldTypeRegistry.set(name, { control, preview, schema });\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/**\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    registerEditorComponent,\n    registerEventListener,\n    registerFieldType,\n    registerPreviewStyle,\n    registerPreviewTemplate,\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      let message = '';\n\n      if (UNSUPPORTED_FUNC_NAMES.includes(key)) {\n        message =\n          'CMS.%s() is not supported in Sveltia CMS, and we don’t have any plans to implement it.';\n      }\n\n      if (message) {\n        // eslint-disable-next-line no-console\n        console.warn(`${message} See %s for compatibility information.`, key, COMPATIBILITY_URL);\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  registerEditorComponent,\n  registerEventListener,\n  registerFieldType,\n  registerPreviewStyle,\n  registerPreviewTemplate,\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';\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// 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"}