/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

// Polyfill for import.meta in CommonJS context
if (typeof import_meta === 'undefined') {
  var import_meta = {
    url: typeof __filename !== 'undefined' ? 'file://' + __filename : 'file:///obsidian-plugin'
  };
}

var swt=Object.create;var nD=Object.defineProperty;var awt=Object.getOwnPropertyDescriptor;var lwt=Object.getOwnPropertyNames;var cwt=Object.getPrototypeOf,uwt=Object.prototype.hasOwnProperty;var oPe=t=>{throw TypeError(t)};var dwt=(t,e,n)=>e in t?nD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var C=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tt=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),zn=(t,e)=>{for(var n in e)nD(t,n,{get:e[n],enumerable:!0})},iPe=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of lwt(e))!uwt.call(t,o)&&o!==n&&nD(t,o,{get:()=>e[o],enumerable:!(r=awt(e,o))||r.enumerable});return t};var N=(t,e,n)=>(n=t!=null?swt(cwt(t)):{},iPe(e||!t||!t.__esModule?nD(n,"default",{value:t,enumerable:!0}):n,t)),fwt=t=>iPe(nD({},"__esModule",{value:!0}),t);var I=(t,e,n)=>dwt(t,typeof e!="symbol"?e+"":e,n),pwt=(t,e,n)=>e.has(t)||oPe("Cannot "+n);var GQ=(t,e,n)=>e.has(t)?oPe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n);var sPe=(t,e,n)=>(pwt(t,e,"access private method"),n);function aPe(t,e=0){return(al[t[e+0]]+al[t[e+1]]+al[t[e+2]]+al[t[e+3]]+"-"+al[t[e+4]]+al[t[e+5]]+"-"+al[t[e+6]]+al[t[e+7]]+"-"+al[t[e+8]]+al[t[e+9]]+"-"+al[t[e+10]]+al[t[e+11]]+al[t[e+12]]+al[t[e+13]]+al[t[e+14]]+al[t[e+15]]).toLowerCase()}var al,lPe=C(()=>{al=[];for(let t=0;t<256;++t)al.push((t+256).toString(16).slice(1))});function ZQ(){if(!YQ){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");YQ=crypto.getRandomValues.bind(crypto)}return YQ(mwt)}var YQ,mwt,cPe=C(()=>{mwt=new Uint8Array(16)});var hwt,JQ,uPe=C(()=>{hwt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),JQ={randomUUID:hwt}});function gwt(t,e,n){if(JQ.randomUUID&&!e&&!t)return JQ.randomUUID();t=t||{};let r=t.random??t.rng?.()??ZQ();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return aPe(r)}var si,dPe=C(()=>{uPe();cPe();lPe();si=gwt});var qh=C(()=>{dPe()});var Qi=C(()=>{});var rD=C(()=>{});var XQ,jy,No,uo,Sd,Af,ywt,wwt,vwt,xwt,bwt,Cwt,QQ,pPe,mPe,oD,bu,eee,iD,NS,sD,tee,aD,nee,ree,ZV,oee,lD,JV,XV,iee,QV,_wt,see,eW,Td,Vy,Pc,ZE,Ec,Ex,Gh,um,OS,aee,Cu,tW,hPe,JE,bt,nW,rW,lee,gPe,XE,Hn,kf,It=C(()=>{qh();Qi();rD();XQ="https://api.brevilabs.com/v1",jy="https://models.brevilabs.com/v1",No="copilot-chat-view",uo="user",Sd="ai",Af="copilot",ywt=`${Af}/copilot-conversations`,wwt=`${Af}/copilot-custom-prompts`,vwt=`${Af}/memory`,xwt=`${Af}/system-prompts`,bwt=`${Af}/projects`,Cwt="",QQ=Af,pPe=`You are Obsidian Copilot, a helpful assistant that integrates AI to Obsidian note-taking.
  1. Never mention that you do not have access to something. Always rely on the user provided context.
  2. Always answer to the best of your knowledge. If you are unsure about something, say so and ask the user to provide more context.
  3. If the user mentions "note", it most likely means an Obsidian note in the vault, not the generic meaning of a note.
  4. If the user mentions "@vault", it means the user wants you to search the Obsidian vault for information relevant to the query. The search results will be provided to you in the context along with the user query, read it carefully and answer the question based on the information provided. If there's no relevant information in the vault, just say so.
  5. If the user mentions any other tool with the @ symbol, check the context for their results. If nothing is found, just ignore the @ symbol in the query.
  6. Always use $'s instead of \\[ etc. for LaTeX equations.
  7. When showing note titles, use [[title]] format and do not wrap them in \` \`.
  8. When showing **Obsidian internal** image links, use ![[link]] format and do not wrap them in \` \`.
  9. When showing **web** image links, use ![link](url) format and do not wrap them in \` \`.
  10. When generating a table, format as github markdown tables, however, for table headings, immediately add ' |' after the table heading.
  11. Always respond in the language of the user's query.
  12. Do NOT mention the additional context provided such as getCurrentTime and getTimeRangeMs if it's irrelevant to the user message.
  13. If the user mentions "tags", it most likely means tags in Obsidian note properties.
  14. YouTube URLs: If the user provides YouTube URLs in their message, transcriptions will be automatically fetched and provided to you. You don't need to do anything special - just use the transcription content if available.
  15. For markdown lists, always use '- ' (hyphen followed by exactly one space) for bullet points, with no leading spaces before the hyphen. Never use '*' (asterisk) for bullets.`,mPe=`Return the new note content or canvas JSON in <writeFile> tags.

  # Steps to find the the target notes
  1. Extract the target note information from user message and find out the note path from the context below.
  2. If target note is not specified, use the <active_note> as the target note.
  3. If still failed to find the target note or the note path, ask the user to specify the target note.

  # Examples

  Input: Add a new section to note A
  Output:
  <writeFile>
  <path>path/to/file.md</path>
  <content>The FULL CONTENT of the note A with added section goes here</content>
  </writeFile>

  Input: Create a new canvas with "Hello, world!"
  Output:
  <writeFile>
  <path>path/to/file.canvas</path>
  <content>
  {
    "nodes": [
      {
        "id": "1",
        "type": "text",
        "text": "Hello, world!",
        "x": 0,
        "y": 0,
        "width": 200,
        "height": 50
      }
    ],
    "edges": []
  }
  </content>
  </writeFile>

  Input: Create a canvas with a file node and a group
  Output:
  <writeFile>
  <path>path/to/file.canvas</path>
  <content>
  {
    "nodes": [
      {"id": "1", "type": "file", "file": "note.md", "subpath": "#heading", "x": 100, "y": 100, "width": 300, "height": 200, "color": "2"},
      {"id": "2", "type": "group", "label": "My Group", "x": 50, "y": 50, "width": 400, "height": 300, "color": "1"},
      {"id": "3", "type": "link", "url": "https://example.com", "x": 500, "y": 100, "width": 200, "height": 100, "color": "#FF5733"}
    ],
    "edges": [
      {"id": "e1-2", "fromNode": "1", "toNode": "3", "fromSide": "right", "toSide": "left", "fromEnd": "arrow", "toEnd": "none", "color": "3", "label": "references"}
    ]
  }
  </content>
  </writeFile>

  # Canvas JSON Format (JSON Canvas spec 1.0)
  Required node fields: id, type, x, y, width, height
  Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
  Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
  Required edge fields: id, fromNode, toNode
  Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
  All IDs must be unique. Edge nodes must reference existing node IDs.
  Position nodes with reasonable spacing and logical visual flow.
  `,oD="note_context",bu="selected_text",eee="web_selected_text",iD="variable",NS="variable_note",sD="embedded_pdf",tee="embedded_note",aD="dataview_block",nee="retrieved_document",ree="web_tab_context",ZV="active_web_tab",oee="youtube_video_context",lD="{activeWebTab}",JV=6e3,XV=.4,iee=448e3,QV=3e4,_wt=30,see=5*60*1e3,eW=16,Td={DEFAULT:"",READING_FILES:"Reading files",SEARCHING_WEB:"Searching the web",READING_FILE_TREE:"Reading file tree",COMPACTING:"Compacting"},Vy={SETTINGS:"settings",EXPIRED_MODAL:"expired_modal",CHAT_MODE_SELECT:"chat_mode_select",MODE_SELECT_TOOLTIP:"mode_select_tooltip"},Pc={MAX_TOKENS:6e3,TEMPERATURE:.1,REASONING_EFFORT:"low",VERBOSITY:"medium"},ZE=131072,Ec=(y=>(y.OPENROUTERAI="openrouterai",y.OPENAI="openai",y.OPENAI_FORMAT="3rd party (openai-format)",y.ANTHROPIC="anthropic",y.GOOGLE="google",y.XAI="xai",y.AMAZON_BEDROCK="amazon-bedrock",y.AZURE_OPENAI="azure openai",y.GROQ="groq",y.OLLAMA="ollama",y.LM_STUDIO="lm-studio",y.COPILOT_PLUS="copilot-plus",y.MISTRAL="mistralai",y.DEEPSEEK="deepseek",y.COHEREAI="cohereai",y.SILICONFLOW="siliconflow",y.GITHUB_COPILOT="github-copilot",y))(Ec||{}),Ex={reasoning:"This model supports general reasoning tasks.",vision:"This model supports image inputs.",websearch:"This model can access the internet."},Gh=[{name:"copilot-plus-flash",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,core:!0,plusExclusive:!0,projectEnabled:!1,capabilities:["vision"]},{name:"google/gemini-2.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,core:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-3.5-flash",provider:"openrouterai",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision","reasoning"]},{name:"gpt-5.5",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"gpt-5.4-mini",provider:"openai",enabled:!0,isBuiltIn:!0,core:!0,capabilities:["vision"]},{name:"claude-sonnet-4-6",provider:"anthropic",enabled:!0,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-flash-lite",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"gemini-2.5-flash",provider:"google",enabled:!0,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"google/gemini-3.1-pro-preview",provider:"openrouterai",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"google/gemini-2.5-pro",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5.5",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"openai/gpt-5.4-mini",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"grok-4.3",provider:"xai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"x-ai/grok-4.3",provider:"openrouterai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"gpt-4.1-mini",provider:"openai",enabled:!1,isBuiltIn:!0,core:!1,projectEnabled:!0,capabilities:["vision"]},{name:"claude-opus-4-7",provider:"anthropic",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"claude-haiku-4-5",provider:"anthropic",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-3.1-pro-preview",provider:"google",enabled:!1,isBuiltIn:!0,capabilities:["vision","reasoning"]},{name:"gemini-2.5-pro",provider:"google",enabled:!1,isBuiltIn:!0,projectEnabled:!0,capabilities:["vision"]},{name:"deepseek-chat",provider:"deepseek",enabled:!1,isBuiltIn:!0},{name:"deepseek-reasoner",provider:"deepseek",enabled:!1,isBuiltIn:!0,capabilities:["reasoning"]},{name:"deepseek-ai/DeepSeek-V3",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1"},{name:"deepseek-ai/DeepSeek-R1",provider:"siliconflow",enabled:!1,isBuiltIn:!1,baseUrl:"https://api.siliconflow.com/v1",capabilities:["reasoning"]}],um=(d=>(d.OPENAI="openai",d.OPENROUTERAI="openrouterai",d.COHEREAI="cohereai",d.GOOGLE="google",d.AZURE_OPENAI="azure openai",d.OLLAMA="ollama",d.LM_STUDIO="lm-studio",d.OPENAI_FORMAT="3rd party (openai-format)",d.COPILOT_PLUS="copilot-plus",d.COPILOT_PLUS_JINA="copilot-plus-jina",d.SILICONFLOW="siliconflow",d))(um||{}),OS=[{name:"copilot-plus-small",provider:"copilot-plus",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0},{name:"copilot-plus-large",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,believerExclusive:!0,dimensions:1024},{name:"copilot-plus-multilingual",provider:"copilot-plus-jina",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,plusExclusive:!0,dimensions:512},{name:"openai/text-embedding-3-small",provider:"openrouterai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-small",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"text-embedding-3-large",provider:"openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"embed-multilingual-light-v3.0",provider:"cohereai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"text-embedding-004",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"gemini-embedding-001",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"gemini-embedding-2-preview",provider:"google",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0},{name:"azure-openai",provider:"azure openai",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0},{name:"Qwen/Qwen3-Embedding-0.6B",provider:"siliconflow",enabled:!0,isBuiltIn:!0,isEmbeddingModel:!0,core:!0,baseUrl:"https://api.siliconflow.com/v1"}],aee="nomic-embed-text",Cu={openrouterai:{label:"OpenRouter",host:"https://openrouter.ai/api/v1/",curlBaseURL:"https://openrouter.ai/api/v1",keyManagementURL:"https://openrouter.ai/keys",listModelURL:"https://openrouter.ai/api/v1/models",testModel:"openai/gpt-5.4-mini"},google:{label:"Gemini",host:"https://generativelanguage.googleapis.com",curlBaseURL:"https://generativelanguage.googleapis.com/v1beta",keyManagementURL:"https://makersuite.google.com/app/apikey",listModelURL:"https://generativelanguage.googleapis.com/v1beta/models",testModel:"gemini-2.5-flash"},anthropic:{label:"Anthropic",host:"https://api.anthropic.com/",curlBaseURL:"https://api.anthropic.com",keyManagementURL:"https://console.anthropic.com/settings/keys",listModelURL:"https://api.anthropic.com/v1/models",testModel:"claude-sonnet-4-6"},openai:{label:"OpenAI",host:"https://api.openai.com",curlBaseURL:"https://api.openai.com/v1",keyManagementURL:"https://platform.openai.com/api-keys",listModelURL:"https://api.openai.com/v1/models",testModel:"gpt-5.5"},xai:{label:"XAI",host:"https://api.x.ai/v1",curlBaseURL:"https://api.x.ai/v1",keyManagementURL:"https://console.x.ai",listModelURL:"https://api.x.ai/v1/models",testModel:"grok-4.3"},"azure openai":{label:"Azure",host:"https://<resource>.services.ai.azure.com/models",curlBaseURL:"https://<resource>.services.ai.azure.com/models",keyManagementURL:"https://ai.azure.com",listModelURL:""},groq:{label:"Groq",host:"https://api.groq.com/openai",curlBaseURL:"https://api.groq.com/openai/v1",keyManagementURL:"https://console.groq.com/keys",listModelURL:"https://api.groq.com/openai/v1/models",testModel:"llama3-8b-8192"},cohereai:{label:"Cohere",host:"https://api.cohere.ai/compatibility/v1",curlBaseURL:"https://api.cohere.ai/compatibility/v1",keyManagementURL:"https://dashboard.cohere.ai/api-keys",listModelURL:"https://api.cohere.com/v1/models",testModel:"command-r"},siliconflow:{label:"SiliconFlow",host:"https://api.siliconflow.com/v1",curlBaseURL:"https://api.siliconflow.com/v1",keyManagementURL:"https://cloud.siliconflow.com/me/account/ak",listModelURL:"https://api.siliconflow.com/v1/models",testModel:"deepseek-ai/DeepSeek-V3"},ollama:{label:"Ollama",host:"http://localhost:11434/v1/",curlBaseURL:"http://localhost:11434",keyManagementURL:"",listModelURL:""},"lm-studio":{label:"LM Studio",host:"http://localhost:1234/v1",curlBaseURL:"http://localhost:1234/v1",keyManagementURL:"",listModelURL:""},"3rd party (openai-format)":{label:"OpenAI Format",host:"https://api.example.com/v1",curlBaseURL:"https://api.example.com/v1",keyManagementURL:"",listModelURL:""},mistralai:{label:"Mistral",host:"https://api.mistral.ai/v1",curlBaseURL:"https://api.mistral.ai/v1",keyManagementURL:"https://console.mistral.ai/api-keys",listModelURL:"https://api.mistral.ai/v1/models",testModel:"mistral-tiny-latest"},deepseek:{label:"DeepSeek",host:"https://api.deepseek.com/",curlBaseURL:"https://api.deepseek.com",keyManagementURL:"https://platform.deepseek.com/api-keys",listModelURL:"https://api.deepseek.com/models",testModel:"deepseek-chat"},"amazon-bedrock":{label:"Amazon Bedrock",host:"https://bedrock-runtime.{region}.amazonaws.com",curlBaseURL:"https://bedrock-runtime.{region}.amazonaws.com",keyManagementURL:"https://console.aws.amazon.com/iam/home#/security_credentials",listModelURL:""},"copilot-plus":{label:"Copilot Plus",host:jy,curlBaseURL:jy,keyManagementURL:"",listModelURL:""},"copilot-plus-jina":{label:"Copilot Plus",host:jy,curlBaseURL:jy,keyManagementURL:"",listModelURL:""},"github-copilot":{label:"GitHub Copilot",host:"https://api.githubcopilot.com",curlBaseURL:"https://api.githubcopilot.com",keyManagementURL:"https://github.com/settings/apps/authorizations",listModelURL:""}},tW={anthropic:"anthropicApiKey",openai:"openAIApiKey","azure openai":"azureOpenAIApiKey",google:"googleApiKey",groq:"groqApiKey",openrouterai:"openRouterAiApiKey",cohereai:"cohereApiKey",xai:"xaiApiKey","copilot-plus":"plusLicenseKey",mistralai:"mistralApiKey",deepseek:"deepseekApiKey","amazon-bedrock":"amazonBedrockApiKey",siliconflow:"siliconflowApiKey","github-copilot":"githubCopilotToken"},hPe=["NEVER","ON STARTUP","ON MODE SWITCH"],JE=(n=>(n.ENTER="enter",n.SHIFT_ENTER="shift+enter",n))(JE||{}),bt={TRIGGER_QUICK_COMMAND:"trigger-quick-command",CLEAR_LOCAL_COPILOT_INDEX:"clear-local-copilot-index",CLEAR_COPILOT_CACHE:"clear-copilot-cache",COUNT_WORD_AND_TOKENS_SELECTION:"count-word-and-tokens-selection",COUNT_TOTAL_VAULT_TOKENS:"count-total-vault-tokens",DEBUG_WORD_COMPLETION:"debug-word-completion",FORCE_REINDEX_VAULT_TO_COPILOT_INDEX:"force-reindex-vault-to-copilot-index",GARBAGE_COLLECT_COPILOT_INDEX:"garbage-collect-copilot-index",INDEX_VAULT_TO_COPILOT_INDEX:"index-vault-to-copilot-index",INSPECT_COPILOT_INDEX_BY_NOTE_PATHS:"copilot-inspect-index-by-note-paths",LIST_INDEXED_FILES:"copilot-list-indexed-files",LOAD_COPILOT_CHAT_CONVERSATION:"load-copilot-chat-conversation",NEW_CHAT:"new-chat",OPEN_COPILOT_CHAT_WINDOW:"chat-open-window",SEARCH_ORAMA_DB:"copilot-search-orama-db",TOGGLE_COPILOT_CHAT_WINDOW:"chat-toggle-window",ADD_SELECTION_TO_CHAT_CONTEXT:"add-selection-to-chat-context",ADD_WEB_SELECTION_TO_CHAT_CONTEXT:"add-web-selection-to-chat-context",ADD_CUSTOM_COMMAND:"add-custom-command",APPLY_CUSTOM_COMMAND:"apply-custom-command",OPEN_LOG_FILE:"open-log-file",CLEAR_LOG_FILE:"clear-log-file",DOWNLOAD_YOUTUBE_SCRIPT:"download-youtube-script",TRIGGER_QUICK_ASK:"trigger-quick-ask"},nW={[bt.TRIGGER_QUICK_COMMAND]:"Trigger quick command",[bt.CLEAR_LOCAL_COPILOT_INDEX]:"Clear local Copilot index",[bt.CLEAR_COPILOT_CACHE]:"Clear Copilot cache",[bt.COUNT_TOTAL_VAULT_TOKENS]:"Count total tokens in your vault",[bt.COUNT_WORD_AND_TOKENS_SELECTION]:"Count words and tokens in selection",[bt.DEBUG_WORD_COMPLETION]:"Word completion: Debug",[bt.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX]:"Force reindex vault",[bt.GARBAGE_COLLECT_COPILOT_INDEX]:"Garbage collect Copilot index (remove files that no longer exist in vault)",[bt.INDEX_VAULT_TO_COPILOT_INDEX]:"Index (refresh) vault",[bt.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS]:"Inspect Copilot index by note paths (debug)",[bt.LIST_INDEXED_FILES]:"List all indexed files (debug)",[bt.LOAD_COPILOT_CHAT_CONVERSATION]:"Load Copilot chat conversation",[bt.NEW_CHAT]:"New Copilot Chat",[bt.OPEN_COPILOT_CHAT_WINDOW]:"Open Copilot Chat Window",[bt.SEARCH_ORAMA_DB]:"Search semantic index (debug)",[bt.TOGGLE_COPILOT_CHAT_WINDOW]:"Toggle Copilot Chat Window",[bt.ADD_SELECTION_TO_CHAT_CONTEXT]:"Add selection to chat context",[bt.ADD_WEB_SELECTION_TO_CHAT_CONTEXT]:"Add web selection to chat context",[bt.ADD_CUSTOM_COMMAND]:"Add new custom command",[bt.APPLY_CUSTOM_COMMAND]:"Apply custom command",[bt.OPEN_LOG_FILE]:"Create log file",[bt.CLEAR_LOG_FILE]:"Clear log file",[bt.DOWNLOAD_YOUTUBE_SCRIPT]:"Download YouTube Script (plus)",[bt.TRIGGER_QUICK_ASK]:"Quick Ask"},rW={[bt.NEW_CHAT]:"message-square-plus",[bt.OPEN_COPILOT_CHAT_WINDOW]:"message-square",[bt.TOGGLE_COPILOT_CHAT_WINDOW]:"message-square",[bt.LOAD_COPILOT_CHAT_CONVERSATION]:"history",[bt.TRIGGER_QUICK_COMMAND]:"terminal-square",[bt.TRIGGER_QUICK_ASK]:"sparkles",[bt.ADD_SELECTION_TO_CHAT_CONTEXT]:"text-cursor-input",[bt.ADD_WEB_SELECTION_TO_CHAT_CONTEXT]:"globe",[bt.ADD_CUSTOM_COMMAND]:"plus-circle",[bt.APPLY_CUSTOM_COMMAND]:"play-circle",[bt.INDEX_VAULT_TO_COPILOT_INDEX]:"refresh-cw",[bt.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX]:"rotate-cw",[bt.CLEAR_LOCAL_COPILOT_INDEX]:"trash-2",[bt.CLEAR_COPILOT_CACHE]:"eraser",[bt.GARBAGE_COLLECT_COPILOT_INDEX]:"filter-x",[bt.COUNT_TOTAL_VAULT_TOKENS]:"calculator",[bt.COUNT_WORD_AND_TOKENS_SELECTION]:"hash",[bt.OPEN_LOG_FILE]:"file-text",[bt.CLEAR_LOG_FILE]:"file-x",[bt.DOWNLOAD_YOUTUBE_SCRIPT]:"youtube"},lee=["md","canvas","base"],gPe=[...lee,"pdf"],XE={NON_MARKDOWN_FILES_RESTRICTED:"Non-markdown files are only available in Copilot Plus mode. Please upgrade to access this file type.",URL_PROCESSING_RESTRICTED:"URL processing is only available in Copilot Plus mode. URLs will not be processed for context.",UNSUPPORTED_FILE_TYPE:t=>`${t.toUpperCase()} files are not supported in the current mode.`},Hn={userId:si(),isPlusUser:!1,plusLicenseKey:"",openAIApiKey:"",openAIOrgId:"",huggingfaceApiKey:"",cohereApiKey:"",anthropicApiKey:"",azureOpenAIApiKey:"",azureOpenAIApiInstanceName:"",azureOpenAIApiDeploymentName:"",azureOpenAIApiVersion:"",azureOpenAIApiEmbeddingDeploymentName:"",googleApiKey:"",openRouterAiApiKey:"",xaiApiKey:"",mistralApiKey:"",deepseekApiKey:"",amazonBedrockApiKey:"",amazonBedrockRegion:"",siliconflowApiKey:"",githubCopilotAccessToken:"",githubCopilotToken:"",githubCopilotTokenExpiresAt:0,defaultChainType:"llm_chain",defaultModelKey:"google/gemini-2.5-flash|openrouterai",embeddingModelKey:"openai/text-embedding-3-small|openrouterai",temperature:Pc.TEMPERATURE,maxTokens:Pc.MAX_TOKENS,contextTurns:15,userSystemPrompt:"",openAIProxyBaseUrl:"",openAIEmbeddingProxyBaseUrl:"",stream:!0,defaultSaveFolder:ywt,defaultConversationTag:"copilot-conversation",autosaveChat:!0,generateAIChatTitleOnSave:!0,autoAddActiveContentToContext:!0,defaultOpenArea:"view",defaultSendShortcut:"enter",customPromptsFolder:wwt,indexVaultToVectorStore:"ON MODE SWITCH",qaExclusions:QQ,qaInclusions:"",chatNoteContextPath:"",chatNoteContextTags:[],enableIndexSync:!0,debug:!1,maxSourceChunks:_wt,enableInlineCitations:!0,groqApiKey:"",activeModels:Gh,activeEmbeddingModels:OS,embeddingRequestsPerMin:60,embeddingBatchSize:16,disableIndexOnMobile:!0,showSuggestedPrompts:!0,showRelevantNotes:!0,numPartitions:1,lexicalSearchRamLimit:100,promptUsageTimestamps:{},promptSortStrategy:"timestamp",chatHistorySortStrategy:"recent",projectListSortStrategy:"recent",projectsFolder:bwt,defaultConversationNoteName:"{$topic}@{$date}_{$time}",inlineEditCommands:[],projectList:[],lastDismissedVersion:null,passMarkdownImages:!0,enableAutonomousAgent:!0,enableCustomPromptTemplating:!0,enableSemanticSearchV3:!1,enableSelfHostMode:!1,enableMiyo:!1,miyoSearchAll:!1,selfHostModeValidatedAt:null,selfHostValidationCount:0,selfHostUrl:"",selfHostApiKey:"",miyoServerUrl:"",selfHostSearchProvider:"firecrawl",firecrawlApiKey:"",perplexityApiKey:"",supadataApiKey:"",enableLexicalBoosts:!0,suggestedDefaultCommands:!1,autonomousAgentMaxIterations:4,autonomousAgentEnabledToolIds:["localSearch","readNote","webSearch","pomodoro","youtubeTranscription","writeFile","editFile","updateMemory"],reasoningEffort:Pc.REASONING_EFFORT,verbosity:Pc.VERBOSITY,memoryFolderName:vwt,enableRecentConversations:!0,maxRecentConversations:30,enableSavedMemory:!0,quickCommandModelKey:void 0,quickCommandIncludeNoteContext:!0,autoIncludeTextSelection:!1,autoAddSelectionToContext:!1,autoAcceptEdits:!1,diffViewMode:"split",userSystemPromptsFolder:xwt,defaultSystemPromptTitle:"",autoCompactThreshold:128e3,convertedDocOutputFolder:Cwt},kf={CHAT_IS_VISIBLE:"chat-is-visible",ACTIVE_LEAF_CHANGE:"active-leaf-change",ABORT_STREAM:"abort-stream"}});var uee=Tt(oW=>{"use strict";oW.byteLength=Twt;oW.toByteArray=Pwt;oW.fromByteArray=kwt;var Yh=[],Mf=[],Swt=typeof Uint8Array<"u"?Uint8Array:Array,cee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(RS=0,yPe=cee.length;RS<yPe;++RS)Yh[RS]=cee[RS],Mf[cee.charCodeAt(RS)]=RS;var RS,yPe;Mf[45]=62;Mf[95]=63;function wPe(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function Twt(t){var e=wPe(t),n=e[0],r=e[1];return(n+r)*3/4-r}function Iwt(t,e,n){return(e+n)*3/4-n}function Pwt(t){var e,n=wPe(t),r=n[0],o=n[1],i=new Swt(Iwt(t,r,o)),s=0,a=o>0?r-4:r,l;for(l=0;l<a;l+=4)e=Mf[t.charCodeAt(l)]<<18|Mf[t.charCodeAt(l+1)]<<12|Mf[t.charCodeAt(l+2)]<<6|Mf[t.charCodeAt(l+3)],i[s++]=e>>16&255,i[s++]=e>>8&255,i[s++]=e&255;return o===2&&(e=Mf[t.charCodeAt(l)]<<2|Mf[t.charCodeAt(l+1)]>>4,i[s++]=e&255),o===1&&(e=Mf[t.charCodeAt(l)]<<10|Mf[t.charCodeAt(l+1)]<<4|Mf[t.charCodeAt(l+2)]>>2,i[s++]=e>>8&255,i[s++]=e&255),i}function Ewt(t){return Yh[t>>18&63]+Yh[t>>12&63]+Yh[t>>6&63]+Yh[t&63]}function Awt(t,e,n){for(var r,o=[],i=e;i<n;i+=3)r=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),o.push(Ewt(r));return o.join("")}function kwt(t){for(var e,n=t.length,r=n%3,o=[],i=16383,s=0,a=n-r;s<a;s+=i)o.push(Awt(t,s,s+i>a?a:s+i));return r===1?(e=t[n-1],o.push(Yh[e>>2]+Yh[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],o.push(Yh[e>>10]+Yh[e>>4&63]+Yh[e<<2&63]+"=")),o.join("")}});var vPe=Tt(dee=>{dee.read=function(t,e,n,r,o){var i,s,a=o*8-r-1,l=(1<<a)-1,c=l>>1,u=-7,d=n?o-1:0,f=n?-1:1,p=t[e+d];for(d+=f,i=p&(1<<-u)-1,p>>=-u,u+=a;u>0;i=i*256+t[e+d],d+=f,u-=8);for(s=i&(1<<-u)-1,i>>=-u,u+=r;u>0;s=s*256+t[e+d],d+=f,u-=8);if(i===0)i=1-c;else{if(i===l)return s?NaN:(p?-1:1)*(1/0);s=s+Math.pow(2,r),i=i-c}return(p?-1:1)*s*Math.pow(2,i-r)};dee.write=function(t,e,n,r,o,i){var s,a,l,c=i*8-o-1,u=(1<<c)-1,d=u>>1,f=o===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:i-1,m=r?1:-1,h=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,s=u):(s=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-s))<1&&(s--,l*=2),s+d>=1?e+=f/l:e+=f*Math.pow(2,1-d),e*l>=2&&(s++,l/=2),s+d>=u?(a=0,s=u):s+d>=1?(a=(e*l-1)*Math.pow(2,o),s=s+d):(a=e*Math.pow(2,d-1)*Math.pow(2,o),s=0));o>=8;t[n+p]=a&255,p+=m,a/=256,o-=8);for(s=s<<o|a,c+=o;c>0;t[n+p]=s&255,p+=m,s/=256,c-=8);t[n+p-m]|=h*128}});var uD=Tt(nA=>{"use strict";var fee=uee(),eA=vPe(),xPe=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;nA.Buffer=xe;nA.SlowBuffer=Dwt;nA.INSPECT_MAX_BYTES=50;var iW=2147483647;nA.kMaxLength=iW;xe.TYPED_ARRAY_SUPPORT=Mwt();!xe.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function Mwt(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch{return!1}}Object.defineProperty(xe.prototype,"parent",{enumerable:!0,get:function(){if(xe.isBuffer(this))return this.buffer}});Object.defineProperty(xe.prototype,"offset",{enumerable:!0,get:function(){if(xe.isBuffer(this))return this.byteOffset}});function Wy(t){if(t>iW)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,xe.prototype),e}function xe(t,e,n){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return gee(t)}return SPe(t,e,n)}xe.poolSize=8192;function SPe(t,e,n){if(typeof t=="string")return Owt(t,e);if(ArrayBuffer.isView(t))return Rwt(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(Zh(t,ArrayBuffer)||t&&Zh(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Zh(t,SharedArrayBuffer)||t&&Zh(t.buffer,SharedArrayBuffer)))return mee(t,e,n);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let r=t.valueOf&&t.valueOf();if(r!=null&&r!==t)return xe.from(r,e,n);let o=Lwt(t);if(o)return o;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return xe.from(t[Symbol.toPrimitive]("string"),e,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}xe.from=function(t,e,n){return SPe(t,e,n)};Object.setPrototypeOf(xe.prototype,Uint8Array.prototype);Object.setPrototypeOf(xe,Uint8Array);function TPe(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function Nwt(t,e,n){return TPe(t),t<=0?Wy(t):e!==void 0?typeof n=="string"?Wy(t).fill(e,n):Wy(t).fill(e):Wy(t)}xe.alloc=function(t,e,n){return Nwt(t,e,n)};function gee(t){return TPe(t),Wy(t<0?0:yee(t)|0)}xe.allocUnsafe=function(t){return gee(t)};xe.allocUnsafeSlow=function(t){return gee(t)};function Owt(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!xe.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let n=IPe(t,e)|0,r=Wy(n),o=r.write(t,e);return o!==n&&(r=r.slice(0,o)),r}function pee(t){let e=t.length<0?0:yee(t.length)|0,n=Wy(e);for(let r=0;r<e;r+=1)n[r]=t[r]&255;return n}function Rwt(t){if(Zh(t,Uint8Array)){let e=new Uint8Array(t);return mee(e.buffer,e.byteOffset,e.byteLength)}return pee(t)}function mee(t,e,n){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return e===void 0&&n===void 0?r=new Uint8Array(t):n===void 0?r=new Uint8Array(t,e):r=new Uint8Array(t,e,n),Object.setPrototypeOf(r,xe.prototype),r}function Lwt(t){if(xe.isBuffer(t)){let e=yee(t.length)|0,n=Wy(e);return n.length===0||t.copy(n,0,0,e),n}if(t.length!==void 0)return typeof t.length!="number"||vee(t.length)?Wy(0):pee(t);if(t.type==="Buffer"&&Array.isArray(t.data))return pee(t.data)}function yee(t){if(t>=iW)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+iW.toString(16)+" bytes");return t|0}function Dwt(t){return+t!=t&&(t=0),xe.alloc(+t)}xe.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==xe.prototype};xe.compare=function(e,n){if(Zh(e,Uint8Array)&&(e=xe.from(e,e.offset,e.byteLength)),Zh(n,Uint8Array)&&(n=xe.from(n,n.offset,n.byteLength)),!xe.isBuffer(e)||!xe.isBuffer(n))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===n)return 0;let r=e.length,o=n.length;for(let i=0,s=Math.min(r,o);i<s;++i)if(e[i]!==n[i]){r=e[i],o=n[i];break}return r<o?-1:o<r?1:0};xe.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}};xe.concat=function(e,n){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(e.length===0)return xe.alloc(0);let r;if(n===void 0)for(n=0,r=0;r<e.length;++r)n+=e[r].length;let o=xe.allocUnsafe(n),i=0;for(r=0;r<e.length;++r){let s=e[r];if(Zh(s,Uint8Array))i+s.length>o.length?(xe.isBuffer(s)||(s=xe.from(s)),s.copy(o,i)):Uint8Array.prototype.set.call(o,s,i);else if(xe.isBuffer(s))s.copy(o,i);else throw new TypeError('"list" argument must be an Array of Buffers');i+=s.length}return o};function IPe(t,e){if(xe.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||Zh(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);let n=t.length,r=arguments.length>2&&arguments[2]===!0;if(!r&&n===0)return 0;let o=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return hee(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return n*2;case"hex":return n>>>1;case"base64":return LPe(t).length;default:if(o)return r?-1:hee(t).length;e=(""+e).toLowerCase(),o=!0}}xe.byteLength=IPe;function $wt(t,e,n){let r=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((n===void 0||n>this.length)&&(n=this.length),n<=0)||(n>>>=0,e>>>=0,n<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return qwt(this,e,n);case"utf8":case"utf-8":return EPe(this,e,n);case"ascii":return Hwt(this,e,n);case"latin1":case"binary":return Kwt(this,e,n);case"base64":return Vwt(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Gwt(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}xe.prototype._isBuffer=!0;function LS(t,e,n){let r=t[e];t[e]=t[n],t[n]=r}xe.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let n=0;n<e;n+=2)LS(this,n,n+1);return this};xe.prototype.swap32=function(){let e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let n=0;n<e;n+=4)LS(this,n,n+3),LS(this,n+1,n+2);return this};xe.prototype.swap64=function(){let e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let n=0;n<e;n+=8)LS(this,n,n+7),LS(this,n+1,n+6),LS(this,n+2,n+5),LS(this,n+3,n+4);return this};xe.prototype.toString=function(){let e=this.length;return e===0?"":arguments.length===0?EPe(this,0,e):$wt.apply(this,arguments)};xe.prototype.toLocaleString=xe.prototype.toString;xe.prototype.equals=function(e){if(!xe.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e?!0:xe.compare(this,e)===0};xe.prototype.inspect=function(){let e="",n=nA.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"};xPe&&(xe.prototype[xPe]=xe.prototype.inspect);xe.prototype.compare=function(e,n,r,o,i){if(Zh(e,Uint8Array)&&(e=xe.from(e,e.offset,e.byteLength)),!xe.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(n===void 0&&(n=0),r===void 0&&(r=e?e.length:0),o===void 0&&(o=0),i===void 0&&(i=this.length),n<0||r>e.length||o<0||i>this.length)throw new RangeError("out of range index");if(o>=i&&n>=r)return 0;if(o>=i)return-1;if(n>=r)return 1;if(n>>>=0,r>>>=0,o>>>=0,i>>>=0,this===e)return 0;let s=i-o,a=r-n,l=Math.min(s,a),c=this.slice(o,i),u=e.slice(n,r);for(let d=0;d<l;++d)if(c[d]!==u[d]){s=c[d],a=u[d];break}return s<a?-1:a<s?1:0};function PPe(t,e,n,r,o){if(t.length===0)return-1;if(typeof n=="string"?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,vee(n)&&(n=o?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(o)return-1;n=t.length-1}else if(n<0)if(o)n=0;else return-1;if(typeof e=="string"&&(e=xe.from(e,r)),xe.isBuffer(e))return e.length===0?-1:bPe(t,e,n,r,o);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?o?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):bPe(t,[e],n,r,o);throw new TypeError("val must be string, number or Buffer")}function bPe(t,e,n,r,o){let i=1,s=t.length,a=e.length;if(r!==void 0&&(r=String(r).toLowerCase(),r==="ucs2"||r==="ucs-2"||r==="utf16le"||r==="utf-16le")){if(t.length<2||e.length<2)return-1;i=2,s/=2,a/=2,n/=2}function l(u,d){return i===1?u[d]:u.readUInt16BE(d*i)}let c;if(o){let u=-1;for(c=n;c<s;c++)if(l(t,c)===l(e,u===-1?0:c-u)){if(u===-1&&(u=c),c-u+1===a)return u*i}else u!==-1&&(c-=c-u),u=-1}else for(n+a>s&&(n=s-a),c=n;c>=0;c--){let u=!0;for(let d=0;d<a;d++)if(l(t,c+d)!==l(e,d)){u=!1;break}if(u)return c}return-1}xe.prototype.includes=function(e,n,r){return this.indexOf(e,n,r)!==-1};xe.prototype.indexOf=function(e,n,r){return PPe(this,e,n,r,!0)};xe.prototype.lastIndexOf=function(e,n,r){return PPe(this,e,n,r,!1)};function Fwt(t,e,n,r){n=Number(n)||0;let o=t.length-n;r?(r=Number(r),r>o&&(r=o)):r=o;let i=e.length;r>i/2&&(r=i/2);let s;for(s=0;s<r;++s){let a=parseInt(e.substr(s*2,2),16);if(vee(a))return s;t[n+s]=a}return s}function Uwt(t,e,n,r){return sW(hee(e,t.length-n),t,n,r)}function Bwt(t,e,n,r){return sW(Xwt(e),t,n,r)}function zwt(t,e,n,r){return sW(LPe(e),t,n,r)}function jwt(t,e,n,r){return sW(Qwt(e,t.length-n),t,n,r)}xe.prototype.write=function(e,n,r,o){if(n===void 0)o="utf8",r=this.length,n=0;else if(r===void 0&&typeof n=="string")o=n,r=this.length,n=0;else if(isFinite(n))n=n>>>0,isFinite(r)?(r=r>>>0,o===void 0&&(o="utf8")):(o=r,r=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let i=this.length-n;if((r===void 0||r>i)&&(r=i),e.length>0&&(r<0||n<0)||n>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");let s=!1;for(;;)switch(o){case"hex":return Fwt(this,e,n,r);case"utf8":case"utf-8":return Uwt(this,e,n,r);case"ascii":case"latin1":case"binary":return Bwt(this,e,n,r);case"base64":return zwt(this,e,n,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return jwt(this,e,n,r);default:if(s)throw new TypeError("Unknown encoding: "+o);o=(""+o).toLowerCase(),s=!0}};xe.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Vwt(t,e,n){return e===0&&n===t.length?fee.fromByteArray(t):fee.fromByteArray(t.slice(e,n))}function EPe(t,e,n){n=Math.min(t.length,n);let r=[],o=e;for(;o<n;){let i=t[o],s=null,a=i>239?4:i>223?3:i>191?2:1;if(o+a<=n){let l,c,u,d;switch(a){case 1:i<128&&(s=i);break;case 2:l=t[o+1],(l&192)===128&&(d=(i&31)<<6|l&63,d>127&&(s=d));break;case 3:l=t[o+1],c=t[o+2],(l&192)===128&&(c&192)===128&&(d=(i&15)<<12|(l&63)<<6|c&63,d>2047&&(d<55296||d>57343)&&(s=d));break;case 4:l=t[o+1],c=t[o+2],u=t[o+3],(l&192)===128&&(c&192)===128&&(u&192)===128&&(d=(i&15)<<18|(l&63)<<12|(c&63)<<6|u&63,d>65535&&d<1114112&&(s=d))}}s===null?(s=65533,a=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|s&1023),r.push(s),o+=a}return Wwt(r)}var CPe=4096;function Wwt(t){let e=t.length;if(e<=CPe)return String.fromCharCode.apply(String,t);let n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=CPe));return n}function Hwt(t,e,n){let r="";n=Math.min(t.length,n);for(let o=e;o<n;++o)r+=String.fromCharCode(t[o]&127);return r}function Kwt(t,e,n){let r="";n=Math.min(t.length,n);for(let o=e;o<n;++o)r+=String.fromCharCode(t[o]);return r}function qwt(t,e,n){let r=t.length;(!e||e<0)&&(e=0),(!n||n<0||n>r)&&(n=r);let o="";for(let i=e;i<n;++i)o+=evt[t[i]];return o}function Gwt(t,e,n){let r=t.slice(e,n),o="";for(let i=0;i<r.length-1;i+=2)o+=String.fromCharCode(r[i]+r[i+1]*256);return o}xe.prototype.slice=function(e,n){let r=this.length;e=~~e,n=n===void 0?r:~~n,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),n<0?(n+=r,n<0&&(n=0)):n>r&&(n=r),n<e&&(n=e);let o=this.subarray(e,n);return Object.setPrototypeOf(o,xe.prototype),o};function Ia(t,e,n){if(t%1!==0||t<0)throw new RangeError("offset is not uint");if(t+e>n)throw new RangeError("Trying to access beyond buffer length")}xe.prototype.readUintLE=xe.prototype.readUIntLE=function(e,n,r){e=e>>>0,n=n>>>0,r||Ia(e,n,this.length);let o=this[e],i=1,s=0;for(;++s<n&&(i*=256);)o+=this[e+s]*i;return o};xe.prototype.readUintBE=xe.prototype.readUIntBE=function(e,n,r){e=e>>>0,n=n>>>0,r||Ia(e,n,this.length);let o=this[e+--n],i=1;for(;n>0&&(i*=256);)o+=this[e+--n]*i;return o};xe.prototype.readUint8=xe.prototype.readUInt8=function(e,n){return e=e>>>0,n||Ia(e,1,this.length),this[e]};xe.prototype.readUint16LE=xe.prototype.readUInt16LE=function(e,n){return e=e>>>0,n||Ia(e,2,this.length),this[e]|this[e+1]<<8};xe.prototype.readUint16BE=xe.prototype.readUInt16BE=function(e,n){return e=e>>>0,n||Ia(e,2,this.length),this[e]<<8|this[e+1]};xe.prototype.readUint32LE=xe.prototype.readUInt32LE=function(e,n){return e=e>>>0,n||Ia(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};xe.prototype.readUint32BE=xe.prototype.readUInt32BE=function(e,n){return e=e>>>0,n||Ia(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};xe.prototype.readBigUInt64LE=Ax(function(e){e=e>>>0,tA(e,"offset");let n=this[e],r=this[e+7];(n===void 0||r===void 0)&&cD(e,this.length-8);let o=n+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,i=this[++e]+this[++e]*2**8+this[++e]*2**16+r*2**24;return BigInt(o)+(BigInt(i)<<BigInt(32))});xe.prototype.readBigUInt64BE=Ax(function(e){e=e>>>0,tA(e,"offset");let n=this[e],r=this[e+7];(n===void 0||r===void 0)&&cD(e,this.length-8);let o=n*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],i=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r;return(BigInt(o)<<BigInt(32))+BigInt(i)});xe.prototype.readIntLE=function(e,n,r){e=e>>>0,n=n>>>0,r||Ia(e,n,this.length);let o=this[e],i=1,s=0;for(;++s<n&&(i*=256);)o+=this[e+s]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*n)),o};xe.prototype.readIntBE=function(e,n,r){e=e>>>0,n=n>>>0,r||Ia(e,n,this.length);let o=n,i=1,s=this[e+--o];for(;o>0&&(i*=256);)s+=this[e+--o]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*n)),s};xe.prototype.readInt8=function(e,n){return e=e>>>0,n||Ia(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};xe.prototype.readInt16LE=function(e,n){e=e>>>0,n||Ia(e,2,this.length);let r=this[e]|this[e+1]<<8;return r&32768?r|4294901760:r};xe.prototype.readInt16BE=function(e,n){e=e>>>0,n||Ia(e,2,this.length);let r=this[e+1]|this[e]<<8;return r&32768?r|4294901760:r};xe.prototype.readInt32LE=function(e,n){return e=e>>>0,n||Ia(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};xe.prototype.readInt32BE=function(e,n){return e=e>>>0,n||Ia(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};xe.prototype.readBigInt64LE=Ax(function(e){e=e>>>0,tA(e,"offset");let n=this[e],r=this[e+7];(n===void 0||r===void 0)&&cD(e,this.length-8);let o=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(r<<24);return(BigInt(o)<<BigInt(32))+BigInt(n+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24)});xe.prototype.readBigInt64BE=Ax(function(e){e=e>>>0,tA(e,"offset");let n=this[e],r=this[e+7];(n===void 0||r===void 0)&&cD(e,this.length-8);let o=(n<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(o)<<BigInt(32))+BigInt(this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+r)});xe.prototype.readFloatLE=function(e,n){return e=e>>>0,n||Ia(e,4,this.length),eA.read(this,e,!0,23,4)};xe.prototype.readFloatBE=function(e,n){return e=e>>>0,n||Ia(e,4,this.length),eA.read(this,e,!1,23,4)};xe.prototype.readDoubleLE=function(e,n){return e=e>>>0,n||Ia(e,8,this.length),eA.read(this,e,!0,52,8)};xe.prototype.readDoubleBE=function(e,n){return e=e>>>0,n||Ia(e,8,this.length),eA.read(this,e,!1,52,8)};function _u(t,e,n,r,o,i){if(!xe.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||e<i)throw new RangeError('"value" argument is out of bounds');if(n+r>t.length)throw new RangeError("Index out of range")}xe.prototype.writeUintLE=xe.prototype.writeUIntLE=function(e,n,r,o){if(e=+e,n=n>>>0,r=r>>>0,!o){let a=Math.pow(2,8*r)-1;_u(this,e,n,r,a,0)}let i=1,s=0;for(this[n]=e&255;++s<r&&(i*=256);)this[n+s]=e/i&255;return n+r};xe.prototype.writeUintBE=xe.prototype.writeUIntBE=function(e,n,r,o){if(e=+e,n=n>>>0,r=r>>>0,!o){let a=Math.pow(2,8*r)-1;_u(this,e,n,r,a,0)}let i=r-1,s=1;for(this[n+i]=e&255;--i>=0&&(s*=256);)this[n+i]=e/s&255;return n+r};xe.prototype.writeUint8=xe.prototype.writeUInt8=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,1,255,0),this[n]=e&255,n+1};xe.prototype.writeUint16LE=xe.prototype.writeUInt16LE=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,2,65535,0),this[n]=e&255,this[n+1]=e>>>8,n+2};xe.prototype.writeUint16BE=xe.prototype.writeUInt16BE=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,2,65535,0),this[n]=e>>>8,this[n+1]=e&255,n+2};xe.prototype.writeUint32LE=xe.prototype.writeUInt32LE=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,4,4294967295,0),this[n+3]=e>>>24,this[n+2]=e>>>16,this[n+1]=e>>>8,this[n]=e&255,n+4};xe.prototype.writeUint32BE=xe.prototype.writeUInt32BE=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,4,4294967295,0),this[n]=e>>>24,this[n+1]=e>>>16,this[n+2]=e>>>8,this[n+3]=e&255,n+4};function APe(t,e,n,r,o){RPe(e,r,o,t,n,7);let i=Number(e&BigInt(4294967295));t[n++]=i,i=i>>8,t[n++]=i,i=i>>8,t[n++]=i,i=i>>8,t[n++]=i;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[n++]=s,s=s>>8,t[n++]=s,s=s>>8,t[n++]=s,s=s>>8,t[n++]=s,n}function kPe(t,e,n,r,o){RPe(e,r,o,t,n,7);let i=Number(e&BigInt(4294967295));t[n+7]=i,i=i>>8,t[n+6]=i,i=i>>8,t[n+5]=i,i=i>>8,t[n+4]=i;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[n+3]=s,s=s>>8,t[n+2]=s,s=s>>8,t[n+1]=s,s=s>>8,t[n]=s,n+8}xe.prototype.writeBigUInt64LE=Ax(function(e,n=0){return APe(this,e,n,BigInt(0),BigInt("0xffffffffffffffff"))});xe.prototype.writeBigUInt64BE=Ax(function(e,n=0){return kPe(this,e,n,BigInt(0),BigInt("0xffffffffffffffff"))});xe.prototype.writeIntLE=function(e,n,r,o){if(e=+e,n=n>>>0,!o){let l=Math.pow(2,8*r-1);_u(this,e,n,r,l-1,-l)}let i=0,s=1,a=0;for(this[n]=e&255;++i<r&&(s*=256);)e<0&&a===0&&this[n+i-1]!==0&&(a=1),this[n+i]=(e/s>>0)-a&255;return n+r};xe.prototype.writeIntBE=function(e,n,r,o){if(e=+e,n=n>>>0,!o){let l=Math.pow(2,8*r-1);_u(this,e,n,r,l-1,-l)}let i=r-1,s=1,a=0;for(this[n+i]=e&255;--i>=0&&(s*=256);)e<0&&a===0&&this[n+i+1]!==0&&(a=1),this[n+i]=(e/s>>0)-a&255;return n+r};xe.prototype.writeInt8=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,1,127,-128),e<0&&(e=255+e+1),this[n]=e&255,n+1};xe.prototype.writeInt16LE=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,2,32767,-32768),this[n]=e&255,this[n+1]=e>>>8,n+2};xe.prototype.writeInt16BE=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,2,32767,-32768),this[n]=e>>>8,this[n+1]=e&255,n+2};xe.prototype.writeInt32LE=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,4,2147483647,-2147483648),this[n]=e&255,this[n+1]=e>>>8,this[n+2]=e>>>16,this[n+3]=e>>>24,n+4};xe.prototype.writeInt32BE=function(e,n,r){return e=+e,n=n>>>0,r||_u(this,e,n,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[n]=e>>>24,this[n+1]=e>>>16,this[n+2]=e>>>8,this[n+3]=e&255,n+4};xe.prototype.writeBigInt64LE=Ax(function(e,n=0){return APe(this,e,n,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});xe.prototype.writeBigInt64BE=Ax(function(e,n=0){return kPe(this,e,n,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function MPe(t,e,n,r,o,i){if(n+r>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function NPe(t,e,n,r,o){return e=+e,n=n>>>0,o||MPe(t,e,n,4,34028234663852886e22,-34028234663852886e22),eA.write(t,e,n,r,23,4),n+4}xe.prototype.writeFloatLE=function(e,n,r){return NPe(this,e,n,!0,r)};xe.prototype.writeFloatBE=function(e,n,r){return NPe(this,e,n,!1,r)};function OPe(t,e,n,r,o){return e=+e,n=n>>>0,o||MPe(t,e,n,8,17976931348623157e292,-17976931348623157e292),eA.write(t,e,n,r,52,8),n+8}xe.prototype.writeDoubleLE=function(e,n,r){return OPe(this,e,n,!0,r)};xe.prototype.writeDoubleBE=function(e,n,r){return OPe(this,e,n,!1,r)};xe.prototype.copy=function(e,n,r,o){if(!xe.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),!o&&o!==0&&(o=this.length),n>=e.length&&(n=e.length),n||(n=0),o>0&&o<r&&(o=r),o===r||e.length===0||this.length===0)return 0;if(n<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-n<o-r&&(o=e.length-n+r);let i=o-r;return this===e&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(n,r,o):Uint8Array.prototype.set.call(e,this.subarray(r,o),n),i};xe.prototype.fill=function(e,n,r,o){if(typeof e=="string"){if(typeof n=="string"?(o=n,n=0,r=this.length):typeof r=="string"&&(o=r,r=this.length),o!==void 0&&typeof o!="string")throw new TypeError("encoding must be a string");if(typeof o=="string"&&!xe.isEncoding(o))throw new TypeError("Unknown encoding: "+o);if(e.length===1){let s=e.charCodeAt(0);(o==="utf8"&&s<128||o==="latin1")&&(e=s)}}else typeof e=="number"?e=e&255:typeof e=="boolean"&&(e=Number(e));if(n<0||this.length<n||this.length<r)throw new RangeError("Out of range index");if(r<=n)return this;n=n>>>0,r=r===void 0?this.length:r>>>0,e||(e=0);let i;if(typeof e=="number")for(i=n;i<r;++i)this[i]=e;else{let s=xe.isBuffer(e)?e:xe.from(e,o),a=s.length;if(a===0)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-n;++i)this[i+n]=s[i%a]}return this};var QE={};function wee(t,e,n){QE[t]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(o){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:o,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}wee("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError);wee("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError);wee("ERR_OUT_OF_RANGE",function(t,e,n){let r=`The value of "${t}" is out of range.`,o=n;return Number.isInteger(n)&&Math.abs(n)>2**32?o=_Pe(String(n)):typeof n=="bigint"&&(o=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(o=_Pe(o)),o+="n"),r+=` It must be ${e}. Received ${o}`,r},RangeError);function _Pe(t){let e="",n=t.length,r=t[0]==="-"?1:0;for(;n>=r+4;n-=3)e=`_${t.slice(n-3,n)}${e}`;return`${t.slice(0,n)}${e}`}function Ywt(t,e,n){tA(e,"offset"),(t[e]===void 0||t[e+n]===void 0)&&cD(e,t.length-(n+1))}function RPe(t,e,n,r,o,i){if(t>n||t<e){let s=typeof e=="bigint"?"n":"",a;throw i>3?e===0||e===BigInt(0)?a=`>= 0${s} and < 2${s} ** ${(i+1)*8}${s}`:a=`>= -(2${s} ** ${(i+1)*8-1}${s}) and < 2 ** ${(i+1)*8-1}${s}`:a=`>= ${e}${s} and <= ${n}${s}`,new QE.ERR_OUT_OF_RANGE("value",a,t)}Ywt(r,o,i)}function tA(t,e){if(typeof t!="number")throw new QE.ERR_INVALID_ARG_TYPE(e,"number",t)}function cD(t,e,n){throw Math.floor(t)!==t?(tA(t,n),new QE.ERR_OUT_OF_RANGE(n||"offset","an integer",t)):e<0?new QE.ERR_BUFFER_OUT_OF_BOUNDS:new QE.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${e}`,t)}var Zwt=/[^+/0-9A-Za-z-_]/g;function Jwt(t){if(t=t.split("=")[0],t=t.trim().replace(Zwt,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function hee(t,e){e=e||1/0;let n,r=t.length,o=null,i=[];for(let s=0;s<r;++s){if(n=t.charCodeAt(s),n>55295&&n<57344){if(!o){if(n>56319){(e-=3)>-1&&i.push(239,191,189);continue}else if(s+1===r){(e-=3)>-1&&i.push(239,191,189);continue}o=n;continue}if(n<56320){(e-=3)>-1&&i.push(239,191,189),o=n;continue}n=(o-55296<<10|n-56320)+65536}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,n<128){if((e-=1)<0)break;i.push(n)}else if(n<2048){if((e-=2)<0)break;i.push(n>>6|192,n&63|128)}else if(n<65536){if((e-=3)<0)break;i.push(n>>12|224,n>>6&63|128,n&63|128)}else if(n<1114112){if((e-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,n&63|128)}else throw new Error("Invalid code point")}return i}function Xwt(t){let e=[];for(let n=0;n<t.length;++n)e.push(t.charCodeAt(n)&255);return e}function Qwt(t,e){let n,r,o,i=[];for(let s=0;s<t.length&&!((e-=2)<0);++s)n=t.charCodeAt(s),r=n>>8,o=n%256,i.push(o),i.push(r);return i}function LPe(t){return fee.toByteArray(Jwt(t))}function sW(t,e,n,r){let o;for(o=0;o<r&&!(o+n>=e.length||o>=t.length);++o)e[o+n]=t[o];return o}function Zh(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function vee(t){return t!==t}var evt=function(){let t="0123456789abcdef",e=new Array(256);for(let n=0;n<16;++n){let r=n*16;for(let o=0;o<16;++o)e[r+o]=t[n]+t[o]}return e}();function Ax(t){return typeof BigInt>"u"?tvt:t}function tvt(){throw new Error("BigInt not supported")}});function xee(){if(!Cee.Platform.isDesktopApp&&!Cee.Platform.isDesktop)return null;if(aW)return aW;try{return aW=require("electron")?.remote?.safeStorage??null,aW}catch{return null}}function kx(t){return t.startsWith(_ee)||t.startsWith(See)||t.startsWith(Pee)}function ivt(){if(!window.crypto?.subtle)throw new Error("WebCrypto API is not available in this environment.")}function svt(){try{return window.localStorage??null}catch{return null}}async function avt(){try{let t=svt();if(!t)return null;let e=t.getItem(nvt);if(!e)return null;let n=Iee(e);return await crypto.subtle.importKey("raw",n,"AES-GCM",!1,["encrypt","decrypt"])}catch(t){return console.warn("Failed to load WebCrypto key from localStorage.",t),null}}async function FPe(){let t=await crypto.subtle.digest("SHA-256",rvt);return await crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}function UPe(t,e){if(t.length<e.length)return!1;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}async function BPe(t){ivt();let e=new Uint8Array(Iee(t));if(UPe(e,DPe)){let o=DPe.length,i=o+Tee;if(e.length<=i)throw new Error("Invalid WebCrypto portable payload: too short.");let s=e.slice(o,i),a=e.slice(i),l=await FPe(),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},l,a);return new TextDecoder().decode(c)}if(UPe(e,$Pe)){let o=$Pe.length,i=o+Tee;if(e.length<=i)throw new Error("Invalid WebCrypto CP01 payload: too short.");let s=e.slice(o,i),a=e.slice(i),l=await avt();if(!l)throw new Error("Per-device WebCrypto key unavailable for CP01 decryption.");let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},l,a);return new TextDecoder().decode(c)}let n=await FPe(),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:ovt},n,Iee(t));return new TextDecoder().decode(r)}function Mx(t){let e=t.toLowerCase();return e.replace(/[_-]/g,"").includes("apikey")||e.endsWith("token")||e.endsWith("accesstoken")||e.endsWith("secret")||e.endsWith("password")||e.endsWith("licensekey")}async function pn(t){try{if(!t||lvt(t))return t;if(cvt(t))return t.replace(Eee,"");if(t.startsWith(_ee)){let n=xee();if(!n?.isEncryptionAvailable())return console.warn("Cannot decrypt desktop-encrypted key: safeStorage unavailable."),"";let r=t.replace(_ee,""),o=bee.Buffer.from(r,"base64");return n.decryptString(o)}if(t.startsWith(See)){let n=t.replace(See,"");return await BPe(n)}let e=t.replace(Pee,"");if(xee()?.isEncryptionAvailable())try{let n=bee.Buffer.from(e,"base64");return xee().decryptString(n)}catch{}return await BPe(e)}catch(e){return console.error("Decryption failed:",e),""}}function lvt(t){return!t.startsWith(Pee)&&!t.startsWith(Eee)}function cvt(t){return t.startsWith(Eee)}function Iee(t){let e=window.atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n.buffer}var bee,Cee,aW,_ee,See,Pee,Eee,Tee,nvt,DPe,$Pe,rvt,ovt,Su=C(()=>{bee=N(uD()),Cee=require("obsidian"),aW=null;_ee="enc_desk_",See="enc_web_",Pee="enc_",Eee="dec_";Tee=12,nvt="obsidian-copilot:webcrypto-key:v1",DPe=new Uint8Array([67,80,48,48]),$Pe=new Uint8Array([67,80,48,49]),rvt=new TextEncoder().encode("obsidian-copilot-v1"),ovt=new Uint8Array(Tee)});var zPe={};zn(zPe,{CustomError:()=>Gn,MissingApiKeyError:()=>fD,MissingModelKeyError:()=>rA,MissingPlusLicenseError:()=>DS,TimeoutError:()=>dD});var Gn,dD,fD,DS,rA,Nf=C(()=>{Gn=class t extends Error{constructor(e,n){super(e),this.code=n,Object.setPrototypeOf(this,t.prototype)}},dD=class t extends Error{constructor(e,n){super(`${e} timed out after ${n}ms`),this.name="TimeoutError",Object.setPrototypeOf(this,t.prototype)}},fD=class t extends Error{constructor(e="API key is not configured."){super(e),this.name="MissingApiKeyError",Object.setPrototypeOf(this,t.prototype)}},DS=class t extends Error{constructor(e="Copilot Plus license key is not configured."){super(e),this.name="MissingPlusLicenseError",Object.setPrototypeOf(this,t.prototype)}},rA=class t extends Error{constructor(e="No model key found. Please select a model in settings."){super(e),this.name="MissingModelKeyError",Object.setPrototypeOf(this,t.prototype)}}});function Oo(t,e){let n=`atom${++uvt}`,r={toString(){return(ai.env?ai.env.MODE:void 0)!=="production"&&this.debugLabel?n+":"+this.debugLabel:n}};return typeof t=="function"?r.read=t:(r.init=t,r.read=dvt,r.write=fvt),e&&(r.write=e),r}function dvt(t){return t(this)}function fvt(t,e,n){return e(this,typeof n=="function"?n(t(this)):n)}var ai,uvt,jPe,Aee,kee,cW,Nee,pvt,mvt,Oee,VPe,lW,KPe,WPe,oA,Mee,hvt,gvt,HPe,Nx,qPe,Jh,pD,GPe,Ree=C(()=>{ai={},uvt=0;jPe=(t,e)=>t.unstable_is?t.unstable_is(e):e===t,Aee=t=>"init"in t,kee=t=>!!t.write,cW=new WeakMap,Nee=t=>{var e;return Oee(t)&&!((e=cW.get(t))!=null&&e[1])},pvt=(t,e)=>{let n=cW.get(t);if(n)n[1]=!0,n[0].forEach(r=>r(e));else if((ai.env?ai.env.MODE:void 0)!=="production")throw new Error("[Bug] cancelable promise not found")},mvt=t=>{if(cW.has(t))return;let e=[new Set,!1];cW.set(t,e);let n=()=>{e[1]=!0};t.then(n,n),t.onCancel=r=>{e[0].add(r)}},Oee=t=>typeof t?.then=="function",VPe=t=>"v"in t||"e"in t,lW=t=>{if("e"in t)throw t.e;if((ai.env?ai.env.MODE:void 0)!=="production"&&!("v"in t))throw new Error("[Bug] atom state is not initialized");return t.v},KPe=(t,e,n)=>{n.p.has(t)||(n.p.add(t),e.then(()=>{n.p.delete(t)},()=>{n.p.delete(t)}))},WPe=(t,e,n,r,o)=>{var i;if((ai.env?ai.env.MODE:void 0)!=="production"&&r===e)throw new Error("[Bug] atom cannot depend on itself");n.d.set(r,o.n),Nee(n.v)&&KPe(e,n.v,o),(i=o.m)==null||i.t.add(e),t&&hvt(t,r,e)},oA=()=>[new Map,new Map,new Set],Mee=(t,e,n)=>{t[0].has(e)||t[0].set(e,new Set),t[1].set(e,n)},hvt=(t,e,n)=>{let r=t[0].get(e);r&&r.add(n)},gvt=(t,e)=>t[0].get(e),HPe=(t,e)=>{t[2].add(e)},Nx=t=>{let e,n=!1,r=o=>{try{o()}catch(i){n||(e=i,n=!0)}};for(;t[1].size||t[2].size;){t[0].clear();let o=new Set(t[1].values());t[1].clear();let i=new Set(t[2]);t[2].clear(),o.forEach(s=>{var a;return(a=s.m)==null?void 0:a.l.forEach(r)}),i.forEach(r)}if(n)throw e},qPe=(...[t,e,n,r])=>{let o;(ai.env?ai.env.MODE:void 0)!=="production"&&(o=new Set);let i=(v,x,b)=>{let _="v"in x,T=x.v,S=Nee(x.v)?x.v:null;if(Oee(b)){mvt(b);for(let P of x.d.keys())KPe(v,b,t(P));x.v=b,delete x.e}else x.v=b,delete x.e;(!_||!Object.is(T,x.v))&&(++x.n,S&&pvt(S,b))},s=(v,x,b)=>{var _;let T=t(x);if(VPe(T)&&(T.m&&!b?.has(x)||Array.from(T.d).every(([$,B])=>s(v,$,b).n===B)))return T;T.d.clear();let S=!0,P=$=>{if(jPe(x,$)){let W=t($);if(!VPe(W))if(Aee($))i($,W,$.init);else throw new Error("no atom init");return lW(W)}let B=s(v,$,b);try{return lW(B)}finally{if(S)WPe(v,x,T,$,B);else{let W=oA();WPe(W,x,T,$,B),p(W,x,T),Nx(W)}}},A,O,D={get signal(){return A||(A=new AbortController),A.signal},get setSelf(){return(ai.env?ai.env.MODE:void 0)!=="production"&&!kee(x)&&console.warn("setSelf function cannot be used with read-only atom"),!O&&kee(x)&&(O=(...$)=>{if((ai.env?ai.env.MODE:void 0)!=="production"&&S&&console.warn("setSelf function cannot be called in sync"),!S)return f(x,...$)}),O}};try{let $=e(x,P,D);if(i(x,T,$),Oee($)){(_=$.onCancel)==null||_.call($,()=>A?.abort());let B=()=>{if(T.m){let W=oA();p(W,x,T),Nx(W)}};$.then(B,B)}return T}catch($){return delete T.v,T.e=$,++T.n,T}finally{S=!1}},a=v=>lW(s(void 0,v)),l=(v,x,b)=>{var _,T;let S=new Map;for(let P of((_=b.m)==null?void 0:_.t)||[])S.set(P,t(P));for(let P of b.p)S.set(P,t(P));return(T=gvt(v,x))==null||T.forEach(P=>{S.set(P,t(P))}),S};function c(v,x,b){let _=[],T=new Set,S=new Set,P=[[x,b]];for(;P.length>0;){let[A,O]=P[P.length-1];if(S.has(A)){P.pop();continue}if(T.has(A)){_.push([A,O,O.n]),S.add(A),P.pop();continue}T.add(A);for(let[D,$]of l(v,A,O))A!==D&&!T.has(D)&&P.push([D,$])}return[_,S]}let u=(v,x,b)=>{let[_,T]=c(v,x,b),S=new Set([x]);for(let P=_.length-1;P>=0;--P){let[A,O,D]=_[P],$=!1;for(let B of O.d.keys())if(B!==A&&S.has(B)){$=!0;break}$&&(s(v,A,T),p(v,A,O),D!==O.n&&(Mee(v,A,O),S.add(A))),T.delete(A)}},d=(v,x,...b)=>{let _=!0,T=P=>lW(s(v,P)),S=(P,...A)=>{let O=t(P);try{if(jPe(x,P)){if(!Aee(P))throw new Error("atom not writable");let D=O.n,$=A[0];i(P,O,$),p(v,P,O),D!==O.n&&(Mee(v,P,O),u(v,P,O));return}else return d(v,P,...A)}finally{_||Nx(v)}};try{return n(x,T,S,...b)}finally{_=!1}},f=(v,...x)=>{let b=oA();try{return d(b,v,...x)}finally{Nx(b)}},p=(v,x,b)=>{if(b.m&&!Nee(b.v)){for(let _ of b.d.keys())b.m.d.has(_)||(m(v,_,t(_)).t.add(x),b.m.d.add(_));for(let _ of b.m.d||[])if(!b.d.has(_)){b.m.d.delete(_);let T=h(v,_,t(_));T?.t.delete(x)}}},m=(v,x,b)=>{if(!b.m){s(v,x);for(let _ of b.d.keys())m(v,_,t(_)).t.add(x);if(b.m={l:new Set,d:new Set(b.d.keys()),t:new Set},(ai.env?ai.env.MODE:void 0)!=="production"&&o.add(x),kee(x)){let _=b.m,T,S=(P,A)=>{let O=!0;T=(...D)=>{try{return d(P,x,...D)}finally{O||Nx(P)}};try{return A()}finally{O=!1}};HPe(v,()=>{let P=S(v,()=>r(x,(...A)=>T(...A)));P&&(_.u=A=>S(A,P))})}}return b.m},h=(v,x,b)=>{if(b.m&&!b.m.l.size&&!Array.from(b.m.t).some(_=>{var T;return(T=t(_).m)==null?void 0:T.d.has(x)})){let _=b.m.u;_&&HPe(v,()=>_(v)),delete b.m,(ai.env?ai.env.MODE:void 0)!=="production"&&o.delete(x);for(let T of b.d.keys()){let S=h(v,T,t(T));S?.t.delete(x)}return}return b.m},w={get:a,set:f,sub:(v,x)=>{let b=oA(),_=t(v),S=m(b,v,_).l;return S.add(x),Nx(b),()=>{S.delete(x);let P=oA();h(P,v,_),Nx(P)}},unstable_derive:v=>qPe(...v(t,e,n,r))};return(ai.env?ai.env.MODE:void 0)!=="production"&&Object.assign(w,{dev4_get_internal_weak_map:()=>({get:x=>{let b=t(x);if(b.n!==0)return b}}),dev4_get_mounted_atoms:()=>o,dev4_restore_atoms:x=>{let b=oA();for(let[_,T]of x)if(Aee(_)){let S=t(_),P=S.n;i(_,S,T),p(b,_,S),P!==S.n&&(Mee(b,_,S),u(b,_,S))}Nx(b)}}),w},Jh=()=>{let t=new WeakMap;return qPe(n=>{if((ai.env?ai.env.MODE:void 0)!=="production"&&!n)throw new Error("Atom is undefined or null");let r=t.get(n);return r||(r={d:new Map,p:new Set,n:0},t.set(n,r)),r},(n,...r)=>n.read(...r),(n,...r)=>n.write(...r),(n,...r)=>{var o;return(o=n.onMount)==null?void 0:o.call(n,...r)})},GPe=()=>(pD||(pD=Jh(),(ai.env?ai.env.MODE:void 0)!=="production"&&(globalThis.__JOTAI_DEFAULT_STORE__||(globalThis.__JOTAI_DEFAULT_STORE__=pD),globalThis.__JOTAI_DEFAULT_STORE__!==pD&&console.warn("Detected multiple Jotai instances. It may cause unexpected behavior with the default store. https://github.com/pmndrs/jotai/discussions/2044"))),pD)});var iEe=Tt(xr=>{"use strict";var mD=Symbol.for("react.element"),yvt=Symbol.for("react.portal"),wvt=Symbol.for("react.fragment"),vvt=Symbol.for("react.strict_mode"),xvt=Symbol.for("react.profiler"),bvt=Symbol.for("react.provider"),Cvt=Symbol.for("react.context"),_vt=Symbol.for("react.forward_ref"),Svt=Symbol.for("react.suspense"),Tvt=Symbol.for("react.memo"),Ivt=Symbol.for("react.lazy"),YPe=Symbol.iterator;function Pvt(t){return t===null||typeof t!="object"?null:(t=YPe&&t[YPe]||t["@@iterator"],typeof t=="function"?t:null)}var XPe={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},QPe=Object.assign,eEe={};function iA(t,e,n){this.props=t,this.context=e,this.refs=eEe,this.updater=n||XPe}iA.prototype.isReactComponent={};iA.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};iA.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function tEe(){}tEe.prototype=iA.prototype;function Dee(t,e,n){this.props=t,this.context=e,this.refs=eEe,this.updater=n||XPe}var $ee=Dee.prototype=new tEe;$ee.constructor=Dee;QPe($ee,iA.prototype);$ee.isPureReactComponent=!0;var ZPe=Array.isArray,nEe=Object.prototype.hasOwnProperty,Fee={current:null},rEe={key:!0,ref:!0,__self:!0,__source:!0};function oEe(t,e,n){var r,o={},i=null,s=null;if(e!=null)for(r in e.ref!==void 0&&(s=e.ref),e.key!==void 0&&(i=""+e.key),e)nEe.call(e,r)&&!rEe.hasOwnProperty(r)&&(o[r]=e[r]);var a=arguments.length-2;if(a===1)o.children=n;else if(1<a){for(var l=Array(a),c=0;c<a;c++)l[c]=arguments[c+2];o.children=l}if(t&&t.defaultProps)for(r in a=t.defaultProps,a)o[r]===void 0&&(o[r]=a[r]);return{$$typeof:mD,type:t,key:i,ref:s,props:o,_owner:Fee.current}}function Evt(t,e){return{$$typeof:mD,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function Uee(t){return typeof t=="object"&&t!==null&&t.$$typeof===mD}function Avt(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var JPe=/\/+/g;function Lee(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Avt(""+t.key):e.toString(36)}function dW(t,e,n,r,o){var i=typeof t;(i==="undefined"||i==="boolean")&&(t=null);var s=!1;if(t===null)s=!0;else switch(i){case"string":case"number":s=!0;break;case"object":switch(t.$$typeof){case mD:case yvt:s=!0}}if(s)return s=t,o=o(s),t=r===""?"."+Lee(s,0):r,ZPe(o)?(n="",t!=null&&(n=t.replace(JPe,"$&/")+"/"),dW(o,e,n,"",function(c){return c})):o!=null&&(Uee(o)&&(o=Evt(o,n+(!o.key||s&&s.key===o.key?"":(""+o.key).replace(JPe,"$&/")+"/")+t)),e.push(o)),1;if(s=0,r=r===""?".":r+":",ZPe(t))for(var a=0;a<t.length;a++){i=t[a];var l=r+Lee(i,a);s+=dW(i,e,n,l,o)}else if(l=Pvt(t),typeof l=="function")for(t=l.call(t),a=0;!(i=t.next()).done;)i=i.value,l=r+Lee(i,a++),s+=dW(i,e,n,l,o);else if(i==="object")throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return s}function uW(t,e,n){if(t==null)return t;var r=[],o=0;return dW(t,r,"","",function(i){return e.call(n,i,o++)}),r}function kvt(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Ac={current:null},fW={transition:null},Mvt={ReactCurrentDispatcher:Ac,ReactCurrentBatchConfig:fW,ReactCurrentOwner:Fee};xr.Children={map:uW,forEach:function(t,e,n){uW(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return uW(t,function(){e++}),e},toArray:function(t){return uW(t,function(e){return e})||[]},only:function(t){if(!Uee(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};xr.Component=iA;xr.Fragment=wvt;xr.Profiler=xvt;xr.PureComponent=Dee;xr.StrictMode=vvt;xr.Suspense=Svt;xr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Mvt;xr.cloneElement=function(t,e,n){if(t==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+t+".");var r=QPe({},t.props),o=t.key,i=t.ref,s=t._owner;if(e!=null){if(e.ref!==void 0&&(i=e.ref,s=Fee.current),e.key!==void 0&&(o=""+e.key),t.type&&t.type.defaultProps)var a=t.type.defaultProps;for(l in e)nEe.call(e,l)&&!rEe.hasOwnProperty(l)&&(r[l]=e[l]===void 0&&a!==void 0?a[l]:e[l])}var l=arguments.length-2;if(l===1)r.children=n;else if(1<l){a=Array(l);for(var c=0;c<l;c++)a[c]=arguments[c+2];r.children=a}return{$$typeof:mD,type:t.type,key:o,ref:i,props:r,_owner:s}};xr.createContext=function(t){return t={$$typeof:Cvt,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},t.Provider={$$typeof:bvt,_context:t},t.Consumer=t};xr.createElement=oEe;xr.createFactory=function(t){var e=oEe.bind(null,t);return e.type=t,e};xr.createRef=function(){return{current:null}};xr.forwardRef=function(t){return{$$typeof:_vt,render:t}};xr.isValidElement=Uee;xr.lazy=function(t){return{$$typeof:Ivt,_payload:{_status:-1,_result:t},_init:kvt}};xr.memo=function(t,e){return{$$typeof:Tvt,type:t,compare:e===void 0?null:e}};xr.startTransition=function(t){var e=fW.transition;fW.transition={};try{t()}finally{fW.transition=e}};xr.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.")};xr.useCallback=function(t,e){return Ac.current.useCallback(t,e)};xr.useContext=function(t){return Ac.current.useContext(t)};xr.useDebugValue=function(){};xr.useDeferredValue=function(t){return Ac.current.useDeferredValue(t)};xr.useEffect=function(t,e){return Ac.current.useEffect(t,e)};xr.useId=function(){return Ac.current.useId()};xr.useImperativeHandle=function(t,e,n){return Ac.current.useImperativeHandle(t,e,n)};xr.useInsertionEffect=function(t,e){return Ac.current.useInsertionEffect(t,e)};xr.useLayoutEffect=function(t,e){return Ac.current.useLayoutEffect(t,e)};xr.useMemo=function(t,e){return Ac.current.useMemo(t,e)};xr.useReducer=function(t,e,n){return Ac.current.useReducer(t,e,n)};xr.useRef=function(t){return Ac.current.useRef(t)};xr.useState=function(t){return Ac.current.useState(t)};xr.useSyncExternalStore=function(t,e,n){return Ac.current.useSyncExternalStore(t,e,n)};xr.useTransition=function(){return Ac.current.useTransition()};xr.version="18.2.0"});var U=Tt((Zon,sEe)=>{"use strict";sEe.exports=iEe()});function Wl(t,e){let n=lEe(e),[[r,o,i],s]=(0,Vl.useReducer)(c=>{let u=n.get(t);return Object.is(c[0],u)&&c[1]===n&&c[2]===t?c:[u,n,t]},void 0,()=>[n.get(t),n,t]),a=r;(o!==n||i!==t)&&(s(),a=n.get(t));let l=e?.delay;if((0,Vl.useEffect)(()=>{let c=n.sub(t,()=>{if(typeof l=="number"){let u=n.get(t);zee(u)&&cEe(aEe(u)),setTimeout(s,l);return}s()});return s(),c},[n,t,l]),(0,Vl.useDebugValue)(a),zee(a)){let c=aEe(a);return Ovt(c)}return a}function Rvt(t,e){let n=lEe(e);return(0,Vl.useCallback)((...o)=>{if((pW.env?pW.env.MODE:void 0)!=="production"&&!("write"in t))throw new Error("not writable atom");return n.set(t,...o)},[n,t])}function Hy(t,e){return[Wl(t,e),Rvt(t,e)]}var Vl,pW,Nvt,lEe,zee,cEe,Ovt,Bee,aEe,uEe=C(()=>{"use client";Vl=N(U(),1);Ree();pW={},Nvt=(0,Vl.createContext)(void 0),lEe=t=>{let e=(0,Vl.useContext)(Nvt);return t?.store||e||GPe()},zee=t=>typeof t?.then=="function",cEe=t=>{t.status="pending",t.then(e=>{t.status="fulfilled",t.value=e},e=>{t.status="rejected",t.reason=e})},Ovt=Vl.default.use||(t=>{if(t.status==="pending")throw t;if(t.status==="fulfilled")return t.value;throw t.status==="rejected"?t.reason:(cEe(t),t)}),Bee=new WeakMap,aEe=t=>{let e=Bee.get(t);return e||(e=new Promise((n,r)=>{let o=t,i=l=>c=>{o===l&&n(c)},s=l=>c=>{o===l&&r(c)},a=l=>{"onCancel"in l&&typeof l.onCancel=="function"&&l.onCancel(c=>{if((pW.env?pW.env.MODE:void 0)!=="production"&&c===l)throw new Error("[Bug] p is not updated even after cancelation");zee(c)?(Bee.set(c,e),o=c,c.then(i(c),s(c)),a(c)):n(c)})};t.then(i(t),s(t)),a(t)}),Bee.set(t,e)),e}});var Id=C(()=>{Ree();uEe()});function aA(t){return typeof t=="string"&&Lvt.includes(t)}function Dvt(t){return typeof t=="string"?t.trim():""}function mW(t){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;if(typeof t=="string"){let e=Number(t);if(Number.isFinite(e)&&e>0)return e;let n=Date.parse(t);if(Number.isFinite(n))return n}return null}function $vt(t,e){let n=new Intl.Collator(void 0),r=l=>Dvt(e.getName(l)),o=l=>{let c=e.getCreatedAtMs(l);return Number.isFinite(c)?c:0},i=l=>{let c=o(l);return mW(e.getLastUsedAtMs(l))??c},s=typeof e.getManualOrder=="function"?l=>{let c=e.getManualOrder?.(l);return typeof c=="number"&&Number.isFinite(c)?c:0}:null,a=t==="manual"&&!s?"name":t;return(l,c)=>{let u=r(l),d=r(c),f=o(l),p=o(c),m=i(l),h=i(c);if(a==="manual"){let v=s(l),x=s(c);if(v!==x)return v-x}else if(a==="name"){let v=n.compare(u,d);if(v!==0)return v}else if(a==="created"){let v=p-f;if(v!==0)return v}else{let v=h-m;if(v!==0)return v}let g=n.compare(u,d);if(g!==0)return g;let y=p-f;if(y!==0)return y;let w=h-m;return w!==0?w:0}}function Xh(t,e,n){return[...t].sort($vt(e,n))}var Lvt,sA,Ky=C(()=>{Lvt=["recent","created","name","manual"];sA=class{constructor(e={}){this.lastTouchedAtMsByKey=new Map;this.lastPersistedAtMsByKey=new Map;this.revision=0;this.listeners=new Set;this.minIntervalMs=e.minIntervalMs??3e4,this.nowMs=e.nowMs??(()=>Date.now())}notifyChange(){this.revision+=1;for(let e of this.listeners)e()}getRevision(){return this.revision}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}touch(e){let n=this.nowMs();return this.lastTouchedAtMsByKey.set(e,n),this.notifyChange(),n}shouldPersist(e,n){let r=this.lastTouchedAtMsByKey.get(e);if(!r)return null;let o=mW(n),i=this.lastPersistedAtMsByKey.get(e),s=Math.max(o??0,i??0);return s===0?r:r-s<this.minIntervalMs?null:r}markPersisted(e,n){let r=mW(n);if(!r)return;let o=this.lastPersistedAtMsByKey.get(e)??0;this.lastPersistedAtMsByKey.set(e,Math.max(o,r))}getLastTouchedAt(e){return this.lastTouchedAtMsByKey.get(e)??null}getEffectiveLastUsedAt(e,n){let r=this.lastTouchedAtMsByKey.get(e),o=mW(n);return Math.max(r??0,o??0)}clear(e){if(e){this.lastTouchedAtMsByKey.delete(e),this.lastPersistedAtMsByKey.delete(e),this.notifyChange();return}this.lastTouchedAtMsByKey.clear(),this.lastPersistedAtMsByKey.clear(),this.notifyChange()}}});var qy={};zn(qy,{getModelKeyFromModel:()=>ln,getSettings:()=>q,normalizeModelProvider:()=>pEe,resetSettings:()=>jee,sanitizeQaExclusions:()=>fEe,sanitizeSettings:()=>Vee,setSettings:()=>Ls,settingsAtom:()=>Ox,settingsStore:()=>Kn,subscribeToSettingsChange:()=>Ho,updateSetting:()=>pe,useSettingsValue:()=>Ht});function Fvt(t){let e=new Set((t.activeEmbeddingModels||[]).map(n=>ln(n)));return t.embeddingModelKey&&e.has(t.embeddingModelKey)?t.embeddingModelKey:Hn.embeddingModelKey}function Ls(t){let e=Uvt({...q(),...t});e.embeddingModelKey=Fvt(e),Kn.set(Ox,e)}function fEe(t){let n=(typeof t=="string"?t:QQ).split(",").map(o=>decodeURIComponent(o.trim())).filter(o=>o.length>0),r=new Map;return n.forEach(o=>{let i=o.replace(/\/+$/,""),s=i.length>0?i:o;if(s===Af){r.set(Af,Af);return}if(!r.has(s)){let a=i.length>0&&o.endsWith("/")?`${i}/`:o;r.set(s,a)}}),r.set(Af,Af),Array.from(r.values()).map(o=>encodeURIComponent(o)).join(",")}function pe(t,e){let n=q();Ls({...n,[t]:e})}function q(){return Kn.get(Ox)}function jee(){let t={...Hn,activeModels:Gh.map(e=>({...e,enabled:!0})),activeEmbeddingModels:OS.map(e=>({...e,enabled:!0}))};Ls(t)}function Ho(t){let e=q();return Kn.sub(Ox,()=>{let n=q();t(e,n),e=n})}function Ht(){return Wl(Ox,{store:Kn})}function pEe(t){return t==="azure_openai"?"azure openai":t}function Vee(t){let e=t||Hn,n=e,{enableSelfHostedSearch:r,selfHostedSearchUrl:o,selfHostedSearchApiKey:i,enableMiyoSearch:s}=n;e.userId||(e.userId=si()),e.activeEmbeddingModels?e.activeEmbeddingModels=e.activeEmbeddingModels.map(P=>({...P,provider:pEe(P.provider)})):e.activeEmbeddingModels=OS.map(P=>({...P,enabled:!0}));let a={...e},l=a;delete l.miyoRemoteVaultPath,delete l.miyoVaultName,delete l.enableMiyoSearch,r!==void 0&&a.enableSelfHostMode===void 0&&(a.enableSelfHostMode=r),o!==void 0&&!a.selfHostUrl&&(a.selfHostUrl=o),i!==void 0&&!a.selfHostApiKey&&(a.selfHostApiKey=i),s!==void 0&&a.enableMiyo===void 0&&(a.enableMiyo=s);let c=Number(e.temperature);a.temperature=isNaN(c)?Hn.temperature:c;let u=Number(e.maxTokens);a.maxTokens=isNaN(u)?Hn.maxTokens:u;let d=Number(e.contextTurns);a.contextTurns=isNaN(d)?Hn.contextTurns:d;let f=Number(e.embeddingRequestsPerMin);a.embeddingRequestsPerMin=isNaN(f)?Hn.embeddingRequestsPerMin:f;let p=Number(e.embeddingBatchSize);a.embeddingBatchSize=isNaN(p)?Hn.embeddingBatchSize:p;let m=Number(e.lexicalSearchRamLimit);if(isNaN(m)?a.lexicalSearchRamLimit=Hn.lexicalSearchRamLimit:a.lexicalSearchRamLimit=Math.min(1e3,Math.max(20,m)),typeof a.autoAddActiveContentToContext!="boolean"){let P=e.includeActiveNoteAsContext;typeof P=="boolean"?a.autoAddActiveContentToContext=P:a.autoAddActiveContentToContext=Hn.autoAddActiveContentToContext}typeof a.generateAIChatTitleOnSave!="boolean"&&(a.generateAIChatTitleOnSave=Hn.generateAIChatTitleOnSave),typeof a.enableMiyo!="boolean"&&(a.enableMiyo=Hn.enableMiyo),typeof a.miyoSearchAll!="boolean"&&(a.miyoSearchAll=Hn.miyoSearchAll),typeof a.miyoServerUrl!="string"&&(a.miyoServerUrl=Hn.miyoServerUrl),["firecrawl","perplexity"].includes(a.selfHostSearchProvider)||(a.selfHostSearchProvider=Hn.selfHostSearchProvider),typeof a.passMarkdownImages!="boolean"&&(a.passMarkdownImages=Hn.passMarkdownImages),typeof a.enableInlineCitations!="boolean"&&(a.enableInlineCitations=Hn.enableInlineCitations),typeof a.enableCustomPromptTemplating!="boolean"&&(a.enableCustomPromptTemplating=Hn.enableCustomPromptTemplating);let g=Number(e.autonomousAgentMaxIterations);isNaN(g)||g<4||g>eW?a.autonomousAgentMaxIterations=Hn.autonomousAgentMaxIterations:a.autonomousAgentMaxIterations=g,Array.isArray(a.autonomousAgentEnabledToolIds)||(a.autonomousAgentEnabledToolIds=Hn.autonomousAgentEnabledToolIds);let y={writeToFile:"writeFile",replaceInFile:"editFile"};a.autonomousAgentEnabledToolIds=a.autonomousAgentEnabledToolIds.map(P=>y[P]??P),(!a.memoryFolderName||typeof a.memoryFolderName!="string")&&(a.memoryFolderName=Hn.memoryFolderName),typeof a.enableRecentConversations!="boolean"&&(a.enableRecentConversations=Hn.enableRecentConversations),typeof a.enableSavedMemory!="boolean"&&(a.enableSavedMemory=Hn.enableSavedMemory);let w=Number(e.maxRecentConversations);isNaN(w)||w<10||w>50?a.maxRecentConversations=Hn.maxRecentConversations:a.maxRecentConversations=w,typeof a.autosaveChat!="boolean"&&(a.autosaveChat=Hn.autosaveChat);let v=Number(e.autoCompactThreshold);if(isNaN(v)?a.autoCompactThreshold=Hn.autoCompactThreshold:a.autoCompactThreshold=Math.min(1e6,Math.max(64e3,v)),typeof a.quickCommandIncludeNoteContext!="boolean"&&(a.quickCommandIncludeNoteContext=Hn.quickCommandIncludeNoteContext),e.quickCommandModelKey!==void 0&&typeof e.quickCommandModelKey!="string"&&(a.quickCommandModelKey=Hn.quickCommandModelKey),typeof a.autoAddSelectionToContext!="boolean"){let P=e.autoIncludeTextSelection;typeof P=="boolean"?a.autoAddSelectionToContext=P:a.autoAddSelectionToContext=Hn.autoAddSelectionToContext}typeof a.autoAcceptEdits!="boolean"&&(a.autoAcceptEdits=Hn.autoAcceptEdits),Object.values(JE).includes(a.defaultSendShortcut)||(a.defaultSendShortcut=Hn.defaultSendShortcut);let x=(e.defaultSaveFolder||"").trim();a.defaultSaveFolder=x.length>0?x:Hn.defaultSaveFolder;let b=(e.customPromptsFolder||"").trim();a.customPromptsFolder=b.length>0?b:Hn.customPromptsFolder;let _=(e.projectsFolder||"").trim(),T=/(^|[/\\])\.\.[/\\]?/.test(_)||/^[a-zA-Z]:/.test(_)||/^[/\\]/.test(_);a.projectsFolder=_.length>0&&!T?_:Hn.projectsFolder,(!aA(a.chatHistorySortStrategy)||a.chatHistorySortStrategy==="manual")&&(a.chatHistorySortStrategy=Hn.chatHistorySortStrategy),(!aA(a.projectListSortStrategy)||a.projectListSortStrategy==="manual")&&(a.projectListSortStrategy=Hn.projectListSortStrategy);let S=(e.userSystemPromptsFolder||"").trim();return a.userSystemPromptsFolder=S.length>0?S:Hn.userSystemPromptsFolder,a.qaExclusions=fEe(e.qaExclusions),a}function Uvt(t){return t.activeModels=dEe(t.activeModels,Gh),t.activeEmbeddingModels=Bvt(dEe(t.activeEmbeddingModels,OS)),t}function ln(t){return`${t.name}|${t.provider}`}function dEe(t,e){let n=new Map;return e.filter(r=>r.core).forEach(r=>{n.set(ln(r),{...r})}),t.forEach(r=>{let o=ln(r),i=n.get(o);if(i){let s=e.find(a=>a.name===r.name&&a.provider===r.provider);s?n.set(o,{...s,...r,isBuiltIn:!0,believerExclusive:s.believerExclusive}):n.set(o,{...r,isBuiltIn:i.isBuiltIn})}else n.set(o,r)}),Array.from(n.values())}function Bvt(t){let e=new Set(Object.values(um));return t.filter(n=>e.has(n.provider))}var Kn,Ox,Se=C(()=>{Id();qh();Ky();It();Kn=Jh(),Ox=Oo(Hn)});function Xt(t,e=!1){try{if(t instanceof Error){let r=t.cause,o=r instanceof Error?r.message:r!=null?typeof r=="string"?r:JSON.stringify(r)??"":"",i=e&&t.stack?t.stack:"",s=[t.message];return o&&s.push(`more message: ${o}`),i&&s.push(i),s.join(`
`)}return JSON.stringify(t)??String(t)}catch{return String(t)}}var Wee=C(()=>{});var Gy,hW,gW,yW,dm,lA,Ri,fm,Rx=C(()=>{Gy=class extends Error{},hW=class extends Gy{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},gW=class extends Gy{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},yW=class extends Gy{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},dm=class extends Gy{},lA=class extends Gy{constructor(e){super(`Invalid unit ${e}`)}},Ri=class extends Gy{},fm=class extends Gy{constructor(){super("Zone is an abstract class")}}});var ft,pm,Pd,Lx,hD,Hee,gD,yD,wD,vD,xD,bD,CD,_D,SD,TD,ID,PD,ED,AD,Kee,kD,MD,ND,OD,RD=C(()=>{ft="numeric",pm="short",Pd="long",Lx={year:ft,month:ft,day:ft},hD={year:ft,month:pm,day:ft},Hee={year:ft,month:pm,day:ft,weekday:pm},gD={year:ft,month:Pd,day:ft},yD={year:ft,month:Pd,day:ft,weekday:Pd},wD={hour:ft,minute:ft},vD={hour:ft,minute:ft,second:ft},xD={hour:ft,minute:ft,second:ft,timeZoneName:pm},bD={hour:ft,minute:ft,second:ft,timeZoneName:Pd},CD={hour:ft,minute:ft,hourCycle:"h23"},_D={hour:ft,minute:ft,second:ft,hourCycle:"h23"},SD={hour:ft,minute:ft,second:ft,hourCycle:"h23",timeZoneName:pm},TD={hour:ft,minute:ft,second:ft,hourCycle:"h23",timeZoneName:Pd},ID={year:ft,month:ft,day:ft,hour:ft,minute:ft},PD={year:ft,month:ft,day:ft,hour:ft,minute:ft,second:ft},ED={year:ft,month:pm,day:ft,hour:ft,minute:ft},AD={year:ft,month:pm,day:ft,hour:ft,minute:ft,second:ft},Kee={year:ft,month:pm,day:ft,weekday:pm,hour:ft,minute:ft},kD={year:ft,month:Pd,day:ft,hour:ft,minute:ft,timeZoneName:pm},MD={year:ft,month:Pd,day:ft,hour:ft,minute:ft,second:ft,timeZoneName:pm},ND={year:ft,month:Pd,day:ft,weekday:Pd,hour:ft,minute:ft,timeZoneName:Pd},OD={year:ft,month:Pd,day:ft,weekday:Pd,hour:ft,minute:ft,second:ft,timeZoneName:Pd}});var Tu,$S=C(()=>{Rx();Tu=class{get type(){throw new fm}get name(){throw new fm}get ianaName(){return this.name}get isUniversal(){throw new fm}offsetName(e,n){throw new fm}formatOffset(e,n){throw new fm}offset(e){throw new fm}equals(e){throw new fm}get isValid(){throw new fm}}});var qee,Dx,vW=C(()=>{kc();$S();qee=null,Dx=class t extends Tu{static get instance(){return qee===null&&(qee=new t),qee}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return xW(e,n,r)}formatOffset(e,n){return $x(this.offset(e),n)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}});function zvt(t){return CW[t]||(CW[t]=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",era:"short"})),CW[t]}function Vvt(t,e){let n=t.format(e).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(n),[,o,i,s,a,l,c,u]=r;return[s,o,i,a,l,c,u]}function Wvt(t,e){let n=t.formatToParts(e),r=[];for(let o=0;o<n.length;o++){let{type:i,value:s}=n[o],a=jvt[i];i==="era"?r[a]=s:mn(a)||(r[a]=parseInt(s,10))}return r}var CW,jvt,bW,Hl,Fx=C(()=>{kc();$S();CW={};jvt={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};bW={},Hl=class t extends Tu{static create(e){return bW[e]||(bW[e]=new t(e)),bW[e]}static resetCache(){bW={},CW={}}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=t.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:n,locale:r}){return xW(e,n,r,this.name)}formatOffset(e,n){return $x(this.offset(e),n)}offset(e){let n=new Date(e);if(isNaN(n))return NaN;let r=zvt(this.name),[o,i,s,a,l,c,u]=r.formatToParts?Wvt(r,n):Vvt(r,n);a==="BC"&&(o=-Math.abs(o)+1);let f=cA({year:o,month:i,day:s,hour:l===24?0:l,minute:c,second:u,millisecond:0}),p=+n,m=p%1e3;return p-=m>=0?m:1e3+m,(f-p)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}});function Hvt(t,e={}){let n=JSON.stringify([t,e]),r=mEe[n];return r||(r=new Intl.ListFormat(t,e),mEe[n]=r),r}function Yee(t,e={}){let n=JSON.stringify([t,e]),r=Gee[n];return r||(r=new Intl.DateTimeFormat(t,e),Gee[n]=r),r}function Kvt(t,e={}){let n=JSON.stringify([t,e]),r=Zee[n];return r||(r=new Intl.NumberFormat(t,e),Zee[n]=r),r}function qvt(t,e={}){let{base:n,...r}=e,o=JSON.stringify([t,r]),i=Jee[o];return i||(i=new Intl.RelativeTimeFormat(t,e),Jee[o]=i),i}function Gvt(){return LD||(LD=new Intl.DateTimeFormat().resolvedOptions().locale,LD)}function Yvt(t){let e=hEe[t];if(!e){let n=new Intl.Locale(t);e="getWeekInfo"in n?n.getWeekInfo():n.weekInfo,hEe[t]=e}return e}function Zvt(t){let e=t.indexOf("-x-");e!==-1&&(t=t.substring(0,e));let n=t.indexOf("-u-");if(n===-1)return[t];{let r,o;try{r=Yee(t).resolvedOptions(),o=t}catch{let l=t.substring(0,n);r=Yee(l).resolvedOptions(),o=l}let{numberingSystem:i,calendar:s}=r;return[o,i,s]}}function Jvt(t,e,n){return(n||e)&&(t.includes("-u-")||(t+="-u"),n&&(t+=`-ca-${n}`),e&&(t+=`-nu-${e}`)),t}function Xvt(t){let e=[];for(let n=1;n<=12;n++){let r=hn.utc(2009,n,1);e.push(t(r))}return e}function Qvt(t){let e=[];for(let n=1;n<=7;n++){let r=hn.utc(2016,11,13+n);e.push(t(r))}return e}function _W(t,e,n,r){let o=t.listingMode();return o==="error"?null:o==="en"?n(e):r(e)}function ext(t){return t.numberingSystem&&t.numberingSystem!=="latn"?!1:t.numberingSystem==="latn"||!t.locale||t.locale.startsWith("en")||new Intl.DateTimeFormat(t.intl).resolvedOptions().numberingSystem==="latn"}var mEe,Gee,Zee,Jee,LD,hEe,Xee,Qee,ete,txt,Wr,$D=C(()=>{kc();IW();Ux();Bx();Fx();mEe={};Gee={};Zee={};Jee={};LD=null;hEe={};Xee=class{constructor(e,n,r){this.padTo=r.padTo||0,this.floor=r.floor||!1;let{padTo:o,floor:i,...s}=r;if(!n||Object.keys(s).length>0){let a={useGrouping:!1,...r};r.padTo>0&&(a.minimumIntegerDigits=r.padTo),this.inf=Kvt(e,a)}}format(e){if(this.inf){let n=this.floor?Math.floor(e):e;return this.inf.format(n)}else{let n=this.floor?Math.floor(e):uA(e,3);return vi(n,this.padTo)}}},Qee=class{constructor(e,n,r){this.opts=r,this.originalZone=void 0;let o;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let s=-1*(e.offset/60),a=s>=0?`Etc/GMT+${s}`:`Etc/GMT${s}`;e.offset!==0&&Hl.create(a).valid?(o=a,this.dt=e):(o="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,o=e.zone.name):(o="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let i={...this.opts};i.timeZone=i.timeZone||o,this.dtf=Yee(n,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(n=>{if(n.type==="timeZoneName"){let r=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...n,value:r}}else return n}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},ete=class{constructor(e,n,r){this.opts={style:"long",...r},!n&&SW()&&(this.rtf=qvt(e,r))}format(e,n){return this.rtf?this.rtf.format(e,n):gEe(n,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,n){return this.rtf?this.rtf.formatToParts(e,n):[]}},txt={firstDay:1,minimalDays:4,weekend:[6,7]},Wr=class t{static fromOpts(e){return t.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,n,r,o,i=!1){let s=e||Vr.defaultLocale,a=s||(i?"en-US":Gvt()),l=n||Vr.defaultNumberingSystem,c=r||Vr.defaultOutputCalendar,u=DD(o)||Vr.defaultWeekSettings;return new t(a,l,c,u,s)}static resetCache(){LD=null,Gee={},Zee={},Jee={}}static fromObject({locale:e,numberingSystem:n,outputCalendar:r,weekSettings:o}={}){return t.create(e,n,r,o)}constructor(e,n,r,o,i){let[s,a,l]=Zvt(e);this.locale=s,this.numberingSystem=n||a||null,this.outputCalendar=r||l||null,this.weekSettings=o,this.intl=Jvt(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=ext(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),n=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&n?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:t.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,DD(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,n=!1){return _W(this,e,tte,()=>{let r=n?{month:e,day:"numeric"}:{month:e},o=n?"format":"standalone";return this.monthsCache[o][e]||(this.monthsCache[o][e]=Xvt(i=>this.extract(i,r,"month"))),this.monthsCache[o][e]})}weekdays(e,n=!1){return _W(this,e,nte,()=>{let r=n?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},o=n?"format":"standalone";return this.weekdaysCache[o][e]||(this.weekdaysCache[o][e]=Qvt(i=>this.extract(i,r,"weekday"))),this.weekdaysCache[o][e]})}meridiems(){return _W(this,void 0,()=>rte,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[hn.utc(2016,11,13,9),hn.utc(2016,11,13,19)].map(n=>this.extract(n,e,"dayperiod"))}return this.meridiemCache})}eras(e){return _W(this,e,ote,()=>{let n={era:e};return this.eraCache[e]||(this.eraCache[e]=[hn.utc(-40,1,1),hn.utc(2017,1,1)].map(r=>this.extract(r,n,"era"))),this.eraCache[e]})}extract(e,n,r){let o=this.dtFormatter(e,n),i=o.formatToParts(),s=i.find(a=>a.type.toLowerCase()===r);return s?s.value:null}numberFormatter(e={}){return new Xee(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,n={}){return new Qee(e,this.intl,n)}relFormatter(e={}){return new ete(this.intl,this.isEnglish(),e)}listFormatter(e={}){return Hvt(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:TW()?Yvt(this.locale):txt}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}});var ste,Pa,dA=C(()=>{kc();$S();ste=null,Pa=class t extends Tu{static get utcInstance(){return ste===null&&(ste=new t(0)),ste}static instance(e){return e===0?t.utcInstance:new t(e)}static parseSpecifier(e){if(e){let n=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(n)return new t(FS(n[1],n[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${$x(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${$x(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,n){return $x(this.fixed,n)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}});var fA,ate=C(()=>{$S();fA=class extends Tu{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}});function mm(t,e){let n;if(mn(t)||t===null)return e;if(t instanceof Tu)return t;if(yEe(t)){let r=t.toLowerCase();return r==="default"?e:r==="local"||r==="system"?Dx.instance:r==="utc"||r==="gmt"?Pa.utcInstance:Pa.parseSpecifier(r)||Hl.create(t)}else return hm(t)?Pa.instance(t):typeof t=="object"&&"offset"in t&&typeof t.offset=="function"?t:new fA(t)}var PW=C(()=>{$S();Fx();dA();ate();kc();vW()});function vEe(t){let e=parseInt(t,10);if(isNaN(e)){e="";for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);if(t[n].search(lte.hanidec)!==-1)e+=nxt.indexOf(t[n]);else for(let o in wEe){let[i,s]=wEe[o];r>=i&&r<=s&&(e+=r-i)}}return parseInt(e,10)}else return e}function xEe(){pA={}}function Of({numberingSystem:t},e=""){let n=t||"latn";return pA[n]||(pA[n]={}),pA[n][e]||(pA[n][e]=new RegExp(`${lte[n]}${e}`)),pA[n][e]}var lte,wEe,nxt,pA,cte=C(()=>{lte={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},wEe={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},nxt=lte.hanidec.replace(/[\[|\]]/g,"").split("");pA={}});var bEe,CEe,_Ee,SEe,TEe,IEe,PEe,EEe,Vr,Ux=C(()=>{vW();Fx();$D();Bx();PW();kc();cte();bEe=()=>Date.now(),CEe="system",_Ee=null,SEe=null,TEe=null,IEe=60,EEe=null,Vr=class{static get now(){return bEe}static set now(e){bEe=e}static set defaultZone(e){CEe=e}static get defaultZone(){return mm(CEe,Dx.instance)}static get defaultLocale(){return _Ee}static set defaultLocale(e){_Ee=e}static get defaultNumberingSystem(){return SEe}static set defaultNumberingSystem(e){SEe=e}static get defaultOutputCalendar(){return TEe}static set defaultOutputCalendar(e){TEe=e}static get defaultWeekSettings(){return EEe}static set defaultWeekSettings(e){EEe=DD(e)}static get twoDigitCutoffYear(){return IEe}static set twoDigitCutoffYear(e){IEe=e%100}static get throwOnInvalid(){return PEe}static set throwOnInvalid(e){PEe=e}static resetCaches(){Wr.resetCache(),Hl.resetCache(),hn.resetCache(),xEe()}}});var Ea,FD=C(()=>{Ea=class{constructor(e,n){this.reason=e,this.explanation=n}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}});function Rf(t,e){return new Ea("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${t}, which is invalid`)}function EW(t,e,n){let r=new Date(Date.UTC(t,e-1,n));t<100&&t>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);let o=r.getUTCDay();return o===0?7:o}function MEe(t,e,n){return n+(BS(t)?kEe:AEe)[e-1]}function NEe(t,e){let n=BS(t)?kEe:AEe,r=n.findIndex(i=>i<e),o=e-n[r];return{month:r+1,day:o}}function AW(t,e){return(t-e+7)%7+1}function UD(t,e=4,n=1){let{year:r,month:o,day:i}=t,s=MEe(r,o,i),a=AW(EW(r,o,i),n),l=Math.floor((s-a+14-e)/7),c;return l<1?(c=r-1,l=US(c,e,n)):l>US(r,e,n)?(c=r+1,l=1):c=r,{weekYear:c,weekNumber:l,weekday:a,...zD(t)}}function ute(t,e=4,n=1){let{weekYear:r,weekNumber:o,weekday:i}=t,s=AW(EW(r,1,e),n),a=zx(r),l=o*7+i-s-7+e,c;l<1?(c=r-1,l+=zx(c)):l>a?(c=r+1,l-=zx(r)):c=r;let{month:u,day:d}=NEe(c,l);return{year:c,month:u,day:d,...zD(t)}}function kW(t){let{year:e,month:n,day:r}=t,o=MEe(e,n,r);return{year:e,ordinal:o,...zD(t)}}function dte(t){let{year:e,ordinal:n}=t,{month:r,day:o}=NEe(e,n);return{year:e,month:r,day:o,...zD(t)}}function fte(t,e){if(!mn(t.localWeekday)||!mn(t.localWeekNumber)||!mn(t.localWeekYear)){if(!mn(t.weekday)||!mn(t.weekNumber)||!mn(t.weekYear))throw new dm("Cannot mix locale-based week fields with ISO-based week fields");return mn(t.localWeekday)||(t.weekday=t.localWeekday),mn(t.localWeekNumber)||(t.weekNumber=t.localWeekNumber),mn(t.localWeekYear)||(t.weekYear=t.localWeekYear),delete t.localWeekday,delete t.localWeekNumber,delete t.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function OEe(t,e=4,n=1){let r=BD(t.weekYear),o=Ed(t.weekNumber,1,US(t.weekYear,e,n)),i=Ed(t.weekday,1,7);return r?o?i?!1:Rf("weekday",t.weekday):Rf("week",t.weekNumber):Rf("weekYear",t.weekYear)}function REe(t){let e=BD(t.year),n=Ed(t.ordinal,1,zx(t.year));return e?n?!1:Rf("ordinal",t.ordinal):Rf("year",t.year)}function pte(t){let e=BD(t.year),n=Ed(t.month,1,12),r=Ed(t.day,1,mA(t.year,t.month));return e?n?r?!1:Rf("day",t.day):Rf("month",t.month):Rf("year",t.year)}function mte(t){let{hour:e,minute:n,second:r,millisecond:o}=t,i=Ed(e,0,23)||e===24&&n===0&&r===0&&o===0,s=Ed(n,0,59),a=Ed(r,0,59),l=Ed(o,0,999);return i?s?a?l?!1:Rf("millisecond",o):Rf("second",r):Rf("minute",n):Rf("hour",e)}var AEe,kEe,hte=C(()=>{kc();FD();Rx();AEe=[0,31,59,90,120,151,181,212,243,273,304,334],kEe=[0,31,60,91,121,152,182,213,244,274,305,335]});function mn(t){return typeof t>"u"}function hm(t){return typeof t=="number"}function BD(t){return typeof t=="number"&&t%1===0}function yEe(t){return typeof t=="string"}function DEe(t){return Object.prototype.toString.call(t)==="[object Date]"}function SW(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function TW(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function $Ee(t){return Array.isArray(t)?t:[t]}function gte(t,e,n){if(t.length!==0)return t.reduce((r,o)=>{let i=[e(o),o];return r&&n(r[0],i[0])===r[0]?r:i},null)[1]}function FEe(t,e){return e.reduce((n,r)=>(n[r]=t[r],n),{})}function jx(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function DD(t){if(t==null)return null;if(typeof t!="object")throw new Ri("Week settings must be an object");if(!Ed(t.firstDay,1,7)||!Ed(t.minimalDays,1,7)||!Array.isArray(t.weekend)||t.weekend.some(e=>!Ed(e,1,7)))throw new Ri("Invalid week settings");return{firstDay:t.firstDay,minimalDays:t.minimalDays,weekend:Array.from(t.weekend)}}function Ed(t,e,n){return BD(t)&&t>=e&&t<=n}function rxt(t,e){return t-e*Math.floor(t/e)}function vi(t,e=2){let n=t<0,r;return n?r="-"+(""+-t).padStart(e,"0"):r=(""+t).padStart(e,"0"),r}function Yy(t){if(!(mn(t)||t===null||t===""))return parseInt(t,10)}function Vx(t){if(!(mn(t)||t===null||t===""))return parseFloat(t)}function jD(t){if(!(mn(t)||t===null||t==="")){let e=parseFloat("0."+t)*1e3;return Math.floor(e)}}function uA(t,e,n=!1){let r=10**e;return(n?Math.trunc:Math.round)(t*r)/r}function BS(t){return t%4===0&&(t%100!==0||t%400===0)}function zx(t){return BS(t)?366:365}function mA(t,e){let n=rxt(e-1,12)+1,r=t+(e-n)/12;return n===2?BS(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][n-1]}function cA(t){let e=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second,t.millisecond);return t.year<100&&t.year>=0&&(e=new Date(e),e.setUTCFullYear(t.year,t.month-1,t.day)),+e}function LEe(t,e,n){return-AW(EW(t,1,e),n)+e-1}function US(t,e=4,n=1){let r=LEe(t,e,n),o=LEe(t+1,e,n);return(zx(t)-r+o)/7}function VD(t){return t>99?t:t>Vr.twoDigitCutoffYear?1900+t:2e3+t}function xW(t,e,n,r=null){let o=new Date(t),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(i.timeZone=r);let s={timeZoneName:e,...i},a=new Intl.DateTimeFormat(n,s).formatToParts(o).find(l=>l.type.toLowerCase()==="timezonename");return a?a.value:null}function FS(t,e){let n=parseInt(t,10);Number.isNaN(n)&&(n=0);let r=parseInt(e,10)||0,o=n<0||Object.is(n,-0)?-r:r;return n*60+o}function yte(t){let e=Number(t);if(typeof t=="boolean"||t===""||Number.isNaN(e))throw new Ri(`Invalid unit value ${t}`);return e}function hA(t,e){let n={};for(let r in t)if(jx(t,r)){let o=t[r];if(o==null)continue;n[e(r)]=yte(o)}return n}function $x(t,e){let n=Math.trunc(Math.abs(t/60)),r=Math.trunc(Math.abs(t%60)),o=t>=0?"+":"-";switch(e){case"short":return`${o}${vi(n,2)}:${vi(r,2)}`;case"narrow":return`${o}${n}${r>0?`:${r}`:""}`;case"techie":return`${o}${vi(n,2)}${vi(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function zD(t){return FEe(t,["hour","minute","second","millisecond"])}var kc=C(()=>{Rx();Ux();hte()});function tte(t){switch(t){case"narrow":return[...ixt];case"short":return[...wte];case"long":return[...oxt];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}function nte(t){switch(t){case"narrow":return[...sxt];case"short":return[...xte];case"long":return[...vte];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}function ote(t){switch(t){case"narrow":return[...cxt];case"short":return[...lxt];case"long":return[...axt];default:return null}}function UEe(t){return rte[t.hour<12?0:1]}function BEe(t,e){return nte(e)[t.weekday-1]}function zEe(t,e){return tte(e)[t.month-1]}function jEe(t,e){return ote(e)[t.year<0?0:1]}function gEe(t,e,n="always",r=!1){let o={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(t)===-1;if(n==="auto"&&i){let d=t==="days";switch(e){case 1:return d?"tomorrow":`next ${o[t][0]}`;case-1:return d?"yesterday":`last ${o[t][0]}`;case 0:return d?"today":`this ${o[t][0]}`;default:}}let s=Object.is(e,-0)||e<0,a=Math.abs(e),l=a===1,c=o[t],u=r?l?c[1]:c[2]||c[1]:l?o[t][0]:t;return s?`${a} ${u} ago`:`in ${a} ${u}`}var oxt,wte,ixt,vte,xte,sxt,rte,axt,lxt,cxt,IW=C(()=>{RD();kc();oxt=["January","February","March","April","May","June","July","August","September","October","November","December"],wte=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ixt=["J","F","M","A","M","J","J","A","S","O","N","D"];vte=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],xte=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],sxt=["M","T","W","T","F","S","S"];rte=["AM","PM"],axt=["Before Christ","Anno Domini"],lxt=["BC","AD"],cxt=["B","A"]});function VEe(t,e){let n="";for(let r of t)r.literal?n+=r.val:n+=e(r.val);return n}var uxt,Aa,WD=C(()=>{IW();RD();kc();uxt={D:Lx,DD:hD,DDD:gD,DDDD:yD,t:wD,tt:vD,ttt:xD,tttt:bD,T:CD,TT:_D,TTT:SD,TTTT:TD,f:ID,ff:ED,fff:kD,ffff:ND,F:PD,FF:AD,FFF:MD,FFFF:OD},Aa=class t{static create(e,n={}){return new t(e,n)}static parseFormat(e){let n=null,r="",o=!1,i=[];for(let s=0;s<e.length;s++){let a=e.charAt(s);a==="'"?(r.length>0&&i.push({literal:o||/^\s+$/.test(r),val:r}),n=null,r="",o=!o):o||a===n?r+=a:(r.length>0&&i.push({literal:/^\s+$/.test(r),val:r}),r=a,n=a)}return r.length>0&&i.push({literal:o||/^\s+$/.test(r),val:r}),i}static macroTokenToFormatOpts(e){return uxt[e]}constructor(e,n){this.opts=n,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,n){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...n}).format()}dtFormatter(e,n={}){return this.loc.dtFormatter(e,{...this.opts,...n})}formatDateTime(e,n){return this.dtFormatter(e,n).format()}formatDateTimeParts(e,n){return this.dtFormatter(e,n).formatToParts()}formatInterval(e,n){return this.dtFormatter(e.start,n).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,n){return this.dtFormatter(e,n).resolvedOptions()}num(e,n=0){if(this.opts.forceSimple)return vi(e,n);let r={...this.opts};return n>0&&(r.padTo=n),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,n){let r=this.loc.listingMode()==="en",o=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(p,m)=>this.loc.extract(e,p,m),s=p=>e.isOffsetFixed&&e.offset===0&&p.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,p.format):"",a=()=>r?UEe(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(p,m)=>r?zEe(e,p):i(m?{month:p}:{month:p,day:"numeric"},"month"),c=(p,m)=>r?BEe(e,p):i(m?{weekday:p}:{weekday:p,month:"long",day:"numeric"},"weekday"),u=p=>{let m=t.macroTokenToFormatOpts(p);return m?this.formatWithSystemDefault(e,m):p},d=p=>r?jEe(e,p):i({era:p},"era"),f=p=>{switch(p){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return s({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return s({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return s({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return a();case"d":return o?i({day:"numeric"},"day"):this.num(e.day);case"dd":return o?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return c("short",!0);case"cccc":return c("long",!0);case"ccccc":return c("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return c("short",!1);case"EEEE":return c("long",!1);case"EEEEE":return c("narrow",!1);case"L":return o?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return o?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return o?i({month:"numeric"},"month"):this.num(e.month);case"MM":return o?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return o?i({year:"numeric"},"year"):this.num(e.year);case"yy":return o?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return o?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return o?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return d("short");case"GG":return d("long");case"GGGGG":return d("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return u(p)}};return VEe(t.parseFormat(n),f)}formatDurationFromString(e,n){let r=l=>{switch(l[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},o=l=>c=>{let u=r(c);return u?this.num(l.get(u),c.length):c},i=t.parseFormat(n),s=i.reduce((l,{literal:c,val:u})=>c?l:l.concat(u),[]),a=e.shiftTo(...s.map(r).filter(l=>l));return VEe(i,o(a))}}});function yA(...t){let e=t.reduce((n,r)=>n+r.source,"");return RegExp(`^${e}$`)}function wA(...t){return e=>t.reduce(([n,r,o],i)=>{let[s,a,l]=i(e,o);return[{...n,...s},a||r,l]},[{},null,1]).slice(0,2)}function vA(t,...e){if(t==null)return[null,null];for(let[n,r]of e){let o=n.exec(t);if(o)return r(o)}return[null,null]}function KEe(...t){return(e,n)=>{let r={},o;for(o=0;o<t.length;o++)r[t[o]]=Yy(e[n+o]);return[r,null,n+o]}}function gA(t,e,n){let r=t[e];return mn(r)?n:Yy(r)}function vxt(t,e){return[{year:gA(t,e),month:gA(t,e+1,1),day:gA(t,e+2,1)},null,e+3]}function xA(t,e){return[{hours:gA(t,e,0),minutes:gA(t,e+1,0),seconds:gA(t,e+2,0),milliseconds:jD(t[e+3])},null,e+4]}function HD(t,e){let n=!t[e]&&!t[e+1],r=FS(t[e+1],t[e+2]),o=n?null:Pa.instance(r);return[{},o,e+3]}function KD(t,e){let n=t[e]?Hl.create(t[e]):null;return[{},n,e+1]}function Cxt(t){let[e,n,r,o,i,s,a,l,c]=t,u=e[0]==="-",d=l&&l[0]==="-",f=(p,m=!1)=>p!==void 0&&(m||p&&u)?-p:p;return[{years:f(Vx(n)),months:f(Vx(r)),weeks:f(Vx(o)),days:f(Vx(i)),hours:f(Vx(s)),minutes:f(Vx(a)),seconds:f(Vx(l),l==="-0"),milliseconds:f(jD(c),d)}]}function _te(t,e,n,r,o,i,s){let a={year:e.length===2?VD(Yy(e)):Yy(e),month:wte.indexOf(n)+1,day:Yy(r),hour:Yy(o),minute:Yy(i)};return s&&(a.second=Yy(s)),t&&(a.weekday=t.length>3?vte.indexOf(t)+1:xte.indexOf(t)+1),a}function Txt(t){let[,e,n,r,o,i,s,a,l,c,u,d]=t,f=_te(e,o,r,n,i,s,a),p;return l?p=_xt[l]:c?p=0:p=FS(u,d),[f,new Pa(p)]}function Ixt(t){return t.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}function WEe(t){let[,e,n,r,o,i,s,a]=t;return[_te(e,o,r,n,i,s,a),Pa.utcInstance]}function kxt(t){let[,e,n,r,o,i,s,a]=t;return[_te(e,a,n,r,o,i,s),Pa.utcInstance]}function JEe(t){return vA(t,[Mxt,ZEe],[Nxt,Lxt],[Oxt,Dxt],[Rxt,$xt])}function XEe(t){return vA(Ixt(t),[Sxt,Txt])}function QEe(t){return vA(t,[Pxt,WEe],[Ext,WEe],[Axt,kxt])}function eAe(t){return vA(t,[bxt,Cxt])}function tAe(t){return vA(t,[xxt,Fxt])}function nAe(t){return vA(t,[Uxt,ZEe],[Bxt,zxt])}var HEe,qEe,dxt,bte,GEe,Cte,fxt,pxt,mxt,hxt,gxt,yxt,YEe,wxt,xxt,bxt,_xt,Sxt,Pxt,Ext,Axt,Mxt,Nxt,Oxt,Rxt,ZEe,Lxt,Dxt,$xt,Fxt,Uxt,Bxt,zxt,Ste=C(()=>{kc();IW();dA();Fx();HEe=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;qEe=/(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/,dxt=`(?:${qEe.source}?(?:\\[(${HEe.source})\\])?)?`,bte=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,GEe=RegExp(`${bte.source}${dxt}`),Cte=RegExp(`(?:T${GEe.source})?`),fxt=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,pxt=/(\d{4})-?W(\d\d)(?:-?(\d))?/,mxt=/(\d{4})-?(\d{3})/,hxt=KEe("weekYear","weekNumber","weekDay"),gxt=KEe("year","ordinal"),yxt=/(\d{4})-(\d\d)-(\d\d)/,YEe=RegExp(`${bte.source} ?(?:${qEe.source}|(${HEe.source}))?`),wxt=RegExp(`(?: ${YEe.source})?`);xxt=RegExp(`^T?${bte.source}$`),bxt=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;_xt={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};Sxt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;Pxt=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Ext=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Axt=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;Mxt=yA(fxt,Cte),Nxt=yA(pxt,Cte),Oxt=yA(mxt,Cte),Rxt=yA(GEe),ZEe=wA(vxt,xA,HD,KD),Lxt=wA(hxt,xA,HD,KD),Dxt=wA(gxt,xA,HD,KD),$xt=wA(xA,HD,KD);Fxt=wA(xA);Uxt=yA(yxt,wxt),Bxt=yA(YEe),zxt=wA(xA,HD,KD)});function Wx(t,e,n=!1){let r={values:n?e.values:{...t.values,...e.values||{}},loc:t.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||t.conversionAccuracy,matrix:e.matrix||t.matrix};return new xi(r)}function sAe(t,e){let n=e.milliseconds??0;for(let r of Wxt.slice(1))e[r]&&(n+=e[r]*t[r].milliseconds);return n}function oAe(t,e){let n=sAe(t,e)<0?-1:1;zS.reduceRight((r,o)=>{if(mn(e[o]))return r;if(r){let i=e[r]*n,s=t[o][r],a=Math.floor(i/s);e[o]+=a*n,e[r]-=a*s*n}return o},null),zS.reduce((r,o)=>{if(mn(e[o]))return r;if(r){let i=e[r]%1;e[r]-=i,e[o]+=i*t[r][o]}return o},null)}function Hxt(t){let e={};for(let[n,r]of Object.entries(t))r!==0&&(e[n]=r);return e}var rAe,iAe,jxt,Lf,bA,Vxt,zS,Wxt,xi,qD=C(()=>{Rx();WD();FD();$D();Ste();kc();Ux();Bx();rAe="Invalid Duration",iAe={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},jxt={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...iAe},Lf=146097/400,bA=146097/4800,Vxt={years:{quarters:4,months:12,weeks:Lf/7,days:Lf,hours:Lf*24,minutes:Lf*24*60,seconds:Lf*24*60*60,milliseconds:Lf*24*60*60*1e3},quarters:{months:3,weeks:Lf/28,days:Lf/4,hours:Lf*24/4,minutes:Lf*24*60/4,seconds:Lf*24*60*60/4,milliseconds:Lf*24*60*60*1e3/4},months:{weeks:bA/7,days:bA,hours:bA*24,minutes:bA*24*60,seconds:bA*24*60*60,milliseconds:bA*24*60*60*1e3},...iAe},zS=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Wxt=zS.slice(0).reverse();xi=class t{constructor(e){let n=e.conversionAccuracy==="longterm"||!1,r=n?Vxt:jxt;e.matrix&&(r=e.matrix),this.values=e.values,this.loc=e.loc||Wr.create(),this.conversionAccuracy=n?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=r,this.isLuxonDuration=!0}static fromMillis(e,n){return t.fromObject({milliseconds:e},n)}static fromObject(e,n={}){if(e==null||typeof e!="object")throw new Ri(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new t({values:hA(e,t.normalizeUnit),loc:Wr.fromObject(n),conversionAccuracy:n.conversionAccuracy,matrix:n.matrix})}static fromDurationLike(e){if(hm(e))return t.fromMillis(e);if(t.isDuration(e))return e;if(typeof e=="object")return t.fromObject(e);throw new Ri(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,n){let[r]=eAe(e);return r?t.fromObject(r,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,n){let[r]=tAe(e);return r?t.fromObject(r,n):t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,n=null){if(!e)throw new Ri("need to specify a reason the Duration is invalid");let r=e instanceof Ea?e:new Ea(e,n);if(Vr.throwOnInvalid)throw new yW(r);return new t({invalid:r})}static normalizeUnit(e){let n={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!n)throw new lA(e);return n}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,n={}){let r={...n,floor:n.round!==!1&&n.floor!==!1};return this.isValid?Aa.create(this.loc,r).formatDurationFromString(this,e):rAe}toHuman(e={}){if(!this.isValid)return rAe;let n=zS.map(r=>{let o=this.values[r];return mn(o)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(o)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(n)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=uA(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let n=this.toMillis();return n<0||n>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},hn.fromMillis(n,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?sAe(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e),r={};for(let o of zS)(jx(n.values,o)||jx(this.values,o))&&(r[o]=n.get(o)+this.get(o));return Wx(this,{values:r},!0)}minus(e){if(!this.isValid)return this;let n=t.fromDurationLike(e);return this.plus(n.negate())}mapUnits(e){if(!this.isValid)return this;let n={};for(let r of Object.keys(this.values))n[r]=yte(e(this.values[r],r));return Wx(this,{values:n},!0)}get(e){return this[t.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let n={...this.values,...hA(e,t.normalizeUnit)};return Wx(this,{values:n})}reconfigure({locale:e,numberingSystem:n,conversionAccuracy:r,matrix:o}={}){let s={loc:this.loc.clone({locale:e,numberingSystem:n}),matrix:o,conversionAccuracy:r};return Wx(this,s)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return oAe(this.matrix,e),Wx(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=Hxt(this.normalize().shiftToAll().toObject());return Wx(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(s=>t.normalizeUnit(s));let n={},r={},o=this.toObject(),i;for(let s of zS)if(e.indexOf(s)>=0){i=s;let a=0;for(let c in r)a+=this.matrix[c][s]*r[c],r[c]=0;hm(o[s])&&(a+=o[s]);let l=Math.trunc(a);n[s]=l,r[s]=(a*1e3-l*1e3)/1e3}else hm(o[s])&&(r[s]=o[s]);for(let s in r)r[s]!==0&&(n[i]+=s===i?r[s]:r[s]/this.matrix[i][s]);return oAe(this.matrix,n),Wx(this,{values:n},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let n of Object.keys(this.values))e[n]=this.values[n]===0?0:-this.values[n];return Wx(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function n(r,o){return r===void 0||r===0?o===void 0||o===0:r===o}for(let r of zS)if(!n(this.values[r],e.values[r]))return!1;return!0}}});function Kxt(t,e){return!t||!t.isValid?Zy.invalid("missing or invalid start"):!e||!e.isValid?Zy.invalid("missing or invalid end"):e<t?Zy.invalid("end before start",`The end of an interval must be after its start, but you had start=${t.toISO()} and end=${e.toISO()}`):null}var CA,Zy,Tte=C(()=>{Bx();qD();Ux();Rx();FD();WD();RD();CA="Invalid Interval";Zy=class t{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,n=null){if(!e)throw new Ri("need to specify a reason the Interval is invalid");let r=e instanceof Ea?e:new Ea(e,n);if(Vr.throwOnInvalid)throw new gW(r);return new t({invalid:r})}static fromDateTimes(e,n){let r=_A(e),o=_A(n),i=Kxt(r,o);return i??new t({start:r,end:o})}static after(e,n){let r=xi.fromDurationLike(n),o=_A(e);return t.fromDateTimes(o,o.plus(r))}static before(e,n){let r=xi.fromDurationLike(n),o=_A(e);return t.fromDateTimes(o.minus(r),o)}static fromISO(e,n){let[r,o]=(e||"").split("/",2);if(r&&o){let i,s;try{i=hn.fromISO(r,n),s=i.isValid}catch{s=!1}let a,l;try{a=hn.fromISO(o,n),l=a.isValid}catch{l=!1}if(s&&l)return t.fromDateTimes(i,a);if(s){let c=xi.fromISO(o,n);if(c.isValid)return t.after(i,c)}else if(l){let c=xi.fromISO(r,n);if(c.isValid)return t.before(a,c)}}return t.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",n){if(!this.isValid)return NaN;let r=this.start.startOf(e,n),o;return n?.useLocaleWeeks?o=this.end.reconfigure({locale:r.locale}):o=this.end,o=o.startOf(e,n),Math.floor(o.diff(r,e).get(e))+(o.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:n}={}){return this.isValid?t.fromDateTimes(e||this.s,n||this.e):this}splitAt(...e){if(!this.isValid)return[];let n=e.map(_A).filter(s=>this.contains(s)).sort((s,a)=>s.toMillis()-a.toMillis()),r=[],{s:o}=this,i=0;for(;o<this.e;){let s=n[i]||this.e,a=+s>+this.e?this.e:s;r.push(t.fromDateTimes(o,a)),o=a,i+=1}return r}splitBy(e){let n=xi.fromDurationLike(e);if(!this.isValid||!n.isValid||n.as("milliseconds")===0)return[];let{s:r}=this,o=1,i,s=[];for(;r<this.e;){let a=this.start.plus(n.mapUnits(l=>l*o));i=+a>+this.e?this.e:a,s.push(t.fromDateTimes(r,i)),r=i,o+=1}return s}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let n=this.s>e.s?this.s:e.s,r=this.e<e.e?this.e:e.e;return n>=r?null:t.fromDateTimes(n,r)}union(e){if(!this.isValid)return this;let n=this.s<e.s?this.s:e.s,r=this.e>e.e?this.e:e.e;return t.fromDateTimes(n,r)}static merge(e){let[n,r]=e.sort((o,i)=>o.s-i.s).reduce(([o,i],s)=>i?i.overlaps(s)||i.abutsStart(s)?[o,i.union(s)]:[o.concat([i]),s]:[o,s],[[],null]);return r&&n.push(r),n}static xor(e){let n=null,r=0,o=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),s=Array.prototype.concat(...i),a=s.sort((l,c)=>l.time-c.time);for(let l of a)r+=l.type==="s"?1:-1,r===1?n=l.time:(n&&+n!=+l.time&&o.push(t.fromDateTimes(n,l.time)),n=null);return t.merge(o)}difference(...e){return t.xor([this].concat(e)).map(n=>this.intersection(n)).filter(n=>n&&!n.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:CA}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=Lx,n={}){return this.isValid?Aa.create(this.s.loc.clone(n),e).formatInterval(this):CA}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:CA}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:CA}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:CA}toFormat(e,{separator:n=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${n}${this.e.toFormat(e)}`:CA}toDuration(e,n){return this.isValid?this.e.diff(this.s,e,n):xi.invalid(this.invalidReason)}mapEndpoints(e){return t.fromDateTimes(e(this.s),e(this.e))}}});var Jy,Ite=C(()=>{Bx();Ux();$D();Fx();PW();kc();Jy=class{static hasDST(e=Vr.defaultZone){let n=hn.now().setZone(e).set({month:12});return!e.isUniversal&&n.offset!==n.set({month:6}).offset}static isValidIANAZone(e){return Hl.isValidZone(e)}static normalizeZone(e){return mm(e,Vr.defaultZone)}static getStartOfWeek({locale:e=null,locObj:n=null}={}){return(n||Wr.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:n=null}={}){return(n||Wr.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:n=null}={}){return(n||Wr.create(e)).getWeekendDays().slice()}static months(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null,outputCalendar:i="gregory"}={}){return(o||Wr.create(n,r,i)).months(e)}static monthsFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null,outputCalendar:i="gregory"}={}){return(o||Wr.create(n,r,i)).months(e,!0)}static weekdays(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null}={}){return(o||Wr.create(n,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:n=null,numberingSystem:r=null,locObj:o=null}={}){return(o||Wr.create(n,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return Wr.create(e).meridiems()}static eras(e="short",{locale:n=null}={}){return Wr.create(n,null,"gregory").eras(e)}static features(){return{relative:SW(),localeWeek:TW()}}}});function aAe(t,e){let n=o=>o.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=n(e)-n(t);return Math.floor(xi.fromMillis(r).as("days"))}function qxt(t,e,n){let r=[["years",(l,c)=>c.year-l.year],["quarters",(l,c)=>c.quarter-l.quarter+(c.year-l.year)*4],["months",(l,c)=>c.month-l.month+(c.year-l.year)*12],["weeks",(l,c)=>{let u=aAe(l,c);return(u-u%7)/7}],["days",aAe]],o={},i=t,s,a;for(let[l,c]of r)n.indexOf(l)>=0&&(s=l,o[l]=c(t,e),a=i.plus(o),a>e?(o[l]--,t=i.plus(o),t>e&&(a=t,o[l]--,t=i.plus(o))):t=a);return[t,o,a,s]}function lAe(t,e,n,r){let[o,i,s,a]=qxt(t,e,n),l=e-o,c=n.filter(d=>["hours","minutes","seconds","milliseconds"].indexOf(d)>=0);c.length===0&&(s<e&&(s=o.plus({[a]:1})),s!==o&&(i[a]=(i[a]||0)+l/(s-o)));let u=xi.fromObject(i,r);return c.length>0?xi.fromMillis(l,r).shiftTo(...c).plus(u):u}var cAe=C(()=>{qD()});function Yr(t,e=n=>n){return{regex:t,deser:([n])=>e(vEe(n))}}function Zxt(t){return t.replace(/\./g,"\\.?").replace(pAe,fAe)}function uAe(t){return t.replace(/\./g,"").replace(pAe," ").toLowerCase()}function gm(t,e){return t===null?null:{regex:RegExp(t.map(Zxt).join("|")),deser:([n])=>t.findIndex(r=>uAe(n)===uAe(r))+e}}function dAe(t,e){return{regex:t,deser:([,n,r])=>FS(n,r),groups:e}}function MW(t){return{regex:t,deser:([e])=>e}}function Jxt(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Xxt(t,e){let n=Of(e),r=Of(e,"{2}"),o=Of(e,"{3}"),i=Of(e,"{4}"),s=Of(e,"{6}"),a=Of(e,"{1,2}"),l=Of(e,"{1,3}"),c=Of(e,"{1,6}"),u=Of(e,"{1,9}"),d=Of(e,"{2,4}"),f=Of(e,"{4,6}"),p=g=>({regex:RegExp(Jxt(g.val)),deser:([y])=>y,literal:!0}),h=(g=>{if(t.literal)return p(g);switch(g.val){case"G":return gm(e.eras("short"),0);case"GG":return gm(e.eras("long"),0);case"y":return Yr(c);case"yy":return Yr(d,VD);case"yyyy":return Yr(i);case"yyyyy":return Yr(f);case"yyyyyy":return Yr(s);case"M":return Yr(a);case"MM":return Yr(r);case"MMM":return gm(e.months("short",!0),1);case"MMMM":return gm(e.months("long",!0),1);case"L":return Yr(a);case"LL":return Yr(r);case"LLL":return gm(e.months("short",!1),1);case"LLLL":return gm(e.months("long",!1),1);case"d":return Yr(a);case"dd":return Yr(r);case"o":return Yr(l);case"ooo":return Yr(o);case"HH":return Yr(r);case"H":return Yr(a);case"hh":return Yr(r);case"h":return Yr(a);case"mm":return Yr(r);case"m":return Yr(a);case"q":return Yr(a);case"qq":return Yr(r);case"s":return Yr(a);case"ss":return Yr(r);case"S":return Yr(l);case"SSS":return Yr(o);case"u":return MW(u);case"uu":return MW(a);case"uuu":return Yr(n);case"a":return gm(e.meridiems(),0);case"kkkk":return Yr(i);case"kk":return Yr(d,VD);case"W":return Yr(a);case"WW":return Yr(r);case"E":case"c":return Yr(n);case"EEE":return gm(e.weekdays("short",!1),1);case"EEEE":return gm(e.weekdays("long",!1),1);case"ccc":return gm(e.weekdays("short",!0),1);case"cccc":return gm(e.weekdays("long",!0),1);case"Z":case"ZZ":return dAe(new RegExp(`([+-]${a.source})(?::(${r.source}))?`),2);case"ZZZ":return dAe(new RegExp(`([+-]${a.source})(${r.source})?`),2);case"z":return MW(/[a-z_+-/]{1,256}?/i);case" ":return MW(/[^\S\n\r]/);default:return p(g)}})(t)||{invalidReason:Gxt};return h.token=t,h}function ebt(t,e,n){let{type:r,value:o}=t;if(r==="literal"){let l=/^\s+$/.test(o);return{literal:!l,val:l?" ":o}}let i=e[r],s=r;r==="hour"&&(e.hour12!=null?s=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?s="hour12":s="hour24":s=n.hour12?"hour12":"hour24");let a=Qxt[s];if(typeof a=="object"&&(a=a[i]),a)return{literal:!1,val:a}}function tbt(t){return[`^${t.map(n=>n.regex).reduce((n,r)=>`${n}(${r.source})`,"")}$`,t]}function nbt(t,e,n){let r=t.match(e);if(r){let o={},i=1;for(let s in n)if(jx(n,s)){let a=n[s],l=a.groups?a.groups+1:1;!a.literal&&a.token&&(o[a.token.val[0]]=a.deser(r.slice(i,i+l))),i+=l}return[r,o]}else return[r,{}]}function rbt(t){let e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},n=null,r;return mn(t.z)||(n=Hl.create(t.z)),mn(t.Z)||(n||(n=new Pa(t.Z)),r=t.Z),mn(t.q)||(t.M=(t.q-1)*3+1),mn(t.h)||(t.h<12&&t.a===1?t.h+=12:t.h===12&&t.a===0&&(t.h=0)),t.G===0&&t.y&&(t.y=-t.y),mn(t.u)||(t.S=jD(t.u)),[Object.keys(t).reduce((i,s)=>{let a=e(s);return a&&(i[a]=t[s]),i},{}),n,r]}function obt(){return Pte||(Pte=hn.fromMillis(1555555555555)),Pte}function ibt(t,e){if(t.literal)return t;let n=Aa.macroTokenToFormatOpts(t.val),r=kte(n,e);return r==null||r.includes(void 0)?t:r}function Ete(t,e){return Array.prototype.concat(...t.map(n=>ibt(n,e)))}function Ate(t,e,n){return new GD(t,n).explainFromTokens(e)}function mAe(t,e,n){let{result:r,zone:o,specificOffset:i,invalidReason:s}=Ate(t,e,n);return[r,o,i,s]}function kte(t,e){if(!t)return null;let r=Aa.create(e,t).dtFormatter(obt()),o=r.formatToParts(),i=r.resolvedOptions();return o.map(s=>ebt(s,t,i))}var Gxt,Yxt,fAe,pAe,Qxt,Pte,GD,hAe=C(()=>{kc();WD();dA();Fx();Bx();cte();Rx();Gxt="missing Intl.DateTimeFormat.formatToParts support";Yxt="\xA0",fAe=`[ ${Yxt}]`,pAe=new RegExp(fAe,"g");Qxt={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};Pte=null;GD=class{constructor(e,n){if(this.locale=e,this.format=n,this.tokens=Ete(Aa.parseFormat(n),e),this.units=this.tokens.map(r=>Xxt(r,e)),this.disqualifyingUnit=this.units.find(r=>r.invalidReason),!this.disqualifyingUnit){let[r,o]=tbt(this.units);this.regex=RegExp(r,"i"),this.handlers=o}}explainFromTokens(e){if(this.isValid){let[n,r]=nbt(e,this.regex,this.handlers),[o,i,s]=r?rbt(r):[null,null,void 0];if(jx(r,"a")&&jx(r,"H"))throw new dm("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:n,matches:r,result:o,zone:i,specificOffset:s}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}});function YD(t){return new Ea("unsupported zone",`the zone "${t.name}" is not supported`)}function Nte(t){return t.weekData===null&&(t.weekData=UD(t.c)),t.weekData}function Ote(t){return t.localWeekData===null&&(t.localWeekData=UD(t.c,t.loc.getMinDaysInFirstWeek(),t.loc.getStartOfWeek())),t.localWeekData}function jS(t,e){let n={ts:t.ts,zone:t.zone,c:t.c,o:t.o,loc:t.loc,invalid:t.invalid};return new hn({...n,...e,old:n})}function _Ae(t,e,n){let r=t-e*60*1e3,o=n.offset(r);if(e===o)return[r,e];r-=(o-e)*60*1e3;let i=n.offset(r);return o===i?[r,o]:[t-Math.min(o,i)*60*1e3,Math.max(o,i)]}function NW(t,e){t+=e*60*1e3;let n=new Date(t);return{year:n.getUTCFullYear(),month:n.getUTCMonth()+1,day:n.getUTCDate(),hour:n.getUTCHours(),minute:n.getUTCMinutes(),second:n.getUTCSeconds(),millisecond:n.getUTCMilliseconds()}}function RW(t,e,n){return _Ae(cA(t),e,n)}function yAe(t,e){let n=t.o,r=t.c.year+Math.trunc(e.years),o=t.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...t.c,year:r,month:o,day:Math.min(t.c.day,mA(r,o))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},s=xi.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),a=cA(i),[l,c]=_Ae(a,n,t.zone);return s!==0&&(l+=s,c=t.zone.offset(l)),{ts:l,o:c}}function SA(t,e,n,r,o,i){let{setZone:s,zone:a}=n;if(t&&Object.keys(t).length!==0||e){let l=e||a,c=hn.fromObject(t,{...n,zone:l,specificOffset:i});return s?c:c.setZone(a)}else return hn.invalid(new Ea("unparsable",`the input "${o}" can't be parsed as ${r}`))}function OW(t,e,n=!0){return t.isValid?Aa.create(Wr.create("en-US"),{allowZ:n,forceSimple:!0}).formatDateTimeFromString(t,e):null}function Rte(t,e){let n=t.c.year>9999||t.c.year<0,r="";return n&&t.c.year>=0&&(r+="+"),r+=vi(t.c.year,n?6:4),e?(r+="-",r+=vi(t.c.month),r+="-",r+=vi(t.c.day)):(r+=vi(t.c.month),r+=vi(t.c.day)),r}function wAe(t,e,n,r,o,i){let s=vi(t.c.hour);return e?(s+=":",s+=vi(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=":")):s+=vi(t.c.minute),(t.c.millisecond!==0||t.c.second!==0||!n)&&(s+=vi(t.c.second),(t.c.millisecond!==0||!r)&&(s+=".",s+=vi(t.c.millisecond,3))),o&&(t.isOffsetFixed&&t.offset===0&&!i?s+="Z":t.o<0?(s+="-",s+=vi(Math.trunc(-t.o/60)),s+=":",s+=vi(Math.trunc(-t.o%60))):(s+="+",s+=vi(Math.trunc(t.o/60)),s+=":",s+=vi(Math.trunc(t.o%60)))),i&&(s+="["+t.zone.ianaName+"]"),s}function ubt(t){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[t.toLowerCase()];if(!e)throw new lA(t);return e}function vAe(t){switch(t.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return ubt(t)}}function dbt(t){return DW[t]||(LW===void 0&&(LW=Vr.now()),DW[t]=t.offset(LW)),DW[t]}function xAe(t,e){let n=mm(e.zone,Vr.defaultZone);if(!n.isValid)return hn.invalid(YD(n));let r=Wr.fromObject(e),o,i;if(mn(t.year))o=Vr.now();else{for(let l of TAe)mn(t[l])&&(t[l]=SAe[l]);let s=pte(t)||mte(t);if(s)return hn.invalid(s);let a=dbt(n);[o,i]=RW(t,a,n)}return new hn({ts:o,zone:n,loc:r,o:i})}function bAe(t,e,n){let r=mn(n.round)?!0:n.round,o=(s,a)=>(s=uA(s,r||n.calendary?0:2,!0),e.loc.clone(n).relFormatter(n).format(s,a)),i=s=>n.calendary?e.hasSame(t,s)?0:e.startOf(s).diff(t.startOf(s),s).get(s):e.diff(t,s).get(s);if(n.unit)return o(i(n.unit),n.unit);for(let s of n.units){let a=i(s);if(Math.abs(a)>=1)return o(a,s)}return o(t>e?-0:0,n.units[n.units.length-1])}function CAe(t){let e={},n;return t.length>0&&typeof t[t.length-1]=="object"?(e=t[t.length-1],n=Array.from(t).slice(0,t.length-1)):n=Array.from(t),[e,n]}function _A(t){if(hn.isDateTime(t))return t;if(t&&t.valueOf&&hm(t.valueOf()))return hn.fromJSDate(t);if(t&&typeof t=="object")return hn.fromObject(t);throw new Ri(`Unknown datetime argument: ${t}, of type ${typeof t}`)}var Mte,gAe,SAe,sbt,abt,TAe,lbt,cbt,LW,DW,hn,Bx=C(()=>{qD();Tte();Ux();Ite();WD();dA();$D();kc();PW();cAe();Ste();hAe();hte();RD();Rx();FD();Mte="Invalid DateTime",gAe=864e13;SAe={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},sbt={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},abt={ordinal:1,hour:0,minute:0,second:0,millisecond:0},TAe=["year","month","day","hour","minute","second","millisecond"],lbt=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],cbt=["year","ordinal","hour","minute","second","millisecond"];DW={},hn=class t{constructor(e){let n=e.zone||Vr.defaultZone,r=e.invalid||(Number.isNaN(e.ts)?new Ea("invalid input"):null)||(n.isValid?null:YD(n));this.ts=mn(e.ts)?Vr.now():e.ts;let o=null,i=null;if(!r)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(n))[o,i]=[e.old.c,e.old.o];else{let a=hm(e.o)&&!e.old?e.o:n.offset(this.ts);o=NW(this.ts,a),r=Number.isNaN(o.year)?new Ea("invalid input"):null,o=r?null:o,i=r?null:a}this._zone=n,this.loc=e.loc||Wr.create(),this.invalid=r,this.weekData=null,this.localWeekData=null,this.c=o,this.o=i,this.isLuxonDateTime=!0}static now(){return new t({})}static local(){let[e,n]=CAe(arguments),[r,o,i,s,a,l,c]=n;return xAe({year:r,month:o,day:i,hour:s,minute:a,second:l,millisecond:c},e)}static utc(){let[e,n]=CAe(arguments),[r,o,i,s,a,l,c]=n;return e.zone=Pa.utcInstance,xAe({year:r,month:o,day:i,hour:s,minute:a,second:l,millisecond:c},e)}static fromJSDate(e,n={}){let r=DEe(e)?e.valueOf():NaN;if(Number.isNaN(r))return t.invalid("invalid input");let o=mm(n.zone,Vr.defaultZone);return o.isValid?new t({ts:r,zone:o,loc:Wr.fromObject(n)}):t.invalid(YD(o))}static fromMillis(e,n={}){if(hm(e))return e<-gAe||e>gAe?t.invalid("Timestamp out of range"):new t({ts:e,zone:mm(n.zone,Vr.defaultZone),loc:Wr.fromObject(n)});throw new Ri(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,n={}){if(hm(e))return new t({ts:e*1e3,zone:mm(n.zone,Vr.defaultZone),loc:Wr.fromObject(n)});throw new Ri("fromSeconds requires a numerical input")}static fromObject(e,n={}){e=e||{};let r=mm(n.zone,Vr.defaultZone);if(!r.isValid)return t.invalid(YD(r));let o=Wr.fromObject(n),i=hA(e,vAe),{minDaysInFirstWeek:s,startOfWeek:a}=fte(i,o),l=Vr.now(),c=mn(n.specificOffset)?r.offset(l):n.specificOffset,u=!mn(i.ordinal),d=!mn(i.year),f=!mn(i.month)||!mn(i.day),p=d||f,m=i.weekYear||i.weekNumber;if((p||u)&&m)throw new dm("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(f&&u)throw new dm("Can't mix ordinal dates with month/day");let h=m||i.weekday&&!p,g,y,w=NW(l,c);h?(g=lbt,y=sbt,w=UD(w,s,a)):u?(g=cbt,y=abt,w=kW(w)):(g=TAe,y=SAe);let v=!1;for(let A of g){let O=i[A];mn(O)?v?i[A]=y[A]:i[A]=w[A]:v=!0}let x=h?OEe(i,s,a):u?REe(i):pte(i),b=x||mte(i);if(b)return t.invalid(b);let _=h?ute(i,s,a):u?dte(i):i,[T,S]=RW(_,c,r),P=new t({ts:T,zone:r,o:S,loc:o});return i.weekday&&p&&e.weekday!==P.weekday?t.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${P.toISO()}`):P.isValid?P:t.invalid(P.invalid)}static fromISO(e,n={}){let[r,o]=JEe(e);return SA(r,o,n,"ISO 8601",e)}static fromRFC2822(e,n={}){let[r,o]=XEe(e);return SA(r,o,n,"RFC 2822",e)}static fromHTTP(e,n={}){let[r,o]=QEe(e);return SA(r,o,n,"HTTP",n)}static fromFormat(e,n,r={}){if(mn(e)||mn(n))throw new Ri("fromFormat requires an input string and a format");let{locale:o=null,numberingSystem:i=null}=r,s=Wr.fromOpts({locale:o,numberingSystem:i,defaultToEN:!0}),[a,l,c,u]=mAe(s,e,n);return u?t.invalid(u):SA(a,l,r,`format ${n}`,e,c)}static fromString(e,n,r={}){return t.fromFormat(e,n,r)}static fromSQL(e,n={}){let[r,o]=nAe(e);return SA(r,o,n,"SQL",e)}static invalid(e,n=null){if(!e)throw new Ri("need to specify a reason the DateTime is invalid");let r=e instanceof Ea?e:new Ea(e,n);if(Vr.throwOnInvalid)throw new hW(r);return new t({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,n={}){let r=kte(e,Wr.fromObject(n));return r?r.map(o=>o?o.val:null).join(""):null}static expandFormat(e,n={}){return Ete(Aa.parseFormat(e),Wr.fromObject(n)).map(o=>o.val).join("")}static resetCache(){LW=void 0,DW={}}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?Nte(this).weekYear:NaN}get weekNumber(){return this.isValid?Nte(this).weekNumber:NaN}get weekday(){return this.isValid?Nte(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Ote(this).weekday:NaN}get localWeekNumber(){return this.isValid?Ote(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Ote(this).weekYear:NaN}get ordinal(){return this.isValid?kW(this.c).ordinal:NaN}get monthShort(){return this.isValid?Jy.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Jy.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Jy.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Jy.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,n=6e4,r=cA(this.c),o=this.zone.offset(r-e),i=this.zone.offset(r+e),s=this.zone.offset(r-o*n),a=this.zone.offset(r-i*n);if(s===a)return[this];let l=r-s*n,c=r-a*n,u=NW(l,s),d=NW(c,a);return u.hour===d.hour&&u.minute===d.minute&&u.second===d.second&&u.millisecond===d.millisecond?[jS(this,{ts:l}),jS(this,{ts:c})]:[this]}get isInLeapYear(){return BS(this.year)}get daysInMonth(){return mA(this.year,this.month)}get daysInYear(){return this.isValid?zx(this.year):NaN}get weeksInWeekYear(){return this.isValid?US(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?US(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:n,numberingSystem:r,calendar:o}=Aa.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:n,numberingSystem:r,outputCalendar:o}}toUTC(e=0,n={}){return this.setZone(Pa.instance(e),n)}toLocal(){return this.setZone(Vr.defaultZone)}setZone(e,{keepLocalTime:n=!1,keepCalendarTime:r=!1}={}){if(e=mm(e,Vr.defaultZone),e.equals(this.zone))return this;if(e.isValid){let o=this.ts;if(n||r){let i=e.offset(this.ts),s=this.toObject();[o]=RW(s,i,e)}return jS(this,{ts:o,zone:e})}else return t.invalid(YD(e))}reconfigure({locale:e,numberingSystem:n,outputCalendar:r}={}){let o=this.loc.clone({locale:e,numberingSystem:n,outputCalendar:r});return jS(this,{loc:o})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let n=hA(e,vAe),{minDaysInFirstWeek:r,startOfWeek:o}=fte(n,this.loc),i=!mn(n.weekYear)||!mn(n.weekNumber)||!mn(n.weekday),s=!mn(n.ordinal),a=!mn(n.year),l=!mn(n.month)||!mn(n.day),c=a||l,u=n.weekYear||n.weekNumber;if((c||s)&&u)throw new dm("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&s)throw new dm("Can't mix ordinal dates with month/day");let d;i?d=ute({...UD(this.c,r,o),...n},r,o):mn(n.ordinal)?(d={...this.toObject(),...n},mn(n.day)&&(d.day=Math.min(mA(d.year,d.month),d.day))):d=dte({...kW(this.c),...n});let[f,p]=RW(d,this.o,this.zone);return jS(this,{ts:f,o:p})}plus(e){if(!this.isValid)return this;let n=xi.fromDurationLike(e);return jS(this,yAe(this,n))}minus(e){if(!this.isValid)return this;let n=xi.fromDurationLike(e).negate();return jS(this,yAe(this,n))}startOf(e,{useLocaleWeeks:n=!1}={}){if(!this.isValid)return this;let r={},o=xi.normalizeUnit(e);switch(o){case"years":r.month=1;case"quarters":case"months":r.day=1;case"weeks":case"days":r.hour=0;case"hours":r.minute=0;case"minutes":r.second=0;case"seconds":r.millisecond=0;break;case"milliseconds":break}if(o==="weeks")if(n){let i=this.loc.getStartOfWeek(),{weekday:s}=this;s<i&&(r.weekNumber=this.weekNumber-1),r.weekday=i}else r.weekday=1;if(o==="quarters"){let i=Math.ceil(this.month/3);r.month=(i-1)*3+1}return this.set(r)}endOf(e,n){return this.isValid?this.plus({[e]:1}).startOf(e,n).minus(1):this}toFormat(e,n={}){return this.isValid?Aa.create(this.loc.redefaultToEN(n)).formatDateTimeFromString(this,e):Mte}toLocaleString(e=Lx,n={}){return this.isValid?Aa.create(this.loc.clone(n),e).formatDateTime(this):Mte}toLocaleParts(e={}){return this.isValid?Aa.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:n=!1,suppressMilliseconds:r=!1,includeOffset:o=!0,extendedZone:i=!1}={}){if(!this.isValid)return null;let s=e==="extended",a=Rte(this,s);return a+="T",a+=wAe(this,s,n,r,o,i),a}toISODate({format:e="extended"}={}){return this.isValid?Rte(this,e==="extended"):null}toISOWeekDate(){return OW(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:n=!1,includeOffset:r=!0,includePrefix:o=!1,extendedZone:i=!1,format:s="extended"}={}){return this.isValid?(o?"T":"")+wAe(this,s==="extended",n,e,r,i):null}toRFC2822(){return OW(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return OW(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Rte(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:n=!1,includeOffsetSpace:r=!0}={}){let o="HH:mm:ss.SSS";return(n||e)&&(r&&(o+=" "),n?o+="z":e&&(o+="ZZ")),OW(this,o,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Mte}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};let n={...this.c};return e.includeConfig&&(n.outputCalendar=this.outputCalendar,n.numberingSystem=this.loc.numberingSystem,n.locale=this.loc.locale),n}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,n="milliseconds",r={}){if(!this.isValid||!e.isValid)return xi.invalid("created by diffing an invalid DateTime");let o={locale:this.locale,numberingSystem:this.numberingSystem,...r},i=$Ee(n).map(xi.normalizeUnit),s=e.valueOf()>this.valueOf(),a=s?this:e,l=s?e:this,c=lAe(a,l,i,o);return s?c.negate():c}diffNow(e="milliseconds",n={}){return this.diff(t.now(),e,n)}until(e){return this.isValid?Zy.fromDateTimes(this,e):this}hasSame(e,n,r){if(!this.isValid)return!1;let o=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(n,r)<=o&&o<=i.endOf(n,r)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let n=e.base||t.fromObject({},{zone:this.zone}),r=e.padding?this<n?-e.padding:e.padding:0,o=["years","months","days","hours","minutes","seconds"],i=e.unit;return Array.isArray(e.unit)&&(o=e.unit,i=void 0),bAe(n,this.plus(r),{...e,numeric:"always",units:o,unit:i})}toRelativeCalendar(e={}){return this.isValid?bAe(e.base||t.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(t.isDateTime))throw new Ri("min requires all arguments be DateTimes");return gte(e,n=>n.valueOf(),Math.min)}static max(...e){if(!e.every(t.isDateTime))throw new Ri("max requires all arguments be DateTimes");return gte(e,n=>n.valueOf(),Math.max)}static fromFormatExplain(e,n,r={}){let{locale:o=null,numberingSystem:i=null}=r,s=Wr.fromOpts({locale:o,numberingSystem:i,defaultToEN:!0});return Ate(s,e,n)}static fromStringExplain(e,n,r={}){return t.fromFormatExplain(e,n,r)}static buildFormatParser(e,n={}){let{locale:r=null,numberingSystem:o=null}=n,i=Wr.fromOpts({locale:r,numberingSystem:o,defaultToEN:!0});return new GD(i,e)}static fromFormatParser(e,n,r={}){if(mn(e)||mn(n))throw new Ri("fromFormatParser requires an input string and a format parser");let{locale:o=null,numberingSystem:i=null}=r,s=Wr.fromOpts({locale:o,numberingSystem:i,defaultToEN:!0});if(!s.equals(n.locale))throw new Ri(`fromFormatParser called with a locale of ${s}, but the format parser was created for ${n.locale}`);let{result:a,zone:l,specificOffset:c,invalidReason:u}=n.explainFromTokens(e);return u?t.invalid(u):SA(a,l,r,`format ${n.format}`,e,c)}static get DATE_SHORT(){return Lx}static get DATE_MED(){return hD}static get DATE_MED_WITH_WEEKDAY(){return Hee}static get DATE_FULL(){return gD}static get DATE_HUGE(){return yD}static get TIME_SIMPLE(){return wD}static get TIME_WITH_SECONDS(){return vD}static get TIME_WITH_SHORT_OFFSET(){return xD}static get TIME_WITH_LONG_OFFSET(){return bD}static get TIME_24_SIMPLE(){return CD}static get TIME_24_WITH_SECONDS(){return _D}static get TIME_24_WITH_SHORT_OFFSET(){return SD}static get TIME_24_WITH_LONG_OFFSET(){return TD}static get DATETIME_SHORT(){return ID}static get DATETIME_SHORT_WITH_SECONDS(){return PD}static get DATETIME_MED(){return ED}static get DATETIME_MED_WITH_SECONDS(){return AD}static get DATETIME_MED_WITH_WEEKDAY(){return Kee}static get DATETIME_FULL(){return kD}static get DATETIME_FULL_WITH_SECONDS(){return MD}static get DATETIME_HUGE(){return ND}static get DATETIME_HUGE_WITH_SECONDS(){return OD}}});var Lte=C(()=>{Bx();qD();Tte();Ite();$S();dA();Fx();ate();vW();Ux()});function Ad(t,e){let n=q();return e?.apiKey||n[tW[t]]||""}function pbt(){return[{name:"copilot-plus-flash",provider:"copilot-plus"},{name:"google/gemini-2.5-flash",provider:"openrouterai"}]}function IAe(t){return pbt().some(e=>e.name===t.name&&e.provider===t.provider)}var VS=C(()=>{It();Se()});function Li(t,e,n={}){let r=n.leading??!1,o=n.trailing??!0,i,s,a,l=!1,c=()=>{let f=s;return s=void 0,l=!1,f&&(a=t(...f)),a},u=()=>{i=window.setTimeout(()=>{i=void 0,o&&l&&c()},e)},d=(...f)=>{s=f,l=!0;let p=i===void 0;return i!==void 0&&window.clearTimeout(i),p&&r&&c(),u(),a};return d.cancel=()=>{i!==void 0&&(window.clearTimeout(i),i=void 0),s=void 0,l=!1},d.flush=()=>i===void 0?a:(window.clearTimeout(i),i=void 0,l?c():a),d}var Hx=C(()=>{});function Xy(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function EAe(t){let e=t,n=e?.detail||{};return{status:n.status,message:n.message||e?.message,reason:n.reason}}function mbt(t){let e=EAe(t),r=t?.message;return!!(e.reason==="Invalid license key"||r==="Invalid license key"||r?.includes("status 403")||e.status===403)}function AAe(t){let e=EAe(t);return mbt(t)?$te.INVALID_LICENSE_KEY_USER:e.message||(e.reason?`Error: ${e.reason}`:$te.UNKNOWN_ERROR)}function TA(t){return t.replace(/^#/,"").trim()}function Qh(t,e={}){let{trimStart:n=!0}=e;if(t.startsWith("---")){let r=t.indexOf("---",3);if(r!==-1){let o=t.slice(r+3);return n?o.trimStart():o.startsWith(`\r
`)?o.slice(2):o.startsWith(`
`)||o.startsWith("\r")?o.slice(1):o}}return t}function eg(t,e=!0){let n=app.metadataCache.getFileCache(t),r=n?.frontmatter?.tags,o=new Set;if(!e){let i=n?.tags?.map(s=>s.tag);i&&i.forEach(s=>o.add(TA(s)))}return r&&(Array.isArray(r)?r.forEach(i=>{typeof i=="string"&&o.add(TA(i))}):typeof r=="string"&&o.add(TA(r))),Array.from(o)}function $W(t,e,n){if(e.length===0)return[];e=e.map(i=>TA(i));let r=n&&n.length>0?n:JD(t,"/"),o=[];for(let i of r){let s=eg(i);e.some(a=>s.includes(a))&&o.push(i)}return o}async function Fr(t){let e=(0,Kl.normalizePath)(t).replace(/^\/+/,"").replace(/\/+$/,"");if(!e)return;let n=e.split("/").filter(Boolean),r="";for(let o of n){r=r?`${r}/${o}`:o;let i=app.vault.getAbstractFileByPath(r);if(i){if(i instanceof Kl.TFile)throw new Error(`Path conflict: "${r}" exists as a file, expected folder.`);continue}await app.vault.adapter.mkdir(r)}}function FW(t){return t?lee.includes(t.extension):!1}async function IA(t,e){return FW(t)?await e.read(t):null}function UW(t){return t.basename}function tg(t){return t?gPe.includes(t.extension):!1}function Mc(t){return t==="copilot_plus"||t==="project"}function PA(t,e){return t?FW(t)?!0:Mc(e):!1}function kAe(t,e){return!t||!e?!1:t.includes(aee)&&e.includes(aee)||t==="small"&&e==="cohereai"||t==="cohereai"&&e==="small"?!0:t===e}function BW(t){let e=[],n=t.history;for(let r=0;r<n.length;r+=2){let o=n[r]?.content||"",i=n[r+1]?.content||"";e.push({role:"user",content:o},{role:"assistant",content:i})}return e}function MAe(t,e){let n=new Map;return t.forEach(r=>{let o=e.getAbstractFileByPath(r);if(o instanceof Kl.TFile)n.set(o.path,o);else{let s=e.getMarkdownFiles().filter(a=>a.basename===r);s.length>0&&(hbt(r,e)?n.set(s[0].path,s[0]):console.warn(`Found multiple files with title "${r}". Expected a full path for duplicate titles.`))}}),Array.from(n.values())}function Df(t,e){let n=/\[\[(.*?)\]\]/g,r=t.match(n);if(!r)return[];let o=r.map(i=>i.slice(2,-2));return MAe(o,e)}function NAe(t,e){let n=/\{\[\[(.*?)\]\]\}/g,r=t.match(n);if(!r)return[];let o=r.map(i=>i.slice(3,-3));return MAe(o,e)}function hbt(t,e){return e.getMarkdownFiles().filter(r=>r.basename===t).length===1}function OAe(t){return t=t.trim(),t.startsWith("[[")&&t.endsWith("]]")?`${t.slice(2,-2).trim()}.md`:t}function RAe(t){let e=new Set;return t.forEach(n=>{n.metadata?.title&&e.add(n.metadata.title)}),Array.from(e)}function Fte(t){if(!t||typeof t!="string")return{isValid:!1,error:"URL is required"};let e=t.trim();if(!e)return{isValid:!1,error:"URL cannot be empty"};let n=Ute(e);return n?/^[a-zA-Z0-9_-]{11}$/.test(n)?{isValid:!0,videoId:n}:{isValid:!1,error:"Invalid YouTube video ID"}:{isValid:!1,error:"Invalid YouTube URL format"}}function Ute(t){try{let e=[/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/)([a-zA-Z0-9_-]{11})/,/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/];for(let n of e){let r=t.match(n);if(r&&r[1])return r[1]}return null}catch{return null}}function LAe(t){return`https://www.youtube.com/watch?v=${t}`}function DAe(t){return Fte(t).isValid}function $Ae(t){if(!t||typeof t!="string")return!1;try{let e=new URL(t.trim());return(e.hostname==="x.com"||e.hostname==="www.x.com"||e.hostname==="twitter.com"||e.hostname==="www.twitter.com")&&e.pathname.includes("/status/")}catch{return!1}}function FAe(t){let e=t.matchAll(new RegExp(gbt,"g"));return Array.from(e,n=>n[0])}async function fo(t,e={}){let{throwOnHttpError:n=!0}=e,r=new Headers(e.headers),o=Object.fromEntries(r.entries());delete o["content-length"],k("safeFetch request");let i=e.method?.toUpperCase()||"POST",a=await(0,Kl.requestUrl)({url:t,contentType:"application/json",headers:o,method:i,...["POST","PUT","PATCH"].includes(i)&&typeof e.body=="string"&&{body:e.body},throw:!1});if(n&&a.status>=400){let l=null;try{l=typeof a.json=="string"?JSON.parse(a.json):a.json}catch{try{l=typeof a.text=="string"?JSON.parse(a.text):a.text}catch{l=null}}let c=new Error($te.REQUEST_FAILED(a.status));c.json=l;let u=l&&typeof l.detail=="object"?l.detail:void 0;if(u?.reason==="Invalid license key"||l?.reason==="Invalid license key")c.message="Invalid license key";else if(u?.message||l?.message){let d=u?.message||l?.message,f=u?.reason||l?.reason;c.message=f?`${d}: ${f}`:d??""}else l?.detail?c.message=JSON.stringify(l.detail):l&&(c.message+=". "+JSON.stringify(l));throw c}return{ok:a.status>=200&&a.status<300,status:a.status,statusText:a.status.toString(),headers:new Headers(a.headers),url:t,type:"basic",redirected:!1,bytes:()=>Promise.resolve(new Uint8Array(0)),body:ybt(a.text),bodyUsed:!0,json:()=>Promise.resolve(a.json),text:async()=>a.text,arrayBuffer:async()=>{if(a.arrayBuffer)return a.arrayBuffer;let l=a.text.replace(/^data:.*;base64,/,""),c=PAe.Buffer.from(l,"base64");return c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength)},blob:()=>{throw new Error("not implemented")},formData:()=>{throw new Error("not implemented")},clone:()=>{throw new Error("not implemented")}}}function Qy(t,e={}){return fo(t,{...e,throwOnHttpError:!1})}function ybt(t){return new ReadableStream({start(e){let r=new TextEncoder().encode(t);e.enqueue(r),e.close()}})}function XD(t,e){let n={...t};return e.forEach(r=>{delete n[r]}),n}function $f(t,e){let[n,r]=t.split("|"),o=e.find(i=>i.name===n&&i.provider===r);if(!o)throw new Error(`No model configuration found for: ${t}`);return o}function ew(t){let e=Cu[t];return{...e,label:e.label||t}}function cl(t,e){let n=Cu[t]?.label||t;return n+(e?.believerExclusive&&n==="Copilot Plus"?"(Believer)":"")}function ng(t){let e=t;return e=jte(e),e=e.replace(/```xml\s*[\s\S]*?<write(?:File|ToFile)>[\s\S]*?<\/write(?:File|ToFile)>[\s\S]*?```/g,""),e=e.replace(/<write(?:File|ToFile)>[\s\S]*?<\/write(?:File|ToFile)>/g,""),e=e.replace(/<!--TOOL_CALL_START:[^:]+:[^:]+:[^:]+:[^:]+:[^:]*:[^:]+-->[\s\S]*?<!--TOOL_CALL_END:[^:]+:[\s\S]*?-->/g,""),e=e.replace(/<!--AGENT_REASONING:\w+:\d+:.*-->/g,""),e=e.replace(/\n{3,}/g,`

`),e=e.trim(),e}async function EA(t,e=!1){let n=app.workspace.getMostRecentLeaf();if(!n){new Kl.Notice("No active leaf found.");return}if(n.view instanceof Kl.MarkdownView||(n=app.workspace.getLeaf(!1),await n.setViewState({type:"markdown",state:n.view.getState()})),!(n.view instanceof Kl.MarkdownView)){new Kl.Notice("Failed to open a markdown view.");return}let r=n.view.editor,o=r.getCursor("from"),i=r.getCursor("to"),s=ng(t),a=s.split(`
`),l=(w,v)=>{let x=v.length-1;return x===0?{line:w.line,ch:w.ch+(v[0]?.length??0)}:{line:w.line+x,ch:v[v.length-1]?.length??0}},c=()=>{let w=e?o:i;r.replaceRange(s,w,i),r.setSelection(w,l(w,a))},u=()=>{r.focus(),new Kl.Notice("Message inserted into the active note.")},d=r.cm;if(!(d?.state?.doc&&typeof d.dispatch=="function")){c(),u();return}let{from:p,to:m}=d.state.selection.main,h=e?p:m,g=d.state.toText(s),y=h+g.length;try{d.dispatch({changes:{from:h,to:m,insert:g},selection:{anchor:h,head:y}})}catch(w){ee("CM6 dispatch failed, falling back to Obsidian API",w),c()}u()}function zW(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if(n[o]>r[o])return!0;if(n[o]<r[o])return!1}return!1}async function UAe(){try{return{version:(await(0,Kl.requestUrl)({url:"https://api.github.com/repos/logancyang/obsidian-copilot/releases/latest",method:"GET"})).json.tag_name.replace("v",""),error:null}}catch(t){return{version:null,error:t instanceof Error?t.message:"Failed to check for updates"}}}function QD(t){if(typeof t=="string")return t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4");let e=t,n=e.modelName||e.model||"";return n.startsWith("o1")||n.startsWith("o3")||n.startsWith("o4")}function wbt(t){if(typeof t=="string")return t.startsWith("gpt-5");let e=t;return(e.modelName||e.model||"").startsWith("gpt-5")}function vbt(t){let e=t;return(typeof t=="string"?t:e.modelName||e.model||"").toLowerCase().includes("codex")}function Bte(t){return t.provider!=="github-copilot"?!1:t.useResponsesApi===!0?!0:vbt(t.name)}function AA(t){let e=t,n=typeof t=="string"?t:e.modelName||e.model||"",r=QD(n),o=wbt(n),i=n.startsWith("claude-3-7-sonnet")||n.startsWith("claude-sonnet-4")||n.startsWith("claude-opus-4"),s=n.match(/^claude-opus-4-(\d{1,2})(?:[-.]|$)/),a=s?parseInt(s[1],10)>=7:!1;return{isOSeries:r,isGPT5:o,isThinkingEnabled:i,usesAdaptiveThinking:a}}function e$(t,e="system"){return QD(t)?"human":e}function zte(){let t=["3rd party (openai-format)","ollama","lm-studio","azure openai","github-copilot","copilot-plus","copilot-plus-jina"];return Object.keys(Cu).filter(e=>!t.includes(e))}function kA(t,e){let n=t.provider;if(n==="amazon-bedrock")return t.apiKey||e.amazonBedrockApiKey?{hasApiKey:!0}:{hasApiKey:!1,errorNotice:"Amazon Bedrock API key is missing. Please add a key in Settings > API Keys or update the model configuration."};if(n==="github-copilot")return!(t.apiKey||e.githubCopilotToken||e.githubCopilotAccessToken)?{hasApiKey:!1,errorNotice:"GitHub Copilot is not authenticated. Please connect it in Settings > Copilot > Basic Tab > Set Keys."}:{hasApiKey:!0};let r=!!zte().find(i=>i===n),o=!Ad(t.provider,t);return r&&o?{hasApiKey:!1,errorNotice:`Please configure API Key for ${t.name} in settings first.
Path: Settings > copilot plugin > Basic Tab > Set Keys`}:{hasApiKey:!0}}function Kx(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>e.type==="text").map(e=>e.text??"").join(""):""}function jte(t){let n=Kx(t).replace(/<think>[\s\S]*?<\/think>/g,"");return n=n.replace(/<think>[\s\S]*$/g,""),n.trim()}function BAe(t){return Kx(t).replace(/<errorChunk>[\s\S]*?<\/errorChunk>/g,"").trim()}function zAe(){return crypto.randomUUID()}async function Nc(t){let e=console.warn;try{return console.warn=function(...n){let r=n[0];typeof r=="string"&&(r.includes("Failed to calculate number of tokens")||r.includes("Unknown model"))||e.apply(console,n)},await t()}finally{console.warn=e}}async function jAe(t,e,n="Operation"){let{TimeoutError:r}=await Promise.resolve().then(()=>(Nf(),zPe)),o=new AbortController,i=window.setTimeout(()=>{o.abort()},e);try{return await Promise.race([t(o.signal),new Promise((s,a)=>{o.signal.addEventListener("abort",()=>{a(new r(n,e))})})])}finally{window.clearTimeout(i)}}function t$(){let t=app.workspace.getActiveViewOfType(Kl.MarkdownView);return t?t.getState().source===!0:!0}function WS(t){return new TextEncoder().encode(t).length}function ZD(t,e){if(e<=0)return"";let n=new TextEncoder;if(n.encode(t).length<=e)return t;let o=0,i=t.length,s="";for(;o<=i;){let a=Math.floor((o+i)/2),l=t.substring(0,a);n.encode(l).length<=e?(s=l,o=a+1):i=a-1}return s}function Vte(t){let e=t.split("/"),n=e[e.length-1];if(WS(n)<=Dte)return t;let r=n.lastIndexOf("."),o=r>=0?n.substring(r):"",i=r>=0?n.substring(0,r):n,s=WS(o),a=Dte-s;return a<=0?e[e.length-1]=ZD(n,Dte):e[e.length-1]=ZD(i,a)+o,e.join("/")}async function VAe(t,e=!0){let n=null;app.workspace.iterateAllLeaves(r=>{if(r.view.getViewType()==="markdown"||r.view.getViewType()==="pdf"||r.view.getViewType()==="canvas"){let o=r.view.file;o&&o.path===t.path&&(n=r)}}),n&&e?app.workspace.setActiveLeaf(n,{focus:!0}):n||await app.workspace.getLeaf("tab").openFile(t)}var PAe,Kl,$te,JD,ll,gbt,Dte,qe=C(()=>{PAe=N(uD());Qi();It();ye();Lte();Kl=require("obsidian");VS();Wee();Hx();$te={INVALID_LICENSE_KEY_USER:"Invalid Copilot Plus license key. Please check your license key in settings.",UNKNOWN_ERROR:"An unknown error occurred",REQUEST_FAILED:t=>`Request failed, status ${t}`};JD=(t,e)=>{let n=t.getMarkdownFiles();if(e==="/")return n;let r=e.toLowerCase().replace(/^\/|\/$/g,"");return n.filter(o=>{let s=o.path.toLowerCase().split("/"),a=r.split("/"),l=0;for(let c of a){for(;l<s.length&&s[l]!==c;)l++;if(l>=s.length)return!1}return!0})};ll=(t,e="local")=>{let n=e==="utc"?hn.fromJSDate(t).toUTC():hn.fromJSDate(t);return{fileName:n.toFormat("yyyyMMdd_HHmmss"),display:n.toFormat("yyyy/MM/dd HH:mm:ss"),epoch:n.toMillis()}};gbt=/(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([^\s&]+)/;Dte=255});var WAe,Wte,Ds,HS=C(()=>{Wee();WAe=require("obsidian");qe();Se();Su();Wte=class t{constructor(){this.maxLines=500;this.maxLineChars=8e3;this.buffer=[];this.initialized=!1;this.flushing=!1}static getInstance(){return t.instance||(t.instance=new t),t.instance}getLogPath(){return"copilot/copilot-log.md"}async ensureInitialized(){this.initialized||(this.initialized=!0)}hasVault(){try{return typeof app<"u"&&!!app.vault?.adapter}catch{return!1}}sanitizeForSingleLine(e){if(e instanceof Error){let n=Xt(e,!0);return this.escapeAngleBrackets(this.collapseToSingleLine(n))}if(typeof e=="string")return this.escapeAngleBrackets(this.collapseToSingleLine(e));try{let n=JSON.stringify(e);return this.escapeAngleBrackets(this.collapseToSingleLine(n??String(e)))}catch{return this.escapeAngleBrackets(this.collapseToSingleLine(String(e)))}}collapseToSingleLine(e){let n=e.replace(/[\r\n]+/g,"\\n").replace(/\t/g," ");return n.length<=this.maxLineChars?n:n.slice(0,this.maxLineChars)+` \u2026 [truncated ${n.length-this.maxLineChars} chars]`}async append(e,...n){await this.ensureInitialized();let r=new Date().toISOString(),o=n.map(s=>this.sanitizeForSingleLine(s)),i=`${r} ${e} ${o.join(" ")}`.trim();this.buffer.push(i),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}escapeAngleBrackets(e){return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}async appendMarkdownBlock(e){if(await this.ensureInitialized(),!(!Array.isArray(e)||e.length===0))for(let n of e){let r=typeof n=="string"?n:String(n??"");this.buffer.push(r),this.buffer.length>this.maxLines&&this.buffer.splice(0,this.buffer.length-this.maxLines)}}async flush(){if(this.hasVault()&&!this.flushing){this.flushing=!0;try{let e=this.getLogPath();if(await app.vault.adapter.exists(e)){let n=this.buffer.join(`
`)+(this.buffer.length?`
`:"");await app.vault.adapter.write(e,n)}}catch{}finally{this.flushing=!1}}}async clear(){if(this.buffer=[],!!this.hasVault())try{let e=this.getLogPath();await app.vault.adapter.exists(e)&&await app.vault.adapter.remove(e)}catch{}}sanitizeSettingsForLog(){let e=q();return this.removeKeysRecursive(e)}removeKeysRecursive(e){if(e==null)return e;if(Array.isArray(e))return e.map(n=>this.removeKeysRecursive(n));if(typeof e=="object"&&e.constructor===Object){let n={},r=e;for(let[o,i]of Object.entries(r))Mx(o)||/orgId$/i.test(o)||/instanceName$/i.test(o)||/deploymentName$/i.test(o)||/apiVersion$/i.test(o)||(n[o]=this.removeKeysRecursive(i));return n}return e}async openLogFile(){if(!this.hasVault())return;let e=this.getLogPath(),n=[...this.buffer];try{let i=this.sanitizeSettingsForLog(),a=["","## Settings","```json",...JSON.stringify(i,null,2).split(`
`),"```"];n.push(...a)}catch{}try{let i=n.join(`
`)+(n.length?`
`:""),s=e.includes("/")?e.split("/").slice(0,-1).join("/"):"";s&&await Fr(s),await app.vault.adapter.exists(e)?await app.vault.adapter.write(e,i):await app.vault.create(e,i)}catch{}let r=app.vault.getAbstractFileByPath(e),o=r instanceof WAe.TFile?r:null;try{o&&await app.workspace.getLeaf(!0).openFile(o)}catch{}}},Ds=Wte.getInstance()});function k(...t){q().debug&&console.log(...t),Ds.append("INFO",...t)}function z(...t){q().debug&&console.error(...t),Ds.append("ERROR",...t)}function ee(...t){q().debug&&console.warn(...t),Ds.append("WARN",...t)}function jW(t){Ds.appendMarkdownBlock(t)}function HAe(t,e){if(q().debug)try{if(typeof console.table=="function"){Array.isArray(e)&&e.length>0?console.table(t,e):console.table(t);return}}catch{}k("Table:",JSON.stringify(t))}var ye=C(()=>{Se();HS()});function ZAe(t){Kn.set(WW,t)}function Iu(){return Kn.get(WW)}function JAe(t){return Kn.sub(WW,t)}function qx(){return Hy(WW,{store:Kn})}function ym(){return Kn.get(HW)}function XAe(t){Kn.set(HW,t)}function QAe(t){return Kn.sub(HW,t)}function kd(){return Hy(HW,{store:Kn})}function Gx(t){Kn.set(VW,t)}function br(){return Kn.get(VW)}function OA(t){return Kn.sub(VW,()=>{t(Kn.get(VW))})}function rg(t){Kn.set(YAe,t)}function KW(){return Hy(YAe,{store:Kn})}function RA(){return ym()==="project"}function og(t){Kn.set(Hte,t)}function wm(){return Kn.get(Hte)}function eke(t){let e=wm();og(e.filter(n=>n.id!==t))}function tke(){og([])}function nke(){return Hy(Hte,{store:Kn})}function rke(t){Kn.set(n$,t)}function ig(t,e){Kn.set(n$,n=>({...n,[t]:e(n[t])}))}function Yx(){return Hy(n$,{store:Kn})}function LA(){return Kn.get(r$)}function Kte(t){Kn.set(r$,t)}function ul(t){Kn.set(r$,e=>({...e,...t}))}function qte(){Ff!==null&&(window.clearTimeout(Ff),Ff=null),MA=0,NA=0,Kn.set(r$,{isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:[],completionStatus:"none"})}function oke(t){NA=t;let e=Date.now();e-MA>=GAe?(MA=e,Ff!==null&&(window.clearTimeout(Ff),Ff=null),ul({indexedCount:NA})):Ff===null&&(Ff=window.setTimeout(()=>{MA=Date.now(),Ff=null,ul({indexedCount:NA})},GAe-(e-MA)))}function ike(){Ff!==null&&(window.clearTimeout(Ff),Ff=null),ul({indexedCount:NA}),MA=0,NA=0}function DA(){return Hy(r$,{store:Kn})}var KAe,WW,qAe,HW,VW,YAe,n$,r$,Hte,MA,NA,Ff,GAe,Ir=C(()=>{Qi();Se();Id();KAe=Oo(null),WW=Oo(t=>{let e=t(KAe);return e!==null?e:t(Ox).defaultModelKey},(t,e,n)=>{e(KAe,n)}),qAe=Oo(null),HW=Oo(t=>{let e=t(qAe);return e!==null?e:t(Ox).defaultChainType},(t,e,n)=>{e(qAe,n)}),VW=Oo(null),YAe=Oo(!1),n$=Oo({success:[],failed:[],processingFiles:[],total:[]}),r$=Oo({isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:[],completionStatus:"none"}),Hte=Oo([]);MA=0,NA=0,Ff=null,GAe=500});function ske(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function ake(...t){return e=>{let n=!1,r=t.map(o=>{let i=ske(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():ske(t[o],null)}}}}var xbt,lke=C(()=>{xbt=N(U(),1)});var uke=Tt(qW=>{"use strict";var bbt=U(),Cbt=Symbol.for("react.element"),_bt=Symbol.for("react.fragment"),Sbt=Object.prototype.hasOwnProperty,Tbt=bbt.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,Ibt={key:!0,ref:!0,__self:!0,__source:!0};function cke(t,e,n){var r,o={},i=null,s=null;n!==void 0&&(i=""+n),e.key!==void 0&&(i=""+e.key),e.ref!==void 0&&(s=e.ref);for(r in e)Sbt.call(e,r)&&!Ibt.hasOwnProperty(r)&&(o[r]=e[r]);if(t&&t.defaultProps)for(r in e=t.defaultProps,e)o[r]===void 0&&(o[r]=e[r]);return{$$typeof:Cbt,type:t,key:i,ref:s,props:o,_owner:Tbt.current}}qW.Fragment=_bt;qW.jsx=cke;qW.jsxs=cke});var Ve=Tt((Wan,dke)=>{"use strict";dke.exports=uke()});function Ebt(t){return typeof t=="object"&&t!==null&&"then"in t}function fke(t){return t!=null&&typeof t=="object"&&"$$typeof"in t&&t.$$typeof===Pbt&&"_payload"in t&&Ebt(t._payload)}function Abt(t){let e=kbt(t),n=gs.forwardRef((r,o)=>{let{children:i,...s}=r;fke(i)&&typeof YW=="function"&&(i=YW(i._payload));let a=gs.Children.toArray(i),l=a.find(Nbt);if(l){let c=l.props.children,u=a.map(d=>d===l?gs.Children.count(c)>1?gs.Children.only(null):gs.isValidElement(c)?c.props.children:null:d);return(0,GW.jsx)(e,{...s,ref:o,children:gs.isValidElement(c)?gs.cloneElement(c,void 0,u):null})}return(0,GW.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function kbt(t){let e=gs.forwardRef((n,r)=>{let{children:o,...i}=n;if(fke(o)&&typeof YW=="function"&&(o=YW(o._payload)),gs.isValidElement(o)){let s=Rbt(o),a=Obt(i,o.props);return o.type!==gs.Fragment&&(a.ref=r?ake(r,s):s),gs.cloneElement(o,a)}return gs.Children.count(o)>1?gs.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}function Nbt(t){return gs.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Mbt}function Obt(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function Rbt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var gs,GW,Pbt,YW,pke,Mbt,mke=C(()=>{gs=N(U(),1);lke();GW=N(Ve(),1),Pbt=Symbol.for("react.lazy"),YW=gs[" use ".trim().toString()];pke=Abt("Slot");Mbt=Symbol("radix.slottable")});function hke(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var o=t.length;for(e=0;e<o;e++)t[e]&&(n=hke(t[e]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n);return r}function ZW(){for(var t,e,n=0,r="",o=arguments.length;n<o;n++)(t=arguments[n])&&(e=hke(t))&&(r&&(r+=" "),r+=e);return r}var Gte=C(()=>{});var gke,yke,$A,JW=C(()=>{Gte();gke=t=>typeof t=="boolean"?`${t}`:t===0?"0":t,yke=ZW,$A=(t,e)=>n=>{var r;if(e?.variants==null)return yke(t,n?.class,n?.className);let{variants:o,defaultVariants:i}=e,s=Object.keys(o).map(c=>{let u=n?.[c],d=i?.[c];if(u===null)return null;let f=gke(u)||gke(d);return o[c][f]}),a=n&&Object.entries(n).reduce((c,u)=>{let[d,f]=u;return f===void 0||(c[d]=f),c},{}),l=e==null||(r=e.compoundVariants)===null||r===void 0?void 0:r.reduce((c,u)=>{let{class:d,className:f,...p}=u;return Object.entries(p).every(m=>{let[h,g]=m;return Array.isArray(g)?g.includes({...i,...a}[h]):{...i,...a}[h]===g})?[...c,d,f]:c},[]);return yke(t,s,l,n?.class,n?.className)}});function Kbt(){let t=0,e,n,r="";for(;t<arguments.length;)(e=arguments[t++])&&(n=Ske(e))&&(r&&(r+=" "),r+=n);return r}function xke(t,...e){let n,r,o,i=s;function s(l){let c=e.reduce((u,d)=>d(u),t());return n=Vbt(c),r=n.cache.get,o=n.cache.set,i=a,a(l)}function a(l){let c=r(l);if(c)return c;let u=Hbt(l,n);return o(l,u),u}return function(){return i(Kbt.apply(null,arguments))}}var Jte,Lbt,Cke,wke,Dbt,$bt,Zte,vke,Fbt,Ubt,Bbt,_ke,zbt,jbt,Vbt,Wbt,Hbt,Ske,Ko,Tke,qbt,Gbt,Ybt,Zbt,Jbt,Xbt,Qbt,tw,Zx,FA,Yte,o$,eCt,er,Jx,tCt,nCt,rCt,oCt,iCt,sCt,i$,UA,aCt,Ike,lCt,cCt,bke,uCt,s$,dCt,fCt,Pke,Eke=C(()=>{Jte="-",Lbt=t=>{let e=$bt(t),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=t;return{getClassGroupId:s=>{let a=s.split(Jte);return a[0]===""&&a.length!==1&&a.shift(),Cke(a,e)||Dbt(s)},getConflictingClassGroupIds:(s,a)=>{let l=n[s]||[];return a&&r[s]?[...l,...r[s]]:l}}},Cke=(t,e)=>{if(t.length===0)return e.classGroupId;let n=t[0],r=e.nextPart.get(n),o=r?Cke(t.slice(1),r):void 0;if(o)return o;if(e.validators.length===0)return;let i=t.join(Jte);return e.validators.find(({validator:s})=>s(i))?.classGroupId},wke=/^\[(.+)\]$/,Dbt=t=>{if(wke.test(t)){let e=wke.exec(t)[1],n=e?.substring(0,e.indexOf(":"));if(n)return"arbitrary.."+n}},$bt=t=>{let{theme:e,prefix:n}=t,r={nextPart:new Map,validators:[]};return Ubt(Object.entries(t.classGroups),n).forEach(([i,s])=>{Zte(s,r,i,e)}),r},Zte=(t,e,n,r)=>{t.forEach(o=>{if(typeof o=="string"){let i=o===""?e:vke(e,o);i.classGroupId=n;return}if(typeof o=="function"){if(Fbt(o)){Zte(o(r),e,n,r);return}e.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Zte(s,vke(e,i),n,r)})})},vke=(t,e)=>{let n=t;return e.split(Jte).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},Fbt=t=>t.isThemeGetter,Ubt=(t,e)=>e?t.map(([n,r])=>{let o=r.map(i=>typeof i=="string"?e+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,a])=>[e+s,a])):i);return[n,o]}):t,Bbt=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,n=new Map,r=new Map,o=(i,s)=>{n.set(i,s),e++,e>t&&(e=0,r=n,n=new Map)};return{get(i){let s=n.get(i);if(s!==void 0)return s;if((s=r.get(i))!==void 0)return o(i,s),s},set(i,s){n.has(i)?n.set(i,s):o(i,s)}}},_ke="!",zbt=t=>{let{separator:e,experimentalParseClassName:n}=t,r=e.length===1,o=e[0],i=e.length,s=a=>{let l=[],c=0,u=0,d;for(let g=0;g<a.length;g++){let y=a[g];if(c===0){if(y===o&&(r||a.slice(g,g+i)===e)){l.push(a.slice(u,g)),u=g+i;continue}if(y==="/"){d=g;continue}}y==="["?c++:y==="]"&&c--}let f=l.length===0?a:a.substring(u),p=f.startsWith(_ke),m=p?f.substring(1):f,h=d&&d>u?d-u:void 0;return{modifiers:l,hasImportantModifier:p,baseClassName:m,maybePostfixModifierPosition:h}};return n?a=>n({className:a,parseClassName:s}):s},jbt=t=>{if(t.length<=1)return t;let e=[],n=[];return t.forEach(r=>{r[0]==="["?(e.push(...n.sort(),r),n=[]):n.push(r)}),e.push(...n.sort()),e},Vbt=t=>({cache:Bbt(t.cacheSize),parseClassName:zbt(t),...Lbt(t)}),Wbt=/\s+/,Hbt=(t,e)=>{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:o}=e,i=[],s=t.trim().split(Wbt),a="";for(let l=s.length-1;l>=0;l-=1){let c=s[l],{modifiers:u,hasImportantModifier:d,baseClassName:f,maybePostfixModifierPosition:p}=n(c),m=!!p,h=r(m?f.substring(0,p):f);if(!h){if(!m){a=c+(a.length>0?" "+a:a);continue}if(h=r(f),!h){a=c+(a.length>0?" "+a:a);continue}m=!1}let g=jbt(u).join(":"),y=d?g+_ke:g,w=y+h;if(i.includes(w))continue;i.push(w);let v=o(h,m);for(let x=0;x<v.length;++x){let b=v[x];i.push(y+b)}a=c+(a.length>0?" "+a:a)}return a};Ske=t=>{if(typeof t=="string")return t;let e,n="";for(let r=0;r<t.length;r++)t[r]&&(e=Ske(t[r]))&&(n&&(n+=" "),n+=e);return n};Ko=t=>{let e=n=>n[t]||[];return e.isThemeGetter=!0,e},Tke=/^\[(?:([a-z-]+):)?(.+)\]$/i,qbt=/^\d+\/\d+$/,Gbt=new Set(["px","full","screen"]),Ybt=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Zbt=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Jbt=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Xbt=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Qbt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,tw=t=>FA(t)||Gbt.has(t)||qbt.test(t),Zx=t=>UA(t,"length",aCt),FA=t=>!!t&&!Number.isNaN(Number(t)),Yte=t=>UA(t,"number",FA),o$=t=>!!t&&Number.isInteger(Number(t)),eCt=t=>t.endsWith("%")&&FA(t.slice(0,-1)),er=t=>Tke.test(t),Jx=t=>Ybt.test(t),tCt=new Set(["length","size","percentage"]),nCt=t=>UA(t,tCt,Ike),rCt=t=>UA(t,"position",Ike),oCt=new Set(["image","url"]),iCt=t=>UA(t,oCt,cCt),sCt=t=>UA(t,"",lCt),i$=()=>!0,UA=(t,e,n)=>{let r=Tke.exec(t);return r?r[1]?typeof e=="string"?r[1]===e:e.has(r[1]):n(r[2]):!1},aCt=t=>Zbt.test(t)&&!Jbt.test(t),Ike=()=>!1,lCt=t=>Xbt.test(t),cCt=t=>Qbt.test(t),bke=()=>{let t=Ko("colors"),e=Ko("spacing"),n=Ko("blur"),r=Ko("brightness"),o=Ko("borderColor"),i=Ko("borderRadius"),s=Ko("borderSpacing"),a=Ko("borderWidth"),l=Ko("contrast"),c=Ko("grayscale"),u=Ko("hueRotate"),d=Ko("invert"),f=Ko("gap"),p=Ko("gradientColorStops"),m=Ko("gradientColorStopPositions"),h=Ko("inset"),g=Ko("margin"),y=Ko("opacity"),w=Ko("padding"),v=Ko("saturate"),x=Ko("scale"),b=Ko("sepia"),_=Ko("skew"),T=Ko("space"),S=Ko("translate"),P=()=>["auto","contain","none"],A=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto",er,e],D=()=>[er,e],$=()=>["",tw,Zx],B=()=>["auto",FA,er],W=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],F=()=>["solid","dashed","dotted","double","none"],Z=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],V=()=>["start","end","center","between","around","evenly","stretch"],H=()=>["","0",er],te=()=>["auto","avoid","all","avoid-page","page","left","right","column"],fe=()=>[FA,er];return{cacheSize:500,separator:":",theme:{colors:[i$],spacing:[tw,Zx],blur:["none","",Jx,er],brightness:fe(),borderColor:[t],borderRadius:["none","","full",Jx,er],borderSpacing:D(),borderWidth:$(),contrast:fe(),grayscale:H(),hueRotate:fe(),invert:H(),gap:D(),gradientColorStops:[t],gradientColorStopPositions:[eCt,Zx],inset:O(),margin:O(),opacity:fe(),padding:D(),saturate:fe(),scale:fe(),sepia:H(),skew:fe(),space:D(),translate:D()},classGroups:{aspect:[{aspect:["auto","square","video",er]}],container:["container"],columns:[{columns:[Jx]}],"break-after":[{"break-after":te()}],"break-before":[{"break-before":te()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...W(),er]}],overflow:[{overflow:A()}],"overflow-x":[{"overflow-x":A()}],"overflow-y":[{"overflow-y":A()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[h]}],"inset-x":[{"inset-x":[h]}],"inset-y":[{"inset-y":[h]}],start:[{start:[h]}],end:[{end:[h]}],top:[{top:[h]}],right:[{right:[h]}],bottom:[{bottom:[h]}],left:[{left:[h]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",o$,er]}],basis:[{basis:O()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",er]}],grow:[{grow:H()}],shrink:[{shrink:H()}],order:[{order:["first","last","none",o$,er]}],"grid-cols":[{"grid-cols":[i$]}],"col-start-end":[{col:["auto",{span:["full",o$,er]},er]}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":[i$]}],"row-start-end":[{row:["auto",{span:[o$,er]},er]}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",er]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",er]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...V()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...V(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...V(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[w]}],px:[{px:[w]}],py:[{py:[w]}],ps:[{ps:[w]}],pe:[{pe:[w]}],pt:[{pt:[w]}],pr:[{pr:[w]}],pb:[{pb:[w]}],pl:[{pl:[w]}],m:[{m:[g]}],mx:[{mx:[g]}],my:[{my:[g]}],ms:[{ms:[g]}],me:[{me:[g]}],mt:[{mt:[g]}],mr:[{mr:[g]}],mb:[{mb:[g]}],ml:[{ml:[g]}],"space-x":[{"space-x":[T]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[T]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",er,e]}],"min-w":[{"min-w":[er,e,"min","max","fit"]}],"max-w":[{"max-w":[er,e,"none","full","min","max","fit","prose",{screen:[Jx]},Jx]}],h:[{h:[er,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[er,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[er,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[er,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Jx,Zx]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Yte]}],"font-family":[{font:[i$]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",er]}],"line-clamp":[{"line-clamp":["none",FA,Yte]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",tw,er]}],"list-image":[{"list-image":["none",er]}],"list-style-type":[{list:["none","disc","decimal",er]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...F(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",tw,Zx]}],"underline-offset":[{"underline-offset":["auto",tw,er]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:D()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",er]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",er]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...W(),rCt]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",nCt]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},iCt]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[m]}],"gradient-via-pos":[{via:[m]}],"gradient-to-pos":[{to:[m]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...F(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}],"divide-style":[{divide:F()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[o]}],"border-color-s":[{"border-s":[o]}],"border-color-e":[{"border-e":[o]}],"border-color-t":[{"border-t":[o]}],"border-color-r":[{"border-r":[o]}],"border-color-b":[{"border-b":[o]}],"border-color-l":[{"border-l":[o]}],"divide-color":[{divide:[o]}],"outline-style":[{outline:["",...F()]}],"outline-offset":[{"outline-offset":[tw,er]}],"outline-w":[{outline:[tw,Zx]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:$()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[tw,Zx]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",Jx,sCt]}],"shadow-color":[{shadow:[i$]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...Z(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":Z()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",Jx,er]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[d]}],saturate:[{saturate:[v]}],sepia:[{sepia:[b]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[d]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[v]}],"backdrop-sepia":[{"backdrop-sepia":[b]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[s]}],"border-spacing-x":[{"border-spacing-x":[s]}],"border-spacing-y":[{"border-spacing-y":[s]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",er]}],duration:[{duration:fe()}],ease:[{ease:["linear","in","out","in-out",er]}],delay:[{delay:fe()}],animate:[{animate:["none","spin","ping","pulse","bounce",er]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[x]}],"scale-x":[{"scale-x":[x]}],"scale-y":[{"scale-y":[x]}],rotate:[{rotate:[o$,er]}],"translate-x":[{"translate-x":[S]}],"translate-y":[{"translate-y":[S]}],"skew-x":[{"skew-x":[_]}],"skew-y":[{"skew-y":[_]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",er]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",er]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":D()}],"scroll-mx":[{"scroll-mx":D()}],"scroll-my":[{"scroll-my":D()}],"scroll-ms":[{"scroll-ms":D()}],"scroll-me":[{"scroll-me":D()}],"scroll-mt":[{"scroll-mt":D()}],"scroll-mr":[{"scroll-mr":D()}],"scroll-mb":[{"scroll-mb":D()}],"scroll-ml":[{"scroll-ml":D()}],"scroll-p":[{"scroll-p":D()}],"scroll-px":[{"scroll-px":D()}],"scroll-py":[{"scroll-py":D()}],"scroll-ps":[{"scroll-ps":D()}],"scroll-pe":[{"scroll-pe":D()}],"scroll-pt":[{"scroll-pt":D()}],"scroll-pr":[{"scroll-pr":D()}],"scroll-pb":[{"scroll-pb":D()}],"scroll-pl":[{"scroll-pl":D()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",er]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[tw,Zx,Yte]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},uCt=(t,{cacheSize:e,prefix:n,separator:r,experimentalParseClassName:o,extend:i={},override:s={}})=>{s$(t,"cacheSize",e),s$(t,"prefix",n),s$(t,"separator",r),s$(t,"experimentalParseClassName",o);for(let a in s)dCt(t[a],s[a]);for(let a in i)fCt(t[a],i[a]);return t},s$=(t,e,n)=>{n!==void 0&&(t[e]=n)},dCt=(t,e)=>{if(e)for(let n in e)s$(t,n,e[n])},fCt=(t,e)=>{if(e)for(let n in e){let r=e[n];r!==void 0&&(t[n]=(t[n]||[]).concat(r))}},Pke=(t,...e)=>typeof t=="function"?xke(bke,t,...e):xke(()=>uCt(bke(),t),...e)});function oe(...t){return pCt(ZW(t))}var pCt,Kt=C(()=>{Gte();Eke();pCt=Pke({prefix:"tw-",extend:{classGroups:{"text-color":["text-muted","text-success","text-warning","text-error","text-accent"],"font-size":["text-smallest","text-smaller","text-small","text-ui-smaller","text-ui-small","text-ui-medium","text-ui-larger"]}}})});var XW,mCt,X,rn=C(()=>{XW=N(U());mke();JW();Kt();mCt=$A("tw-inline-flex tw-items-center tw-justify-center tw-gap-1 tw-whitespace-nowrap tw-rounded-md tw-text-sm tw-font-medium tw-transition-colors focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-pointer-events-none disabled:tw-opacity-50 [&_svg]:tw-shrink-0",{variants:{variant:{default:"mod-cta tw-bg-interactive-accent tw-text-on-accent tw-shadow hover:tw-bg-interactive-accent-hover",destructive:"clickable-icon tw-bg-modifier-error tw-text-on-accent hover:tw-bg-modifier-error hover:tw-text-on-accent",secondary:"tw-bg-secondary tw-text-normal tw-shadow-sm hover:tw-bg-interactive-hover",ghost:"clickable-icon tw-bg-transparent hover:tw-bg-interactive-accent hover:tw-text-on-accent",link:"tw-text-accent tw-underline-offset-4 hover:tw-underline",success:"clickable-icon tw-bg-modifier-success tw-text-on-accent hover:tw-bg-modifier-success hover:tw-text-on-accent",ghost2:"clickable-icon tw-bg-transparent tw-text-faint tw-outline-none hover:tw-bg-transparent hover:tw-bg-opacity-100 hover:tw-text-normal focus-visible:tw-text-normal focus-visible:tw-outline-none focus-visible:tw-ring-0"},size:{default:"tw-h-9 tw-px-4 tw-py-2",sm:"tw-h-6 tw-rounded-md tw-px-3 tw-text-xs",lg:"tw-h-10 tw-rounded-md tw-px-8",icon:"tw-size-7",fit:"tw-gap-1 tw-px-1 tw-text-xs"}},defaultVariants:{variant:"default",size:"default"}}),X=XW.forwardRef(({className:t,variant:e,size:n,asChild:r=!1,...o},i)=>XW.createElement(r?pke:"button",{className:oe(mCt({variant:e,size:n,className:t})),ref:i,...o}));X.displayName="Button"});var Ake,QW,Xte=C(()=>{Ake=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),QW=(...t)=>t.filter((e,n,r)=>!!e&&e.trim()!==""&&r.indexOf(e)===n).join(" ").trim()});var kke,Mke=C(()=>{kke={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"}});var a$,Nke,Oke=C(()=>{a$=N(U());Mke();Xte();Nke=(0,a$.forwardRef)(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:o="",children:i,iconNode:s,...a},l)=>(0,a$.createElement)("svg",{ref:l,...kke,width:e,height:e,stroke:t,strokeWidth:r?Number(n)*24/Number(e):n,className:QW("lucide",o),...a},[...s.map(([c,u])=>(0,a$.createElement)(c,u)),...Array.isArray(i)?i:[i]]))});var eH,ie,je=C(()=>{eH=N(U());Xte();Oke();ie=(t,e)=>{let n=(0,eH.forwardRef)(({className:r,...o},i)=>(0,eH.createElement)(Nke,{ref:i,iconNode:e,className:QW(`lucide-${Ake(t)}`,r),...o}));return n.displayName=`${t}`,n}});var BA,Rke=C(()=>{je();BA=ie("ArrowBigUp",[["path",{d:"M9 18v-6H5l7-7 7 7h-4v6H9z",key:"1x06kx"}]])});var l$,Lke=C(()=>{je();l$=ie("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]])});var Oc,Dke=C(()=>{je();Oc=ie("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]])});var c$,$ke=C(()=>{je();c$=ie("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]])});var zA,Fke=C(()=>{je();zA=ie("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]])});var Ro,Uke=C(()=>{je();Ro=ie("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]])});var hr,Bke=C(()=>{je();hr=ie("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]])});var Di,zke=C(()=>{je();Di=ie("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]])});var $s,jke=C(()=>{je();$s=ie("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]])});var Fs,Vke=C(()=>{je();Fs=ie("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]])});var Pu,Wke=C(()=>{je();Pu=ie("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]])});var vm,Hke=C(()=>{je();vm=ie("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]])});var nw,Kke=C(()=>{je();nw=ie("CircleDashed",[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]])});var Uf,qke=C(()=>{je();Uf=ie("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]])});var Md,Gke=C(()=>{je();Md=ie("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]])});var Xx,Yke=C(()=>{je();Xx=ie("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]])});var sg,Zke=C(()=>{je();sg=ie("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]])});var u$,Jke=C(()=>{je();u$=ie("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]])});var KS,Xke=C(()=>{je();KS=ie("ClipboardPaste",[["path",{d:"M15 2H9a1 1 0 0 0-1 1v2c0 .6.4 1 1 1h6c.6 0 1-.4 1-1V3c0-.6-.4-1-1-1Z",key:"1pp7kr"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2M16 4h2a2 2 0 0 1 2 2v2M11 14h10",key:"2ik1ml"}],["path",{d:"m17 10 4 4-4 4",key:"vp2hj1"}]])});var jA,Qke=C(()=>{je();jA=ie("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]])});var d$,eMe=C(()=>{je();d$=ie("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]])});var f$,tMe=C(()=>{je();f$=ie("Coins",[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]])});var Qx,nMe=C(()=>{je();Qx=ie("Command",[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]])});var VA,rMe=C(()=>{je();VA=ie("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]])});var Eu,oMe=C(()=>{je();Eu=ie("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]])});var ag,iMe=C(()=>{je();ag=ie("CornerDownLeft",[["polyline",{points:"9 10 4 15 9 20",key:"r3jprv"}],["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}]])});var p$,sMe=C(()=>{je();p$=ie("Cpu",[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]])});var xm,aMe=C(()=>{je();xm=ie("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]])});var m$,lMe=C(()=>{je();m$=ie("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]])});var lg,cMe=C(()=>{je();lg=ie("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]])});var eb,uMe=C(()=>{je();eb=ie("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]])});var rw,dMe=C(()=>{je();rw=ie("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]])});var h$,fMe=C(()=>{je();h$=ie("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]])});var ow,pMe=C(()=>{je();ow=ie("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]])});var g$,mMe=C(()=>{je();g$=ie("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]])});var iw,hMe=C(()=>{je();iw=ie("FileClock",[["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"37hlfg"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"8",cy:"16",r:"6",key:"10v15b"}],["path",{d:"M9.5 17.5 8 16.25V14",key:"1o80t2"}]])});var qS,gMe=C(()=>{je();qS=ie("FileImage",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]])});var y$,yMe=C(()=>{je();y$=ie("FileInput",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]])});var w$,wMe=C(()=>{je();w$=ie("FileOutput",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 7V4a2 2 0 0 1 2-2 2 2 0 0 0-2 2",key:"1vk7w2"}],["path",{d:"M4.063 20.999a2 2 0 0 0 2 1L18 22a2 2 0 0 0 2-2V7l-5-5H6",key:"1jink5"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]])});var Ur,vMe=C(()=>{je();Ur=ie("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]])});var GS,xMe=C(()=>{je();GS=ie("FileVideo",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]])});var v$,bMe=C(()=>{je();v$=ie("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]])});var es,CMe=C(()=>{je();es=ie("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]])});var Br,_Me=C(()=>{je();Br=ie("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]])});var bm,SMe=C(()=>{je();bm=ie("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]])});var cg,TMe=C(()=>{je();cg=ie("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]])});var x$,IMe=C(()=>{je();x$=ie("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]])});var b$,PMe=C(()=>{je();b$=ie("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]])});var ug,EMe=C(()=>{je();ug=ie("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]])});var C$,AMe=C(()=>{je();C$=ie("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]])});var YS,kMe=C(()=>{je();YS=ie("LibraryBig",[["rect",{width:"8",height:"18",x:"3",y:"3",rx:"1",key:"oynpb5"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",key:"1qboyk"}]])});var Cm,MMe=C(()=>{je();Cm=ie("Lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]])});var _$,NMe=C(()=>{je();_$=ie("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]])});var Pr,OMe=C(()=>{je();Pr=ie("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]])});var tb,RMe=C(()=>{je();tb=ie("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]])});var S$,LMe=C(()=>{je();S$=ie("MessageCirclePlus",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]])});var WA,DMe=C(()=>{je();WA=ie("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]])});var T$,$Me=C(()=>{je();T$=ie("MessageSquareX",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]])});var HA,FMe=C(()=>{je();HA=ie("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]])});var KA,UMe=C(()=>{je();KA=ie("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]])});var Bf,BMe=C(()=>{je();Bf=ie("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]])});var Rc,zMe=C(()=>{je();Rc=ie("Pen",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]])});var nb,jMe=C(()=>{je();nb=ie("PencilLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}],["path",{d:"m15 5 3 3",key:"1w25hb"}]])});var rb,VMe=C(()=>{je();rb=ie("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]])});var I$,WMe=C(()=>{je();I$=ie("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]])});var Lc,HMe=C(()=>{je();Lc=ie("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]])});var P$,KMe=C(()=>{je();P$=ie("RefreshCcw",[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]])});var zf,qMe=C(()=>{je();zf=ie("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]])});var E$,GMe=C(()=>{je();E$=ie("Replace",[["path",{d:"M14 4a2 2 0 0 1 2-2",key:"1w2hp7"}],["path",{d:"M16 10a2 2 0 0 1-2-2",key:"shjach"}],["path",{d:"M20 2a2 2 0 0 1 2 2",key:"188mtx"}],["path",{d:"M22 8a2 2 0 0 1-2 2",key:"ddf4tu"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a3 3 0 0 1 3-3h1",key:"3y3t5z"}],["rect",{x:"2",y:"14",width:"8",height:"8",rx:"2",key:"4rksxw"}]])});var A$,YMe=C(()=>{je();A$=ie("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]])});var k$,ZMe=C(()=>{je();k$=ie("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]])});var ZS,JMe=C(()=>{je();ZS=ie("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]])});var JS,XMe=C(()=>{je();JS=ie("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]])});var XS,QMe=C(()=>{je();XS=ie("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]])});var sw,eNe=C(()=>{je();sw=ie("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]])});var M$,tNe=C(()=>{je();M$=ie("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]])});var ql,nNe=C(()=>{je();ql=ie("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]])});var aw,rNe=C(()=>{je();aw=ie("SquareArrowOutUpRight",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]])});var Au,oNe=C(()=>{je();Au=ie("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]])});var QS,iNe=C(()=>{je();QS=ie("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]])});var _m,sNe=C(()=>{je();_m=ie("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]])});var N$,aNe=C(()=>{je();N$=ie("TextCursorInput",[["path",{d:"M5 4h1a3 3 0 0 1 3 3 3 3 0 0 1 3-3h1",key:"18xjzo"}],["path",{d:"M13 20h-1a3 3 0 0 1-3-3 3 3 0 0 1-3 3H5",key:"fj48gi"}],["path",{d:"M5 16H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h1",key:"1n9rhb"}],["path",{d:"M13 8h7a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-7",key:"13ksps"}],["path",{d:"M9 7v10",key:"1vc8ob"}]])});var ka,lNe=C(()=>{je();ka=ie("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]])});var dl,cNe=C(()=>{je();dl=ie("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]])});var Nd,uNe=C(()=>{je();Nd=ie("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]])});var Sn,dNe=C(()=>{je();Sn=ie("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]])});var O$,fNe=C(()=>{je();O$=ie("ZapOff",[["path",{d:"M10.513 4.856 13.12 2.17a.5.5 0 0 1 .86.46l-1.377 4.317",key:"193nxd"}],["path",{d:"M15.656 10H20a1 1 0 0 1 .78 1.63l-1.72 1.773",key:"27a7lr"}],["path",{d:"M16.273 16.273 10.88 21.83a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14H4a1 1 0 0 1-.78-1.63l4.507-4.643",key:"1e0qe9"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]])});var R$,pNe=C(()=>{je();R$=ie("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]])});var vt=C(()=>{Vke();Wke();Hke();qke();Gke();Yke();Zke();cMe();uMe();OMe();RMe();BMe();zMe();nNe();rNe();oNe();cNe();Rke();Lke();Dke();$ke();Fke();Uke();Bke();zke();jke();Kke();Jke();Xke();Qke();eMe();tMe();nMe();rMe();oMe();iMe();sMe();aMe();lMe();dMe();fMe();pMe();mMe();hMe();gMe();yMe();wMe();vMe();xMe();bMe();CMe();_Me();SMe();TMe();IMe();PMe();EMe();AMe();kMe();MMe();NMe();LMe();DMe();$Me();FMe();UMe();jMe();VMe();WMe();HMe();KMe();qMe();GMe();YMe();ZMe();JMe();XMe();QMe();eNe();tNe();iNe();sNe();aNe();lNe();uNe();dNe();fNe();pNe();});function tr(){let t=L$.useContext(D$);if(!t)throw new Error("useApp() called outside of an <AppContext.Provider>");return t}var L$,D$,qA,bi=C(()=>{L$=N(U()),D$=L$.createContext(void 0),qA=L$.createContext(void 0)});var _Ne=Tt(Lo=>{"use strict";function nne(t,e){var n=t.length;t.push(e);e:for(;0<n;){var r=n-1>>>1,o=t[r];if(0<tH(o,e))t[r]=e,t[n]=o,n=r;else break e}}function Sm(t){return t.length===0?null:t[0]}function rH(t){if(t.length===0)return null;var e=t[0],n=t.pop();if(n!==e){t[0]=n;e:for(var r=0,o=t.length,i=o>>>1;r<i;){var s=2*(r+1)-1,a=t[s],l=s+1,c=t[l];if(0>tH(a,n))l<o&&0>tH(c,a)?(t[r]=c,t[l]=n,r=l):(t[r]=a,t[s]=n,r=s);else if(l<o&&0>tH(c,n))t[r]=c,t[l]=n,r=l;else break e}}return e}function tH(t,e){var n=t.sortIndex-e.sortIndex;return n!==0?n:t.id-e.id}typeof performance=="object"&&typeof performance.now=="function"?(mNe=performance,Lo.unstable_now=function(){return mNe.now()}):(Qte=Date,hNe=Qte.now(),Lo.unstable_now=function(){return Qte.now()-hNe});var mNe,Qte,hNe,dg=[],ob=[],hCt=1,jf=null,Gl=3,oH=!1,eT=!1,F$=!1,wNe=typeof setTimeout=="function"?setTimeout:null,vNe=typeof clearTimeout=="function"?clearTimeout:null,gNe=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function rne(t){for(var e=Sm(ob);e!==null;){if(e.callback===null)rH(ob);else if(e.startTime<=t)rH(ob),e.sortIndex=e.expirationTime,nne(dg,e);else break;e=Sm(ob)}}function one(t){if(F$=!1,rne(t),!eT)if(Sm(dg)!==null)eT=!0,sne(ine);else{var e=Sm(ob);e!==null&&ane(one,e.startTime-t)}}function ine(t,e){eT=!1,F$&&(F$=!1,vNe(U$),U$=-1),oH=!0;var n=Gl;try{for(rne(e),jf=Sm(dg);jf!==null&&(!(jf.expirationTime>e)||t&&!CNe());){var r=jf.callback;if(typeof r=="function"){jf.callback=null,Gl=jf.priorityLevel;var o=r(jf.expirationTime<=e);e=Lo.unstable_now(),typeof o=="function"?jf.callback=o:jf===Sm(dg)&&rH(dg),rne(e)}else rH(dg);jf=Sm(dg)}if(jf!==null)var i=!0;else{var s=Sm(ob);s!==null&&ane(one,s.startTime-e),i=!1}return i}finally{jf=null,Gl=n,oH=!1}}var iH=!1,nH=null,U$=-1,xNe=5,bNe=-1;function CNe(){return!(Lo.unstable_now()-bNe<xNe)}function ene(){if(nH!==null){var t=Lo.unstable_now();bNe=t;var e=!0;try{e=nH(!0,t)}finally{e?$$():(iH=!1,nH=null)}}else iH=!1}var $$;typeof gNe=="function"?$$=function(){gNe(ene)}:typeof MessageChannel<"u"?(tne=new MessageChannel,yNe=tne.port2,tne.port1.onmessage=ene,$$=function(){yNe.postMessage(null)}):$$=function(){wNe(ene,0)};var tne,yNe;function sne(t){nH=t,iH||(iH=!0,$$())}function ane(t,e){U$=wNe(function(){t(Lo.unstable_now())},e)}Lo.unstable_IdlePriority=5;Lo.unstable_ImmediatePriority=1;Lo.unstable_LowPriority=4;Lo.unstable_NormalPriority=3;Lo.unstable_Profiling=null;Lo.unstable_UserBlockingPriority=2;Lo.unstable_cancelCallback=function(t){t.callback=null};Lo.unstable_continueExecution=function(){eT||oH||(eT=!0,sne(ine))};Lo.unstable_forceFrameRate=function(t){0>t||125<t?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):xNe=0<t?Math.floor(1e3/t):5};Lo.unstable_getCurrentPriorityLevel=function(){return Gl};Lo.unstable_getFirstCallbackNode=function(){return Sm(dg)};Lo.unstable_next=function(t){switch(Gl){case 1:case 2:case 3:var e=3;break;default:e=Gl}var n=Gl;Gl=e;try{return t()}finally{Gl=n}};Lo.unstable_pauseExecution=function(){};Lo.unstable_requestPaint=function(){};Lo.unstable_runWithPriority=function(t,e){switch(t){case 1:case 2:case 3:case 4:case 5:break;default:t=3}var n=Gl;Gl=t;try{return e()}finally{Gl=n}};Lo.unstable_scheduleCallback=function(t,e,n){var r=Lo.unstable_now();switch(typeof n=="object"&&n!==null?(n=n.delay,n=typeof n=="number"&&0<n?r+n:r):n=r,t){case 1:var o=-1;break;case 2:o=250;break;case 5:o=1073741823;break;case 4:o=1e4;break;default:o=5e3}return o=n+o,t={id:hCt++,callback:e,priorityLevel:t,startTime:n,expirationTime:o,sortIndex:-1},n>r?(t.sortIndex=n,nne(ob,t),Sm(dg)===null&&t===Sm(ob)&&(F$?(vNe(U$),U$=-1):F$=!0,ane(one,n-r))):(t.sortIndex=o,nne(dg,t),eT||oH||(eT=!0,sne(ine))),t};Lo.unstable_shouldYield=CNe;Lo.unstable_wrapCallback=function(t){var e=Gl;return function(){var n=Gl;Gl=e;try{return t.apply(this,arguments)}finally{Gl=n}}}});var TNe=Tt((upn,SNe)=>{"use strict";SNe.exports=_Ne()});var MLe=Tt(Fd=>{"use strict";var NOe=U(),Dd=TNe();function Be(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,n=1;n<arguments.length;n++)e+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+t+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var OOe=new Set,aF={};function pT(t,e){mk(t,e),mk(t+"Capture",e)}function mk(t,e){for(aF[t]=e,t=0;t<e.length;t++)OOe.add(e[t])}var pw=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),kne=Object.prototype.hasOwnProperty,gCt=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,INe={},PNe={};function yCt(t){return kne.call(PNe,t)?!0:kne.call(INe,t)?!1:gCt.test(t)?PNe[t]=!0:(INe[t]=!0,!1)}function wCt(t,e,n,r){if(n!==null&&n.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function vCt(t,e,n,r){if(e===null||typeof e>"u"||wCt(t,e,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function Fc(t,e,n,r,o,i,s){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=t,this.type=e,this.sanitizeURL=i,this.removeEmptyString=s}var ml={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){ml[t]=new Fc(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];ml[e]=new Fc(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){ml[t]=new Fc(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){ml[t]=new Fc(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){ml[t]=new Fc(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){ml[t]=new Fc(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){ml[t]=new Fc(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){ml[t]=new Fc(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){ml[t]=new Fc(t,5,!1,t.toLowerCase(),null,!1,!1)});var Cre=/[\-:]([a-z])/g;function _re(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(Cre,_re);ml[e]=new Fc(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(Cre,_re);ml[e]=new Fc(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(Cre,_re);ml[e]=new Fc(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){ml[t]=new Fc(t,1,!1,t.toLowerCase(),null,!1,!1)});ml.xlinkHref=new Fc("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){ml[t]=new Fc(t,1,!1,t.toLowerCase(),null,!0,!0)});function Sre(t,e,n,r){var o=ml.hasOwnProperty(e)?ml[e]:null;(o!==null?o.type!==0:r||!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&(vCt(e,n,o,r)&&(n=null),r||o===null?yCt(e)&&(n===null?t.removeAttribute(e):t.setAttribute(e,""+n)):o.mustUseProperty?t[o.propertyName]=n===null?o.type===3?!1:"":n:(e=o.attributeName,r=o.attributeNamespace,n===null?t.removeAttribute(e):(o=o.type,n=o===3||o===4&&n===!0?"":""+n,r?t.setAttributeNS(r,e,n):t.setAttribute(e,n))))}var yw=NOe.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,sH=Symbol.for("react.element"),ZA=Symbol.for("react.portal"),JA=Symbol.for("react.fragment"),Tre=Symbol.for("react.strict_mode"),Mne=Symbol.for("react.profiler"),ROe=Symbol.for("react.provider"),LOe=Symbol.for("react.context"),Ire=Symbol.for("react.forward_ref"),Nne=Symbol.for("react.suspense"),One=Symbol.for("react.suspense_list"),Pre=Symbol.for("react.memo"),sb=Symbol.for("react.lazy");Symbol.for("react.scope");Symbol.for("react.debug_trace_mode");var DOe=Symbol.for("react.offscreen");Symbol.for("react.legacy_hidden");Symbol.for("react.cache");Symbol.for("react.tracing_marker");var ENe=Symbol.iterator;function B$(t){return t===null||typeof t!="object"?null:(t=ENe&&t[ENe]||t["@@iterator"],typeof t=="function"?t:null)}var Si=Object.assign,lne;function G$(t){if(lne===void 0)try{throw Error()}catch(n){var e=n.stack.trim().match(/\n( *(at )?)/);lne=e&&e[1]||""}return`
`+lne+t}var cne=!1;function une(t,e){if(!t||cne)return"";cne=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(c){var r=c}Reflect.construct(t,[],e)}else{try{e.call()}catch(c){r=c}t.call(e.prototype)}else{try{throw Error()}catch(c){r=c}t()}}catch(c){if(c&&r&&typeof c.stack=="string"){for(var o=c.stack.split(`
`),i=r.stack.split(`
`),s=o.length-1,a=i.length-1;1<=s&&0<=a&&o[s]!==i[a];)a--;for(;1<=s&&0<=a;s--,a--)if(o[s]!==i[a]){if(s!==1||a!==1)do if(s--,a--,0>a||o[s]!==i[a]){var l=`
`+o[s].replace(" at new "," at ");return t.displayName&&l.includes("<anonymous>")&&(l=l.replace("<anonymous>",t.displayName)),l}while(1<=s&&0<=a);break}}}finally{cne=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?G$(t):""}function xCt(t){switch(t.tag){case 5:return G$(t.type);case 16:return G$("Lazy");case 13:return G$("Suspense");case 19:return G$("SuspenseList");case 0:case 2:case 15:return t=une(t.type,!1),t;case 11:return t=une(t.type.render,!1),t;case 1:return t=une(t.type,!0),t;default:return""}}function Rne(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case JA:return"Fragment";case ZA:return"Portal";case Mne:return"Profiler";case Tre:return"StrictMode";case Nne:return"Suspense";case One:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case LOe:return(t.displayName||"Context")+".Consumer";case ROe:return(t._context.displayName||"Context")+".Provider";case Ire:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case Pre:return e=t.displayName||null,e!==null?e:Rne(t.type)||"Memo";case sb:e=t._payload,t=t._init;try{return Rne(t(e))}catch{}}return null}function bCt(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Rne(e);case 8:return e===Tre?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function xb(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function $Oe(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function CCt(t){var e=$Oe(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function aH(t){t._valueTracker||(t._valueTracker=CCt(t))}function FOe(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=$Oe(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function LH(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function Lne(t,e){var n=e.checked;return Si({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function ANe(t,e){var n=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;n=xb(e.value!=null?e.value:n),t._wrapperState={initialChecked:r,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function UOe(t,e){e=e.checked,e!=null&&Sre(t,"checked",e,!1)}function Dne(t,e){UOe(t,e);var n=xb(e.value),r=e.type;if(n!=null)r==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(r==="submit"||r==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?$ne(t,e.type,n):e.hasOwnProperty("defaultValue")&&$ne(t,e.type,xb(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function kNe(t,e,n){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,n||e===t.value||(t.value=e),t.defaultValue=e}n=t.name,n!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,n!==""&&(t.name=n)}function $ne(t,e,n){(e!=="number"||LH(t.ownerDocument)!==t)&&(n==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+n&&(t.defaultValue=""+n))}var Y$=Array.isArray;function lk(t,e,n,r){if(t=t.options,e){e={};for(var o=0;o<n.length;o++)e["$"+n[o]]=!0;for(n=0;n<t.length;n++)o=e.hasOwnProperty("$"+t[n].value),t[n].selected!==o&&(t[n].selected=o),o&&r&&(t[n].defaultSelected=!0)}else{for(n=""+xb(n),e=null,o=0;o<t.length;o++){if(t[o].value===n){t[o].selected=!0,r&&(t[o].defaultSelected=!0);return}e!==null||t[o].disabled||(e=t[o])}e!==null&&(e.selected=!0)}}function Fne(t,e){if(e.dangerouslySetInnerHTML!=null)throw Error(Be(91));return Si({},e,{value:void 0,defaultValue:void 0,children:""+t._wrapperState.initialValue})}function MNe(t,e){var n=e.value;if(n==null){if(n=e.children,e=e.defaultValue,n!=null){if(e!=null)throw Error(Be(92));if(Y$(n)){if(1<n.length)throw Error(Be(93));n=n[0]}e=n}e==null&&(e=""),n=e}t._wrapperState={initialValue:xb(n)}}function BOe(t,e){var n=xb(e.value),r=xb(e.defaultValue);n!=null&&(n=""+n,n!==t.value&&(t.value=n),e.defaultValue==null&&t.defaultValue!==n&&(t.defaultValue=n)),r!=null&&(t.defaultValue=""+r)}function NNe(t){var e=t.textContent;e===t._wrapperState.initialValue&&e!==""&&e!==null&&(t.value=e)}function zOe(t){switch(t){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Une(t,e){return t==null||t==="http://www.w3.org/1999/xhtml"?zOe(e):t==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":t}var lH,jOe=function(t){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(e,n,r,o){MSApp.execUnsafeLocalFunction(function(){return t(e,n,r,o)})}:t}(function(t,e){if(t.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in t)t.innerHTML=e;else{for(lH=lH||document.createElement("div"),lH.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=lH.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function lF(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var X$={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},_Ct=["Webkit","ms","Moz","O"];Object.keys(X$).forEach(function(t){_Ct.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),X$[e]=X$[t]})});function VOe(t,e,n){return e==null||typeof e=="boolean"||e===""?"":n||typeof e!="number"||e===0||X$.hasOwnProperty(t)&&X$[t]?(""+e).trim():e+"px"}function WOe(t,e){t=t.style;for(var n in e)if(e.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=VOe(n,e[n],r);n==="float"&&(n="cssFloat"),r?t.setProperty(n,o):t[n]=o}}var SCt=Si({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function Bne(t,e){if(e){if(SCt[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(Be(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(Be(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(Be(61))}if(e.style!=null&&typeof e.style!="object")throw Error(Be(62))}}function zne(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var jne=null;function Ere(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var Vne=null,ck=null,uk=null;function ONe(t){if(t=IF(t)){if(typeof Vne!="function")throw Error(Be(280));var e=t.stateNode;e&&(e=c6(e),Vne(t.stateNode,t.type,e))}}function HOe(t){ck?uk?uk.push(t):uk=[t]:ck=t}function KOe(){if(ck){var t=ck,e=uk;if(uk=ck=null,ONe(t),e)for(t=0;t<e.length;t++)ONe(e[t])}}function qOe(t,e){return t(e)}function GOe(){}var dne=!1;function YOe(t,e,n){if(dne)return t(e,n);dne=!0;try{return qOe(t,e,n)}finally{dne=!1,(ck!==null||uk!==null)&&(GOe(),KOe())}}function cF(t,e){var n=t.stateNode;if(n===null)return null;var r=c6(n);if(r===null)return null;n=r[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(t=t.type,r=!(t==="button"||t==="input"||t==="select"||t==="textarea")),t=!r;break e;default:t=!1}if(t)return null;if(n&&typeof n!="function")throw Error(Be(231,e,typeof n));return n}var Wne=!1;if(pw)try{GA={},Object.defineProperty(GA,"passive",{get:function(){Wne=!0}}),window.addEventListener("test",GA,GA),window.removeEventListener("test",GA,GA)}catch{Wne=!1}var GA;function TCt(t,e,n,r,o,i,s,a,l){var c=Array.prototype.slice.call(arguments,3);try{e.apply(n,c)}catch(u){this.onError(u)}}var Q$=!1,DH=null,$H=!1,Hne=null,ICt={onError:function(t){Q$=!0,DH=t}};function PCt(t,e,n,r,o,i,s,a,l){Q$=!1,DH=null,TCt.apply(ICt,arguments)}function ECt(t,e,n,r,o,i,s,a,l){if(PCt.apply(this,arguments),Q$){if(Q$){var c=DH;Q$=!1,DH=null}else throw Error(Be(198));$H||($H=!0,Hne=c)}}function mT(t){var e=t,n=t;if(t.alternate)for(;e.return;)e=e.return;else{t=e;do e=t,(e.flags&4098)!==0&&(n=e.return),t=e.return;while(t)}return e.tag===3?n:null}function ZOe(t){if(t.tag===13){var e=t.memoizedState;if(e===null&&(t=t.alternate,t!==null&&(e=t.memoizedState)),e!==null)return e.dehydrated}return null}function RNe(t){if(mT(t)!==t)throw Error(Be(188))}function ACt(t){var e=t.alternate;if(!e){if(e=mT(t),e===null)throw Error(Be(188));return e!==t?null:t}for(var n=t,r=e;;){var o=n.return;if(o===null)break;var i=o.alternate;if(i===null){if(r=o.return,r!==null){n=r;continue}break}if(o.child===i.child){for(i=o.child;i;){if(i===n)return RNe(o),t;if(i===r)return RNe(o),e;i=i.sibling}throw Error(Be(188))}if(n.return!==r.return)n=o,r=i;else{for(var s=!1,a=o.child;a;){if(a===n){s=!0,n=o,r=i;break}if(a===r){s=!0,r=o,n=i;break}a=a.sibling}if(!s){for(a=i.child;a;){if(a===n){s=!0,n=i,r=o;break}if(a===r){s=!0,r=i,n=o;break}a=a.sibling}if(!s)throw Error(Be(189))}}if(n.alternate!==r)throw Error(Be(190))}if(n.tag!==3)throw Error(Be(188));return n.stateNode.current===n?t:e}function JOe(t){return t=ACt(t),t!==null?XOe(t):null}function XOe(t){if(t.tag===5||t.tag===6)return t;for(t=t.child;t!==null;){var e=XOe(t);if(e!==null)return e;t=t.sibling}return null}var QOe=Dd.unstable_scheduleCallback,LNe=Dd.unstable_cancelCallback,kCt=Dd.unstable_shouldYield,MCt=Dd.unstable_requestPaint,ts=Dd.unstable_now,NCt=Dd.unstable_getCurrentPriorityLevel,Are=Dd.unstable_ImmediatePriority,eRe=Dd.unstable_UserBlockingPriority,FH=Dd.unstable_NormalPriority,OCt=Dd.unstable_LowPriority,tRe=Dd.unstable_IdlePriority,i6=null,hg=null;function RCt(t){if(hg&&typeof hg.onCommitFiberRoot=="function")try{hg.onCommitFiberRoot(i6,t,void 0,(t.current.flags&128)===128)}catch{}}var Am=Math.clz32?Math.clz32:$Ct,LCt=Math.log,DCt=Math.LN2;function $Ct(t){return t>>>=0,t===0?32:31-(LCt(t)/DCt|0)|0}var cH=64,uH=4194304;function Z$(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function UH(t,e){var n=t.pendingLanes;if(n===0)return 0;var r=0,o=t.suspendedLanes,i=t.pingedLanes,s=n&268435455;if(s!==0){var a=s&~o;a!==0?r=Z$(a):(i&=s,i!==0&&(r=Z$(i)))}else s=n&~o,s!==0?r=Z$(s):i!==0&&(r=Z$(i));if(r===0)return 0;if(e!==0&&e!==r&&(e&o)===0&&(o=r&-r,i=e&-e,o>=i||o===16&&(i&4194240)!==0))return e;if((r&4)!==0&&(r|=n&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=r;0<e;)n=31-Am(e),o=1<<n,r|=t[n],e&=~o;return r}function FCt(t,e){switch(t){case 1:case 2:case 4:return e+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function UCt(t,e){for(var n=t.suspendedLanes,r=t.pingedLanes,o=t.expirationTimes,i=t.pendingLanes;0<i;){var s=31-Am(i),a=1<<s,l=o[s];l===-1?((a&n)===0||(a&r)!==0)&&(o[s]=FCt(a,e)):l<=e&&(t.expiredLanes|=a),i&=~a}}function Kne(t){return t=t.pendingLanes&-1073741825,t!==0?t:t&1073741824?1073741824:0}function nRe(){var t=cH;return cH<<=1,(cH&4194240)===0&&(cH=64),t}function fne(t){for(var e=[],n=0;31>n;n++)e.push(t);return e}function SF(t,e,n){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Am(e),t[e]=n}function BCt(t,e){var n=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var r=t.eventTimes;for(t=t.expirationTimes;0<n;){var o=31-Am(n),i=1<<o;e[o]=0,r[o]=-1,t[o]=-1,n&=~i}}function kre(t,e){var n=t.entangledLanes|=e;for(t=t.entanglements;n;){var r=31-Am(n),o=1<<r;o&e|t[r]&e&&(t[r]|=e),n&=~o}}var po=0;function rRe(t){return t&=-t,1<t?4<t?(t&268435455)!==0?16:536870912:4:1}var oRe,Mre,iRe,sRe,aRe,qne=!1,dH=[],fb=null,pb=null,mb=null,uF=new Map,dF=new Map,lb=[],zCt="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function DNe(t,e){switch(t){case"focusin":case"focusout":fb=null;break;case"dragenter":case"dragleave":pb=null;break;case"mouseover":case"mouseout":mb=null;break;case"pointerover":case"pointerout":uF.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":dF.delete(e.pointerId)}}function z$(t,e,n,r,o,i){return t===null||t.nativeEvent!==i?(t={blockedOn:e,domEventName:n,eventSystemFlags:r,nativeEvent:i,targetContainers:[o]},e!==null&&(e=IF(e),e!==null&&Mre(e)),t):(t.eventSystemFlags|=r,e=t.targetContainers,o!==null&&e.indexOf(o)===-1&&e.push(o),t)}function jCt(t,e,n,r,o){switch(e){case"focusin":return fb=z$(fb,t,e,n,r,o),!0;case"dragenter":return pb=z$(pb,t,e,n,r,o),!0;case"mouseover":return mb=z$(mb,t,e,n,r,o),!0;case"pointerover":var i=o.pointerId;return uF.set(i,z$(uF.get(i)||null,t,e,n,r,o)),!0;case"gotpointercapture":return i=o.pointerId,dF.set(i,z$(dF.get(i)||null,t,e,n,r,o)),!0}return!1}function lRe(t){var e=rT(t.target);if(e!==null){var n=mT(e);if(n!==null){if(e=n.tag,e===13){if(e=ZOe(n),e!==null){t.blockedOn=e,aRe(t.priority,function(){iRe(n)});return}}else if(e===3&&n.stateNode.current.memoizedState.isDehydrated){t.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}t.blockedOn=null}function TH(t){if(t.blockedOn!==null)return!1;for(var e=t.targetContainers;0<e.length;){var n=Gne(t.domEventName,t.eventSystemFlags,e[0],t.nativeEvent);if(n===null){n=t.nativeEvent;var r=new n.constructor(n.type,n);jne=r,n.target.dispatchEvent(r),jne=null}else return e=IF(n),e!==null&&Mre(e),t.blockedOn=n,!1;e.shift()}return!0}function $Ne(t,e,n){TH(t)&&n.delete(e)}function VCt(){qne=!1,fb!==null&&TH(fb)&&(fb=null),pb!==null&&TH(pb)&&(pb=null),mb!==null&&TH(mb)&&(mb=null),uF.forEach($Ne),dF.forEach($Ne)}function j$(t,e){t.blockedOn===e&&(t.blockedOn=null,qne||(qne=!0,Dd.unstable_scheduleCallback(Dd.unstable_NormalPriority,VCt)))}function fF(t){function e(o){return j$(o,t)}if(0<dH.length){j$(dH[0],t);for(var n=1;n<dH.length;n++){var r=dH[n];r.blockedOn===t&&(r.blockedOn=null)}}for(fb!==null&&j$(fb,t),pb!==null&&j$(pb,t),mb!==null&&j$(mb,t),uF.forEach(e),dF.forEach(e),n=0;n<lb.length;n++)r=lb[n],r.blockedOn===t&&(r.blockedOn=null);for(;0<lb.length&&(n=lb[0],n.blockedOn===null);)lRe(n),n.blockedOn===null&&lb.shift()}var dk=yw.ReactCurrentBatchConfig,BH=!0;function WCt(t,e,n,r){var o=po,i=dk.transition;dk.transition=null;try{po=1,Nre(t,e,n,r)}finally{po=o,dk.transition=i}}function HCt(t,e,n,r){var o=po,i=dk.transition;dk.transition=null;try{po=4,Nre(t,e,n,r)}finally{po=o,dk.transition=i}}function Nre(t,e,n,r){if(BH){var o=Gne(t,e,n,r);if(o===null)vne(t,e,r,zH,n),DNe(t,r);else if(jCt(o,t,e,n,r))r.stopPropagation();else if(DNe(t,r),e&4&&-1<zCt.indexOf(t)){for(;o!==null;){var i=IF(o);if(i!==null&&oRe(i),i=Gne(t,e,n,r),i===null&&vne(t,e,r,zH,n),i===o)break;o=i}o!==null&&r.stopPropagation()}else vne(t,e,r,null,n)}}var zH=null;function Gne(t,e,n,r){if(zH=null,t=Ere(r),t=rT(t),t!==null)if(e=mT(t),e===null)t=null;else if(n=e.tag,n===13){if(t=ZOe(e),t!==null)return t;t=null}else if(n===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;t=null}else e!==t&&(t=null);return zH=t,null}function cRe(t){switch(t){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(NCt()){case Are:return 1;case eRe:return 4;case FH:case OCt:return 16;case tRe:return 536870912;default:return 16}default:return 16}}var ub=null,Ore=null,IH=null;function uRe(){if(IH)return IH;var t,e=Ore,n=e.length,r,o="value"in ub?ub.value:ub.textContent,i=o.length;for(t=0;t<n&&e[t]===o[t];t++);var s=n-t;for(r=1;r<=s&&e[n-r]===o[i-r];r++);return IH=o.slice(t,1<r?1-r:void 0)}function PH(t){var e=t.keyCode;return"charCode"in t?(t=t.charCode,t===0&&e===13&&(t=13)):t=e,t===10&&(t=13),32<=t||t===13?t:0}function fH(){return!0}function FNe(){return!1}function $d(t){function e(n,r,o,i,s){this._reactName=n,this._targetInst=o,this.type=r,this.nativeEvent=i,this.target=s,this.currentTarget=null;for(var a in t)t.hasOwnProperty(a)&&(n=t[a],this[a]=n?n(i):i[a]);return this.isDefaultPrevented=(i.defaultPrevented!=null?i.defaultPrevented:i.returnValue===!1)?fH:FNe,this.isPropagationStopped=FNe,this}return Si(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=fH)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=fH)},persist:function(){},isPersistent:fH}),e}var bk={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(t){return t.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Rre=$d(bk),TF=Si({},bk,{view:0,detail:0}),KCt=$d(TF),pne,mne,V$,s6=Si({},TF,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Lre,button:0,buttons:0,relatedTarget:function(t){return t.relatedTarget===void 0?t.fromElement===t.srcElement?t.toElement:t.fromElement:t.relatedTarget},movementX:function(t){return"movementX"in t?t.movementX:(t!==V$&&(V$&&t.type==="mousemove"?(pne=t.screenX-V$.screenX,mne=t.screenY-V$.screenY):mne=pne=0,V$=t),pne)},movementY:function(t){return"movementY"in t?t.movementY:mne}}),UNe=$d(s6),qCt=Si({},s6,{dataTransfer:0}),GCt=$d(qCt),YCt=Si({},TF,{relatedTarget:0}),hne=$d(YCt),ZCt=Si({},bk,{animationName:0,elapsedTime:0,pseudoElement:0}),JCt=$d(ZCt),XCt=Si({},bk,{clipboardData:function(t){return"clipboardData"in t?t.clipboardData:window.clipboardData}}),QCt=$d(XCt),e_t=Si({},bk,{data:0}),BNe=$d(e_t),t_t={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},n_t={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},r_t={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function o_t(t){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(t):(t=r_t[t])?!!e[t]:!1}function Lre(){return o_t}var i_t=Si({},TF,{key:function(t){if(t.key){var e=t_t[t.key]||t.key;if(e!=="Unidentified")return e}return t.type==="keypress"?(t=PH(t),t===13?"Enter":String.fromCharCode(t)):t.type==="keydown"||t.type==="keyup"?n_t[t.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Lre,charCode:function(t){return t.type==="keypress"?PH(t):0},keyCode:function(t){return t.type==="keydown"||t.type==="keyup"?t.keyCode:0},which:function(t){return t.type==="keypress"?PH(t):t.type==="keydown"||t.type==="keyup"?t.keyCode:0}}),s_t=$d(i_t),a_t=Si({},s6,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),zNe=$d(a_t),l_t=Si({},TF,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Lre}),c_t=$d(l_t),u_t=Si({},bk,{propertyName:0,elapsedTime:0,pseudoElement:0}),d_t=$d(u_t),f_t=Si({},s6,{deltaX:function(t){return"deltaX"in t?t.deltaX:"wheelDeltaX"in t?-t.wheelDeltaX:0},deltaY:function(t){return"deltaY"in t?t.deltaY:"wheelDeltaY"in t?-t.wheelDeltaY:"wheelDelta"in t?-t.wheelDelta:0},deltaZ:0,deltaMode:0}),p_t=$d(f_t),m_t=[9,13,27,32],Dre=pw&&"CompositionEvent"in window,eF=null;pw&&"documentMode"in document&&(eF=document.documentMode);var h_t=pw&&"TextEvent"in window&&!eF,dRe=pw&&(!Dre||eF&&8<eF&&11>=eF),jNe=" ",VNe=!1;function fRe(t,e){switch(t){case"keyup":return m_t.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function pRe(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var XA=!1;function g_t(t,e){switch(t){case"compositionend":return pRe(e);case"keypress":return e.which!==32?null:(VNe=!0,jNe);case"textInput":return t=e.data,t===jNe&&VNe?null:t;default:return null}}function y_t(t,e){if(XA)return t==="compositionend"||!Dre&&fRe(t,e)?(t=uRe(),IH=Ore=ub=null,XA=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return dRe&&e.locale!=="ko"?null:e.data;default:return null}}var w_t={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function WNe(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e==="input"?!!w_t[t.type]:e==="textarea"}function mRe(t,e,n,r){HOe(r),e=jH(e,"onChange"),0<e.length&&(n=new Rre("onChange","change",null,n,r),t.push({event:n,listeners:e}))}var tF=null,pF=null;function v_t(t){TRe(t,0)}function a6(t){var e=tk(t);if(FOe(e))return t}function x_t(t,e){if(t==="change")return e}var hRe=!1;pw&&(pw?(mH="oninput"in document,mH||(gne=document.createElement("div"),gne.setAttribute("oninput","return;"),mH=typeof gne.oninput=="function"),pH=mH):pH=!1,hRe=pH&&(!document.documentMode||9<document.documentMode));var pH,mH,gne;function HNe(){tF&&(tF.detachEvent("onpropertychange",gRe),pF=tF=null)}function gRe(t){if(t.propertyName==="value"&&a6(pF)){var e=[];mRe(e,pF,t,Ere(t)),YOe(v_t,e)}}function b_t(t,e,n){t==="focusin"?(HNe(),tF=e,pF=n,tF.attachEvent("onpropertychange",gRe)):t==="focusout"&&HNe()}function C_t(t){if(t==="selectionchange"||t==="keyup"||t==="keydown")return a6(pF)}function __t(t,e){if(t==="click")return a6(e)}function S_t(t,e){if(t==="input"||t==="change")return a6(e)}function T_t(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var Mm=typeof Object.is=="function"?Object.is:T_t;function mF(t,e){if(Mm(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var o=n[r];if(!kne.call(e,o)||!Mm(t[o],e[o]))return!1}return!0}function KNe(t){for(;t&&t.firstChild;)t=t.firstChild;return t}function qNe(t,e){var n=KNe(t);t=0;for(var r;n;){if(n.nodeType===3){if(r=t+n.textContent.length,t<=e&&r>=e)return{node:n,offset:e-t};t=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=KNe(n)}}function yRe(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?yRe(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function wRe(){for(var t=window,e=LH();e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=LH(t.document)}return e}function $re(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function I_t(t){var e=wRe(),n=t.focusedElem,r=t.selectionRange;if(e!==n&&n&&n.ownerDocument&&yRe(n.ownerDocument.documentElement,n)){if(r!==null&&$re(n)){if(e=r.start,t=r.end,t===void 0&&(t=e),"selectionStart"in n)n.selectionStart=e,n.selectionEnd=Math.min(t,n.value.length);else if(t=(e=n.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!t.extend&&i>r&&(o=r,r=i,i=o),o=qNe(n,i);var s=qNe(n,r);o&&s&&(t.rangeCount!==1||t.anchorNode!==o.node||t.anchorOffset!==o.offset||t.focusNode!==s.node||t.focusOffset!==s.offset)&&(e=e.createRange(),e.setStart(o.node,o.offset),t.removeAllRanges(),i>r?(t.addRange(e),t.extend(s.node,s.offset)):(e.setEnd(s.node,s.offset),t.addRange(e)))}}for(e=[],t=n;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n<e.length;n++)t=e[n],t.element.scrollLeft=t.left,t.element.scrollTop=t.top}}var P_t=pw&&"documentMode"in document&&11>=document.documentMode,QA=null,Yne=null,nF=null,Zne=!1;function GNe(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Zne||QA==null||QA!==LH(r)||(r=QA,"selectionStart"in r&&$re(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),nF&&mF(nF,r)||(nF=r,r=jH(Yne,"onSelect"),0<r.length&&(e=new Rre("onSelect","select",null,e,n),t.push({event:e,listeners:r}),e.target=QA)))}function hH(t,e){var n={};return n[t.toLowerCase()]=e.toLowerCase(),n["Webkit"+t]="webkit"+e,n["Moz"+t]="moz"+e,n}var ek={animationend:hH("Animation","AnimationEnd"),animationiteration:hH("Animation","AnimationIteration"),animationstart:hH("Animation","AnimationStart"),transitionend:hH("Transition","TransitionEnd")},yne={},vRe={};pw&&(vRe=document.createElement("div").style,"AnimationEvent"in window||(delete ek.animationend.animation,delete ek.animationiteration.animation,delete ek.animationstart.animation),"TransitionEvent"in window||delete ek.transitionend.transition);function l6(t){if(yne[t])return yne[t];if(!ek[t])return t;var e=ek[t],n;for(n in e)if(e.hasOwnProperty(n)&&n in vRe)return yne[t]=e[n];return t}var xRe=l6("animationend"),bRe=l6("animationiteration"),CRe=l6("animationstart"),_Re=l6("transitionend"),SRe=new Map,YNe="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Cb(t,e){SRe.set(t,e),pT(e,[t])}for(gH=0;gH<YNe.length;gH++)yH=YNe[gH],ZNe=yH.toLowerCase(),JNe=yH[0].toUpperCase()+yH.slice(1),Cb(ZNe,"on"+JNe);var yH,ZNe,JNe,gH;Cb(xRe,"onAnimationEnd");Cb(bRe,"onAnimationIteration");Cb(CRe,"onAnimationStart");Cb("dblclick","onDoubleClick");Cb("focusin","onFocus");Cb("focusout","onBlur");Cb(_Re,"onTransitionEnd");mk("onMouseEnter",["mouseout","mouseover"]);mk("onMouseLeave",["mouseout","mouseover"]);mk("onPointerEnter",["pointerout","pointerover"]);mk("onPointerLeave",["pointerout","pointerover"]);pT("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));pT("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));pT("onBeforeInput",["compositionend","keypress","textInput","paste"]);pT("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));pT("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));pT("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var J$="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),E_t=new Set("cancel close invalid load scroll toggle".split(" ").concat(J$));function XNe(t,e,n){var r=t.type||"unknown-event";t.currentTarget=n,ECt(r,e,void 0,t),t.currentTarget=null}function TRe(t,e){e=(e&4)!==0;for(var n=0;n<t.length;n++){var r=t[n],o=r.event;r=r.listeners;e:{var i=void 0;if(e)for(var s=r.length-1;0<=s;s--){var a=r[s],l=a.instance,c=a.currentTarget;if(a=a.listener,l!==i&&o.isPropagationStopped())break e;XNe(o,a,c),i=l}else for(s=0;s<r.length;s++){if(a=r[s],l=a.instance,c=a.currentTarget,a=a.listener,l!==i&&o.isPropagationStopped())break e;XNe(o,a,c),i=l}}}if($H)throw t=Hne,$H=!1,Hne=null,t}function qo(t,e){var n=e[tre];n===void 0&&(n=e[tre]=new Set);var r=t+"__bubble";n.has(r)||(IRe(e,t,2,!1),n.add(r))}function wne(t,e,n){var r=0;e&&(r|=4),IRe(n,t,r,e)}var wH="_reactListening"+Math.random().toString(36).slice(2);function hF(t){if(!t[wH]){t[wH]=!0,OOe.forEach(function(n){n!=="selectionchange"&&(E_t.has(n)||wne(n,!1,t),wne(n,!0,t))});var e=t.nodeType===9?t:t.ownerDocument;e===null||e[wH]||(e[wH]=!0,wne("selectionchange",!1,e))}}function IRe(t,e,n,r){switch(cRe(e)){case 1:var o=WCt;break;case 4:o=HCt;break;default:o=Nre}n=o.bind(null,e,n,t),o=void 0,!Wne||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(o=!0),r?o!==void 0?t.addEventListener(e,n,{capture:!0,passive:o}):t.addEventListener(e,n,!0):o!==void 0?t.addEventListener(e,n,{passive:o}):t.addEventListener(e,n,!1)}function vne(t,e,n,r,o){var i=r;if((e&1)===0&&(e&2)===0&&r!==null)e:for(;;){if(r===null)return;var s=r.tag;if(s===3||s===4){var a=r.stateNode.containerInfo;if(a===o||a.nodeType===8&&a.parentNode===o)break;if(s===4)for(s=r.return;s!==null;){var l=s.tag;if((l===3||l===4)&&(l=s.stateNode.containerInfo,l===o||l.nodeType===8&&l.parentNode===o))return;s=s.return}for(;a!==null;){if(s=rT(a),s===null)return;if(l=s.tag,l===5||l===6){r=i=s;continue e}a=a.parentNode}}r=r.return}YOe(function(){var c=i,u=Ere(n),d=[];e:{var f=SRe.get(t);if(f!==void 0){var p=Rre,m=t;switch(t){case"keypress":if(PH(n)===0)break e;case"keydown":case"keyup":p=s_t;break;case"focusin":m="focus",p=hne;break;case"focusout":m="blur",p=hne;break;case"beforeblur":case"afterblur":p=hne;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":p=UNe;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":p=GCt;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":p=c_t;break;case xRe:case bRe:case CRe:p=JCt;break;case _Re:p=d_t;break;case"scroll":p=KCt;break;case"wheel":p=p_t;break;case"copy":case"cut":case"paste":p=QCt;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":p=zNe}var h=(e&4)!==0,g=!h&&t==="scroll",y=h?f!==null?f+"Capture":null:f;h=[];for(var w=c,v;w!==null;){v=w;var x=v.stateNode;if(v.tag===5&&x!==null&&(v=x,y!==null&&(x=cF(w,y),x!=null&&h.push(gF(w,x,v)))),g)break;w=w.return}0<h.length&&(f=new p(f,m,null,n,u),d.push({event:f,listeners:h}))}}if((e&7)===0){e:{if(f=t==="mouseover"||t==="pointerover",p=t==="mouseout"||t==="pointerout",f&&n!==jne&&(m=n.relatedTarget||n.fromElement)&&(rT(m)||m[mw]))break e;if((p||f)&&(f=u.window===u?u:(f=u.ownerDocument)?f.defaultView||f.parentWindow:window,p?(m=n.relatedTarget||n.toElement,p=c,m=m?rT(m):null,m!==null&&(g=mT(m),m!==g||m.tag!==5&&m.tag!==6)&&(m=null)):(p=null,m=c),p!==m)){if(h=UNe,x="onMouseLeave",y="onMouseEnter",w="mouse",(t==="pointerout"||t==="pointerover")&&(h=zNe,x="onPointerLeave",y="onPointerEnter",w="pointer"),g=p==null?f:tk(p),v=m==null?f:tk(m),f=new h(x,w+"leave",p,n,u),f.target=g,f.relatedTarget=v,x=null,rT(u)===c&&(h=new h(y,w+"enter",m,n,u),h.target=v,h.relatedTarget=g,x=h),g=x,p&&m)t:{for(h=p,y=m,w=0,v=h;v;v=YA(v))w++;for(v=0,x=y;x;x=YA(x))v++;for(;0<w-v;)h=YA(h),w--;for(;0<v-w;)y=YA(y),v--;for(;w--;){if(h===y||y!==null&&h===y.alternate)break t;h=YA(h),y=YA(y)}h=null}else h=null;p!==null&&QNe(d,f,p,h,!1),m!==null&&g!==null&&QNe(d,g,m,h,!0)}}e:{if(f=c?tk(c):window,p=f.nodeName&&f.nodeName.toLowerCase(),p==="select"||p==="input"&&f.type==="file")var b=x_t;else if(WNe(f))if(hRe)b=S_t;else{b=C_t;var _=b_t}else(p=f.nodeName)&&p.toLowerCase()==="input"&&(f.type==="checkbox"||f.type==="radio")&&(b=__t);if(b&&(b=b(t,c))){mRe(d,b,n,u);break e}_&&_(t,f,c),t==="focusout"&&(_=f._wrapperState)&&_.controlled&&f.type==="number"&&$ne(f,"number",f.value)}switch(_=c?tk(c):window,t){case"focusin":(WNe(_)||_.contentEditable==="true")&&(QA=_,Yne=c,nF=null);break;case"focusout":nF=Yne=QA=null;break;case"mousedown":Zne=!0;break;case"contextmenu":case"mouseup":case"dragend":Zne=!1,GNe(d,n,u);break;case"selectionchange":if(P_t)break;case"keydown":case"keyup":GNe(d,n,u)}var T;if(Dre)e:{switch(t){case"compositionstart":var S="onCompositionStart";break e;case"compositionend":S="onCompositionEnd";break e;case"compositionupdate":S="onCompositionUpdate";break e}S=void 0}else XA?fRe(t,n)&&(S="onCompositionEnd"):t==="keydown"&&n.keyCode===229&&(S="onCompositionStart");S&&(dRe&&n.locale!=="ko"&&(XA||S!=="onCompositionStart"?S==="onCompositionEnd"&&XA&&(T=uRe()):(ub=u,Ore="value"in ub?ub.value:ub.textContent,XA=!0)),_=jH(c,S),0<_.length&&(S=new BNe(S,t,null,n,u),d.push({event:S,listeners:_}),T?S.data=T:(T=pRe(n),T!==null&&(S.data=T)))),(T=h_t?g_t(t,n):y_t(t,n))&&(c=jH(c,"onBeforeInput"),0<c.length&&(u=new BNe("onBeforeInput","beforeinput",null,n,u),d.push({event:u,listeners:c}),u.data=T))}TRe(d,e)})}function gF(t,e,n){return{instance:t,listener:e,currentTarget:n}}function jH(t,e){for(var n=e+"Capture",r=[];t!==null;){var o=t,i=o.stateNode;o.tag===5&&i!==null&&(o=i,i=cF(t,n),i!=null&&r.unshift(gF(t,i,o)),i=cF(t,e),i!=null&&r.push(gF(t,i,o))),t=t.return}return r}function YA(t){if(t===null)return null;do t=t.return;while(t&&t.tag!==5);return t||null}function QNe(t,e,n,r,o){for(var i=e._reactName,s=[];n!==null&&n!==r;){var a=n,l=a.alternate,c=a.stateNode;if(l!==null&&l===r)break;a.tag===5&&c!==null&&(a=c,o?(l=cF(n,i),l!=null&&s.unshift(gF(n,l,a))):o||(l=cF(n,i),l!=null&&s.push(gF(n,l,a)))),n=n.return}s.length!==0&&t.push({event:e,listeners:s})}var A_t=/\r\n?/g,k_t=/\u0000|\uFFFD/g;function eOe(t){return(typeof t=="string"?t:""+t).replace(A_t,`
`).replace(k_t,"")}function vH(t,e,n){if(e=eOe(e),eOe(t)!==e&&n)throw Error(Be(425))}function VH(){}var Jne=null,Xne=null;function Qne(t,e){return t==="textarea"||t==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var ere=typeof setTimeout=="function"?setTimeout:void 0,M_t=typeof clearTimeout=="function"?clearTimeout:void 0,tOe=typeof Promise=="function"?Promise:void 0,N_t=typeof queueMicrotask=="function"?queueMicrotask:typeof tOe<"u"?function(t){return tOe.resolve(null).then(t).catch(O_t)}:ere;function O_t(t){setTimeout(function(){throw t})}function xne(t,e){var n=e,r=0;do{var o=n.nextSibling;if(t.removeChild(n),o&&o.nodeType===8)if(n=o.data,n==="/$"){if(r===0){t.removeChild(o),fF(e);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=o}while(n);fF(e)}function hb(t){for(;t!=null;t=t.nextSibling){var e=t.nodeType;if(e===1||e===3)break;if(e===8){if(e=t.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return t}function nOe(t){t=t.previousSibling;for(var e=0;t;){if(t.nodeType===8){var n=t.data;if(n==="$"||n==="$!"||n==="$?"){if(e===0)return t;e--}else n==="/$"&&e++}t=t.previousSibling}return null}var Ck=Math.random().toString(36).slice(2),mg="__reactFiber$"+Ck,yF="__reactProps$"+Ck,mw="__reactContainer$"+Ck,tre="__reactEvents$"+Ck,R_t="__reactListeners$"+Ck,L_t="__reactHandles$"+Ck;function rT(t){var e=t[mg];if(e)return e;for(var n=t.parentNode;n;){if(e=n[mw]||n[mg]){if(n=e.alternate,e.child!==null||n!==null&&n.child!==null)for(t=nOe(t);t!==null;){if(n=t[mg])return n;t=nOe(t)}return e}t=n,n=t.parentNode}return null}function IF(t){return t=t[mg]||t[mw],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function tk(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(Be(33))}function c6(t){return t[yF]||null}var nre=[],nk=-1;function _b(t){return{current:t}}function Go(t){0>nk||(t.current=nre[nk],nre[nk]=null,nk--)}function Do(t,e){nk++,nre[nk]=t.current,t.current=e}var bb={},Xl=_b(bb),Nu=_b(!1),lT=bb;function hk(t,e){var n=t.type.contextTypes;if(!n)return bb;var r=t.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=e[i];return r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=o),o}function Ou(t){return t=t.childContextTypes,t!=null}function WH(){Go(Nu),Go(Xl)}function rOe(t,e,n){if(Xl.current!==bb)throw Error(Be(168));Do(Xl,e),Do(Nu,n)}function PRe(t,e,n){var r=t.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in e))throw Error(Be(108,bCt(t)||"Unknown",o));return Si({},n,r)}function HH(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||bb,lT=Xl.current,Do(Xl,t),Do(Nu,Nu.current),!0}function oOe(t,e,n){var r=t.stateNode;if(!r)throw Error(Be(169));n?(t=PRe(t,e,lT),r.__reactInternalMemoizedMergedChildContext=t,Go(Nu),Go(Xl),Do(Xl,t)):Go(Nu),Do(Nu,n)}var cw=null,u6=!1,bne=!1;function ERe(t){cw===null?cw=[t]:cw.push(t)}function D_t(t){u6=!0,ERe(t)}function Sb(){if(!bne&&cw!==null){bne=!0;var t=0,e=po;try{var n=cw;for(po=1;t<n.length;t++){var r=n[t];do r=r(!0);while(r!==null)}cw=null,u6=!1}catch(o){throw cw!==null&&(cw=cw.slice(t+1)),QOe(Are,Sb),o}finally{po=e,bne=!1}}return null}var rk=[],ok=0,KH=null,qH=0,Vf=[],Wf=0,cT=null,uw=1,dw="";function tT(t,e){rk[ok++]=qH,rk[ok++]=KH,KH=t,qH=e}function ARe(t,e,n){Vf[Wf++]=uw,Vf[Wf++]=dw,Vf[Wf++]=cT,cT=t;var r=uw;t=dw;var o=32-Am(r)-1;r&=~(1<<o),n+=1;var i=32-Am(e)+o;if(30<i){var s=o-o%5;i=(r&(1<<s)-1).toString(32),r>>=s,o-=s,uw=1<<32-Am(e)+o|n<<o|r,dw=i+t}else uw=1<<i|n<<o|r,dw=t}function Fre(t){t.return!==null&&(tT(t,1),ARe(t,1,0))}function Ure(t){for(;t===KH;)KH=rk[--ok],rk[ok]=null,qH=rk[--ok],rk[ok]=null;for(;t===cT;)cT=Vf[--Wf],Vf[Wf]=null,dw=Vf[--Wf],Vf[Wf]=null,uw=Vf[--Wf],Vf[Wf]=null}var Ld=null,Rd=null,li=!1,Em=null;function kRe(t,e){var n=Hf(5,null,null,0);n.elementType="DELETED",n.stateNode=e,n.return=t,e=t.deletions,e===null?(t.deletions=[n],t.flags|=16):e.push(n)}function iOe(t,e){switch(t.tag){case 5:var n=t.type;return e=e.nodeType!==1||n.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(t.stateNode=e,Ld=t,Rd=hb(e.firstChild),!0):!1;case 6:return e=t.pendingProps===""||e.nodeType!==3?null:e,e!==null?(t.stateNode=e,Ld=t,Rd=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(n=cT!==null?{id:uw,overflow:dw}:null,t.memoizedState={dehydrated:e,treeContext:n,retryLane:1073741824},n=Hf(18,null,null,0),n.stateNode=e,n.return=t,t.child=n,Ld=t,Rd=null,!0):!1;default:return!1}}function rre(t){return(t.mode&1)!==0&&(t.flags&128)===0}function ore(t){if(li){var e=Rd;if(e){var n=e;if(!iOe(t,e)){if(rre(t))throw Error(Be(418));e=hb(n.nextSibling);var r=Ld;e&&iOe(t,e)?kRe(r,n):(t.flags=t.flags&-4097|2,li=!1,Ld=t)}}else{if(rre(t))throw Error(Be(418));t.flags=t.flags&-4097|2,li=!1,Ld=t}}}function sOe(t){for(t=t.return;t!==null&&t.tag!==5&&t.tag!==3&&t.tag!==13;)t=t.return;Ld=t}function xH(t){if(t!==Ld)return!1;if(!li)return sOe(t),li=!0,!1;var e;if((e=t.tag!==3)&&!(e=t.tag!==5)&&(e=t.type,e=e!=="head"&&e!=="body"&&!Qne(t.type,t.memoizedProps)),e&&(e=Rd)){if(rre(t))throw MRe(),Error(Be(418));for(;e;)kRe(t,e),e=hb(e.nextSibling)}if(sOe(t),t.tag===13){if(t=t.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(Be(317));e:{for(t=t.nextSibling,e=0;t;){if(t.nodeType===8){var n=t.data;if(n==="/$"){if(e===0){Rd=hb(t.nextSibling);break e}e--}else n!=="$"&&n!=="$!"&&n!=="$?"||e++}t=t.nextSibling}Rd=null}}else Rd=Ld?hb(t.stateNode.nextSibling):null;return!0}function MRe(){for(var t=Rd;t;)t=hb(t.nextSibling)}function gk(){Rd=Ld=null,li=!1}function Bre(t){Em===null?Em=[t]:Em.push(t)}var $_t=yw.ReactCurrentBatchConfig;function Im(t,e){if(t&&t.defaultProps){e=Si({},e),t=t.defaultProps;for(var n in t)e[n]===void 0&&(e[n]=t[n]);return e}return e}var GH=_b(null),YH=null,ik=null,zre=null;function jre(){zre=ik=YH=null}function Vre(t){var e=GH.current;Go(GH),t._currentValue=e}function ire(t,e,n){for(;t!==null;){var r=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),t===n)break;t=t.return}}function fk(t,e){YH=t,zre=ik=null,t=t.dependencies,t!==null&&t.firstContext!==null&&((t.lanes&e)!==0&&(Mu=!0),t.firstContext=null)}function qf(t){var e=t._currentValue;if(zre!==t)if(t={context:t,memoizedValue:e,next:null},ik===null){if(YH===null)throw Error(Be(308));ik=t,YH.dependencies={lanes:0,firstContext:t}}else ik=ik.next=t;return e}var oT=null;function Wre(t){oT===null?oT=[t]:oT.push(t)}function NRe(t,e,n,r){var o=e.interleaved;return o===null?(n.next=n,Wre(e)):(n.next=o.next,o.next=n),e.interleaved=n,hw(t,r)}function hw(t,e){t.lanes|=e;var n=t.alternate;for(n!==null&&(n.lanes|=e),n=t,t=t.return;t!==null;)t.childLanes|=e,n=t.alternate,n!==null&&(n.childLanes|=e),n=t,t=t.return;return n.tag===3?n.stateNode:null}var ab=!1;function Hre(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function ORe(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function fw(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function gb(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,(zr&2)!==0){var o=r.pending;return o===null?e.next=e:(e.next=o.next,o.next=e),r.pending=e,hw(t,n)}return o=r.interleaved,o===null?(e.next=e,Wre(r)):(e.next=o.next,o.next=e),r.interleaved=e,hw(t,n)}function EH(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194240)!==0)){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,kre(t,n)}}function aOe(t,e){var n=t.updateQueue,r=t.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var o=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var s={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?o=i=s:i=i.next=s,n=n.next}while(n!==null);i===null?o=i=e:i=i.next=e}else o=i=e;n={baseState:r.baseState,firstBaseUpdate:o,lastBaseUpdate:i,shared:r.shared,effects:r.effects},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}function ZH(t,e,n,r){var o=t.updateQueue;ab=!1;var i=o.firstBaseUpdate,s=o.lastBaseUpdate,a=o.shared.pending;if(a!==null){o.shared.pending=null;var l=a,c=l.next;l.next=null,s===null?i=c:s.next=c,s=l;var u=t.alternate;u!==null&&(u=u.updateQueue,a=u.lastBaseUpdate,a!==s&&(a===null?u.firstBaseUpdate=c:a.next=c,u.lastBaseUpdate=l))}if(i!==null){var d=o.baseState;s=0,u=c=l=null,a=i;do{var f=a.lane,p=a.eventTime;if((r&f)===f){u!==null&&(u=u.next={eventTime:p,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var m=t,h=a;switch(f=e,p=n,h.tag){case 1:if(m=h.payload,typeof m=="function"){d=m.call(p,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m=="function"?m.call(p,d,f):m,f==null)break e;d=Si({},d,f);break e;case 2:ab=!0}}a.callback!==null&&a.lane!==0&&(t.flags|=64,f=o.effects,f===null?o.effects=[a]:f.push(a))}else p={eventTime:p,lane:f,tag:a.tag,payload:a.payload,callback:a.callback,next:null},u===null?(c=u=p,l=d):u=u.next=p,s|=f;if(a=a.next,a===null){if(a=o.shared.pending,a===null)break;f=a,a=f.next,f.next=null,o.lastBaseUpdate=f,o.shared.pending=null}}while(!0);if(u===null&&(l=d),o.baseState=l,o.firstBaseUpdate=c,o.lastBaseUpdate=u,e=o.shared.interleaved,e!==null){o=e;do s|=o.lane,o=o.next;while(o!==e)}else i===null&&(o.shared.lanes=0);dT|=s,t.lanes=s,t.memoizedState=d}}function lOe(t,e,n){if(t=e.effects,e.effects=null,t!==null)for(e=0;e<t.length;e++){var r=t[e],o=r.callback;if(o!==null){if(r.callback=null,r=n,typeof o!="function")throw Error(Be(191,o));o.call(r)}}}var RRe=new NOe.Component().refs;function sre(t,e,n,r){e=t.memoizedState,n=n(r,e),n=n==null?e:Si({},e,n),t.memoizedState=n,t.lanes===0&&(t.updateQueue.baseState=n)}var d6={isMounted:function(t){return(t=t._reactInternals)?mT(t)===t:!1},enqueueSetState:function(t,e,n){t=t._reactInternals;var r=$c(),o=wb(t),i=fw(r,o);i.payload=e,n!=null&&(i.callback=n),e=gb(t,i,o),e!==null&&(km(e,t,o,r),EH(e,t,o))},enqueueReplaceState:function(t,e,n){t=t._reactInternals;var r=$c(),o=wb(t),i=fw(r,o);i.tag=1,i.payload=e,n!=null&&(i.callback=n),e=gb(t,i,o),e!==null&&(km(e,t,o,r),EH(e,t,o))},enqueueForceUpdate:function(t,e){t=t._reactInternals;var n=$c(),r=wb(t),o=fw(n,r);o.tag=2,e!=null&&(o.callback=e),e=gb(t,o,r),e!==null&&(km(e,t,r,n),EH(e,t,r))}};function cOe(t,e,n,r,o,i,s){return t=t.stateNode,typeof t.shouldComponentUpdate=="function"?t.shouldComponentUpdate(r,i,s):e.prototype&&e.prototype.isPureReactComponent?!mF(n,r)||!mF(o,i):!0}function LRe(t,e,n){var r=!1,o=bb,i=e.contextType;return typeof i=="object"&&i!==null?i=qf(i):(o=Ou(e)?lT:Xl.current,r=e.contextTypes,i=(r=r!=null)?hk(t,o):bb),e=new e(n,i),t.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=d6,t.stateNode=e,e._reactInternals=t,r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=o,t.__reactInternalMemoizedMaskedChildContext=i),e}function uOe(t,e,n,r){t=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(n,r),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(n,r),e.state!==t&&d6.enqueueReplaceState(e,e.state,null)}function are(t,e,n,r){var o=t.stateNode;o.props=n,o.state=t.memoizedState,o.refs=RRe,Hre(t);var i=e.contextType;typeof i=="object"&&i!==null?o.context=qf(i):(i=Ou(e)?lT:Xl.current,o.context=hk(t,i)),o.state=t.memoizedState,i=e.getDerivedStateFromProps,typeof i=="function"&&(sre(t,e,i,n),o.state=t.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof o.getSnapshotBeforeUpdate=="function"||typeof o.UNSAFE_componentWillMount!="function"&&typeof o.componentWillMount!="function"||(e=o.state,typeof o.componentWillMount=="function"&&o.componentWillMount(),typeof o.UNSAFE_componentWillMount=="function"&&o.UNSAFE_componentWillMount(),e!==o.state&&d6.enqueueReplaceState(o,o.state,null),ZH(t,n,o,r),o.state=t.memoizedState),typeof o.componentDidMount=="function"&&(t.flags|=4194308)}function W$(t,e,n){if(t=n.ref,t!==null&&typeof t!="function"&&typeof t!="object"){if(n._owner){if(n=n._owner,n){if(n.tag!==1)throw Error(Be(309));var r=n.stateNode}if(!r)throw Error(Be(147,t));var o=r,i=""+t;return e!==null&&e.ref!==null&&typeof e.ref=="function"&&e.ref._stringRef===i?e.ref:(e=function(s){var a=o.refs;a===RRe&&(a=o.refs={}),s===null?delete a[i]:a[i]=s},e._stringRef=i,e)}if(typeof t!="string")throw Error(Be(284));if(!n._owner)throw Error(Be(290,t))}return t}function bH(t,e){throw t=Object.prototype.toString.call(e),Error(Be(31,t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t))}function dOe(t){var e=t._init;return e(t._payload)}function DRe(t){function e(y,w){if(t){var v=y.deletions;v===null?(y.deletions=[w],y.flags|=16):v.push(w)}}function n(y,w){if(!t)return null;for(;w!==null;)e(y,w),w=w.sibling;return null}function r(y,w){for(y=new Map;w!==null;)w.key!==null?y.set(w.key,w):y.set(w.index,w),w=w.sibling;return y}function o(y,w){return y=vb(y,w),y.index=0,y.sibling=null,y}function i(y,w,v){return y.index=v,t?(v=y.alternate,v!==null?(v=v.index,v<w?(y.flags|=2,w):v):(y.flags|=2,w)):(y.flags|=1048576,w)}function s(y){return t&&y.alternate===null&&(y.flags|=2),y}function a(y,w,v,x){return w===null||w.tag!==6?(w=Ene(v,y.mode,x),w.return=y,w):(w=o(w,v),w.return=y,w)}function l(y,w,v,x){var b=v.type;return b===JA?u(y,w,v.props.children,x,v.key):w!==null&&(w.elementType===b||typeof b=="object"&&b!==null&&b.$$typeof===sb&&dOe(b)===w.type)?(x=o(w,v.props),x.ref=W$(y,w,v),x.return=y,x):(x=RH(v.type,v.key,v.props,null,y.mode,x),x.ref=W$(y,w,v),x.return=y,x)}function c(y,w,v,x){return w===null||w.tag!==4||w.stateNode.containerInfo!==v.containerInfo||w.stateNode.implementation!==v.implementation?(w=Ane(v,y.mode,x),w.return=y,w):(w=o(w,v.children||[]),w.return=y,w)}function u(y,w,v,x,b){return w===null||w.tag!==7?(w=aT(v,y.mode,x,b),w.return=y,w):(w=o(w,v),w.return=y,w)}function d(y,w,v){if(typeof w=="string"&&w!==""||typeof w=="number")return w=Ene(""+w,y.mode,v),w.return=y,w;if(typeof w=="object"&&w!==null){switch(w.$$typeof){case sH:return v=RH(w.type,w.key,w.props,null,y.mode,v),v.ref=W$(y,null,w),v.return=y,v;case ZA:return w=Ane(w,y.mode,v),w.return=y,w;case sb:var x=w._init;return d(y,x(w._payload),v)}if(Y$(w)||B$(w))return w=aT(w,y.mode,v,null),w.return=y,w;bH(y,w)}return null}function f(y,w,v,x){var b=w!==null?w.key:null;if(typeof v=="string"&&v!==""||typeof v=="number")return b!==null?null:a(y,w,""+v,x);if(typeof v=="object"&&v!==null){switch(v.$$typeof){case sH:return v.key===b?l(y,w,v,x):null;case ZA:return v.key===b?c(y,w,v,x):null;case sb:return b=v._init,f(y,w,b(v._payload),x)}if(Y$(v)||B$(v))return b!==null?null:u(y,w,v,x,null);bH(y,v)}return null}function p(y,w,v,x,b){if(typeof x=="string"&&x!==""||typeof x=="number")return y=y.get(v)||null,a(w,y,""+x,b);if(typeof x=="object"&&x!==null){switch(x.$$typeof){case sH:return y=y.get(x.key===null?v:x.key)||null,l(w,y,x,b);case ZA:return y=y.get(x.key===null?v:x.key)||null,c(w,y,x,b);case sb:var _=x._init;return p(y,w,v,_(x._payload),b)}if(Y$(x)||B$(x))return y=y.get(v)||null,u(w,y,x,b,null);bH(w,x)}return null}function m(y,w,v,x){for(var b=null,_=null,T=w,S=w=0,P=null;T!==null&&S<v.length;S++){T.index>S?(P=T,T=null):P=T.sibling;var A=f(y,T,v[S],x);if(A===null){T===null&&(T=P);break}t&&T&&A.alternate===null&&e(y,T),w=i(A,w,S),_===null?b=A:_.sibling=A,_=A,T=P}if(S===v.length)return n(y,T),li&&tT(y,S),b;if(T===null){for(;S<v.length;S++)T=d(y,v[S],x),T!==null&&(w=i(T,w,S),_===null?b=T:_.sibling=T,_=T);return li&&tT(y,S),b}for(T=r(y,T);S<v.length;S++)P=p(T,y,S,v[S],x),P!==null&&(t&&P.alternate!==null&&T.delete(P.key===null?S:P.key),w=i(P,w,S),_===null?b=P:_.sibling=P,_=P);return t&&T.forEach(function(O){return e(y,O)}),li&&tT(y,S),b}function h(y,w,v,x){var b=B$(v);if(typeof b!="function")throw Error(Be(150));if(v=b.call(v),v==null)throw Error(Be(151));for(var _=b=null,T=w,S=w=0,P=null,A=v.next();T!==null&&!A.done;S++,A=v.next()){T.index>S?(P=T,T=null):P=T.sibling;var O=f(y,T,A.value,x);if(O===null){T===null&&(T=P);break}t&&T&&O.alternate===null&&e(y,T),w=i(O,w,S),_===null?b=O:_.sibling=O,_=O,T=P}if(A.done)return n(y,T),li&&tT(y,S),b;if(T===null){for(;!A.done;S++,A=v.next())A=d(y,A.value,x),A!==null&&(w=i(A,w,S),_===null?b=A:_.sibling=A,_=A);return li&&tT(y,S),b}for(T=r(y,T);!A.done;S++,A=v.next())A=p(T,y,S,A.value,x),A!==null&&(t&&A.alternate!==null&&T.delete(A.key===null?S:A.key),w=i(A,w,S),_===null?b=A:_.sibling=A,_=A);return t&&T.forEach(function(D){return e(y,D)}),li&&tT(y,S),b}function g(y,w,v,x){if(typeof v=="object"&&v!==null&&v.type===JA&&v.key===null&&(v=v.props.children),typeof v=="object"&&v!==null){switch(v.$$typeof){case sH:e:{for(var b=v.key,_=w;_!==null;){if(_.key===b){if(b=v.type,b===JA){if(_.tag===7){n(y,_.sibling),w=o(_,v.props.children),w.return=y,y=w;break e}}else if(_.elementType===b||typeof b=="object"&&b!==null&&b.$$typeof===sb&&dOe(b)===_.type){n(y,_.sibling),w=o(_,v.props),w.ref=W$(y,_,v),w.return=y,y=w;break e}n(y,_);break}else e(y,_);_=_.sibling}v.type===JA?(w=aT(v.props.children,y.mode,x,v.key),w.return=y,y=w):(x=RH(v.type,v.key,v.props,null,y.mode,x),x.ref=W$(y,w,v),x.return=y,y=x)}return s(y);case ZA:e:{for(_=v.key;w!==null;){if(w.key===_)if(w.tag===4&&w.stateNode.containerInfo===v.containerInfo&&w.stateNode.implementation===v.implementation){n(y,w.sibling),w=o(w,v.children||[]),w.return=y,y=w;break e}else{n(y,w);break}else e(y,w);w=w.sibling}w=Ane(v,y.mode,x),w.return=y,y=w}return s(y);case sb:return _=v._init,g(y,w,_(v._payload),x)}if(Y$(v))return m(y,w,v,x);if(B$(v))return h(y,w,v,x);bH(y,v)}return typeof v=="string"&&v!==""||typeof v=="number"?(v=""+v,w!==null&&w.tag===6?(n(y,w.sibling),w=o(w,v),w.return=y,y=w):(n(y,w),w=Ene(v,y.mode,x),w.return=y,y=w),s(y)):n(y,w)}return g}var yk=DRe(!0),$Re=DRe(!1),PF={},gg=_b(PF),wF=_b(PF),vF=_b(PF);function iT(t){if(t===PF)throw Error(Be(174));return t}function Kre(t,e){switch(Do(vF,e),Do(wF,t),Do(gg,PF),t=e.nodeType,t){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:Une(null,"");break;default:t=t===8?e.parentNode:e,e=t.namespaceURI||null,t=t.tagName,e=Une(e,t)}Go(gg),Do(gg,e)}function wk(){Go(gg),Go(wF),Go(vF)}function FRe(t){iT(vF.current);var e=iT(gg.current),n=Une(e,t.type);e!==n&&(Do(wF,t),Do(gg,n))}function qre(t){wF.current===t&&(Go(gg),Go(wF))}var Ci=_b(0);function JH(t){for(var e=t;e!==null;){if(e.tag===13){var n=e.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if((e.flags&128)!==0)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break;for(;e.sibling===null;){if(e.return===null||e.return===t)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var Cne=[];function Gre(){for(var t=0;t<Cne.length;t++)Cne[t]._workInProgressVersionPrimary=null;Cne.length=0}var AH=yw.ReactCurrentDispatcher,_ne=yw.ReactCurrentBatchConfig,uT=0,_i=null,Us=null,Ma=null,XH=!1,rF=!1,xF=0,F_t=0;function Yl(){throw Error(Be(321))}function Yre(t,e){if(e===null)return!1;for(var n=0;n<e.length&&n<t.length;n++)if(!Mm(t[n],e[n]))return!1;return!0}function Zre(t,e,n,r,o,i){if(uT=i,_i=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,AH.current=t===null||t.memoizedState===null?j_t:V_t,t=n(r,o),rF){i=0;do{if(rF=!1,xF=0,25<=i)throw Error(Be(301));i+=1,Ma=Us=null,e.updateQueue=null,AH.current=W_t,t=n(r,o)}while(rF)}if(AH.current=QH,e=Us!==null&&Us.next!==null,uT=0,Ma=Us=_i=null,XH=!1,e)throw Error(Be(300));return t}function Jre(){var t=xF!==0;return xF=0,t}function pg(){var t={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Ma===null?_i.memoizedState=Ma=t:Ma=Ma.next=t,Ma}function Gf(){if(Us===null){var t=_i.alternate;t=t!==null?t.memoizedState:null}else t=Us.next;var e=Ma===null?_i.memoizedState:Ma.next;if(e!==null)Ma=e,Us=t;else{if(t===null)throw Error(Be(310));Us=t,t={memoizedState:Us.memoizedState,baseState:Us.baseState,baseQueue:Us.baseQueue,queue:Us.queue,next:null},Ma===null?_i.memoizedState=Ma=t:Ma=Ma.next=t}return Ma}function bF(t,e){return typeof e=="function"?e(t):e}function Sne(t){var e=Gf(),n=e.queue;if(n===null)throw Error(Be(311));n.lastRenderedReducer=t;var r=Us,o=r.baseQueue,i=n.pending;if(i!==null){if(o!==null){var s=o.next;o.next=i.next,i.next=s}r.baseQueue=o=i,n.pending=null}if(o!==null){i=o.next,r=r.baseState;var a=s=null,l=null,c=i;do{var u=c.lane;if((uT&u)===u)l!==null&&(l=l.next={lane:0,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null}),r=c.hasEagerState?c.eagerState:t(r,c.action);else{var d={lane:u,action:c.action,hasEagerState:c.hasEagerState,eagerState:c.eagerState,next:null};l===null?(a=l=d,s=r):l=l.next=d,_i.lanes|=u,dT|=u}c=c.next}while(c!==null&&c!==i);l===null?s=r:l.next=a,Mm(r,e.memoizedState)||(Mu=!0),e.memoizedState=r,e.baseState=s,e.baseQueue=l,n.lastRenderedState=r}if(t=n.interleaved,t!==null){o=t;do i=o.lane,_i.lanes|=i,dT|=i,o=o.next;while(o!==t)}else o===null&&(n.lanes=0);return[e.memoizedState,n.dispatch]}function Tne(t){var e=Gf(),n=e.queue;if(n===null)throw Error(Be(311));n.lastRenderedReducer=t;var r=n.dispatch,o=n.pending,i=e.memoizedState;if(o!==null){n.pending=null;var s=o=o.next;do i=t(i,s.action),s=s.next;while(s!==o);Mm(i,e.memoizedState)||(Mu=!0),e.memoizedState=i,e.baseQueue===null&&(e.baseState=i),n.lastRenderedState=i}return[i,r]}function URe(){}function BRe(t,e){var n=_i,r=Gf(),o=e(),i=!Mm(r.memoizedState,o);if(i&&(r.memoizedState=o,Mu=!0),r=r.queue,Xre(VRe.bind(null,n,r,t),[t]),r.getSnapshot!==e||i||Ma!==null&&Ma.memoizedState.tag&1){if(n.flags|=2048,CF(9,jRe.bind(null,n,r,o,e),void 0,null),Na===null)throw Error(Be(349));(uT&30)!==0||zRe(n,e,o)}return o}function zRe(t,e,n){t.flags|=16384,t={getSnapshot:e,value:n},e=_i.updateQueue,e===null?(e={lastEffect:null,stores:null},_i.updateQueue=e,e.stores=[t]):(n=e.stores,n===null?e.stores=[t]:n.push(t))}function jRe(t,e,n,r){e.value=n,e.getSnapshot=r,WRe(e)&&HRe(t)}function VRe(t,e,n){return n(function(){WRe(e)&&HRe(t)})}function WRe(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!Mm(t,n)}catch{return!0}}function HRe(t){var e=hw(t,1);e!==null&&km(e,t,1,-1)}function fOe(t){var e=pg();return typeof t=="function"&&(t=t()),e.memoizedState=e.baseState=t,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:bF,lastRenderedState:t},e.queue=t,t=t.dispatch=z_t.bind(null,_i,t),[e.memoizedState,t]}function CF(t,e,n,r){return t={tag:t,create:e,destroy:n,deps:r,next:null},e=_i.updateQueue,e===null?(e={lastEffect:null,stores:null},_i.updateQueue=e,e.lastEffect=t.next=t):(n=e.lastEffect,n===null?e.lastEffect=t.next=t:(r=n.next,n.next=t,t.next=r,e.lastEffect=t)),t}function KRe(){return Gf().memoizedState}function kH(t,e,n,r){var o=pg();_i.flags|=t,o.memoizedState=CF(1|e,n,void 0,r===void 0?null:r)}function f6(t,e,n,r){var o=Gf();r=r===void 0?null:r;var i=void 0;if(Us!==null){var s=Us.memoizedState;if(i=s.destroy,r!==null&&Yre(r,s.deps)){o.memoizedState=CF(e,n,i,r);return}}_i.flags|=t,o.memoizedState=CF(1|e,n,i,r)}function pOe(t,e){return kH(8390656,8,t,e)}function Xre(t,e){return f6(2048,8,t,e)}function qRe(t,e){return f6(4,2,t,e)}function GRe(t,e){return f6(4,4,t,e)}function YRe(t,e){if(typeof e=="function")return t=t(),e(t),function(){e(null)};if(e!=null)return t=t(),e.current=t,function(){e.current=null}}function ZRe(t,e,n){return n=n!=null?n.concat([t]):null,f6(4,4,YRe.bind(null,e,t),n)}function Qre(){}function JRe(t,e){var n=Gf();e=e===void 0?null:e;var r=n.memoizedState;return r!==null&&e!==null&&Yre(e,r[1])?r[0]:(n.memoizedState=[t,e],t)}function XRe(t,e){var n=Gf();e=e===void 0?null:e;var r=n.memoizedState;return r!==null&&e!==null&&Yre(e,r[1])?r[0]:(t=t(),n.memoizedState=[t,e],t)}function QRe(t,e,n){return(uT&21)===0?(t.baseState&&(t.baseState=!1,Mu=!0),t.memoizedState=n):(Mm(n,e)||(n=nRe(),_i.lanes|=n,dT|=n,t.baseState=!0),e)}function U_t(t,e){var n=po;po=n!==0&&4>n?n:4,t(!0);var r=_ne.transition;_ne.transition={};try{t(!1),e()}finally{po=n,_ne.transition=r}}function eLe(){return Gf().memoizedState}function B_t(t,e,n){var r=wb(t);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},tLe(t))nLe(e,n);else if(n=NRe(t,e,n,r),n!==null){var o=$c();km(n,t,r,o),rLe(n,e,r)}}function z_t(t,e,n){var r=wb(t),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(tLe(t))nLe(e,o);else{var i=t.alternate;if(t.lanes===0&&(i===null||i.lanes===0)&&(i=e.lastRenderedReducer,i!==null))try{var s=e.lastRenderedState,a=i(s,n);if(o.hasEagerState=!0,o.eagerState=a,Mm(a,s)){var l=e.interleaved;l===null?(o.next=o,Wre(e)):(o.next=l.next,l.next=o),e.interleaved=o;return}}catch{}finally{}n=NRe(t,e,o,r),n!==null&&(o=$c(),km(n,t,r,o),rLe(n,e,r))}}function tLe(t){var e=t.alternate;return t===_i||e!==null&&e===_i}function nLe(t,e){rF=XH=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function rLe(t,e,n){if((n&4194240)!==0){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,kre(t,n)}}var QH={readContext:qf,useCallback:Yl,useContext:Yl,useEffect:Yl,useImperativeHandle:Yl,useInsertionEffect:Yl,useLayoutEffect:Yl,useMemo:Yl,useReducer:Yl,useRef:Yl,useState:Yl,useDebugValue:Yl,useDeferredValue:Yl,useTransition:Yl,useMutableSource:Yl,useSyncExternalStore:Yl,useId:Yl,unstable_isNewReconciler:!1},j_t={readContext:qf,useCallback:function(t,e){return pg().memoizedState=[t,e===void 0?null:e],t},useContext:qf,useEffect:pOe,useImperativeHandle:function(t,e,n){return n=n!=null?n.concat([t]):null,kH(4194308,4,YRe.bind(null,e,t),n)},useLayoutEffect:function(t,e){return kH(4194308,4,t,e)},useInsertionEffect:function(t,e){return kH(4,2,t,e)},useMemo:function(t,e){var n=pg();return e=e===void 0?null:e,t=t(),n.memoizedState=[t,e],t},useReducer:function(t,e,n){var r=pg();return e=n!==void 0?n(e):e,r.memoizedState=r.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},r.queue=t,t=t.dispatch=B_t.bind(null,_i,t),[r.memoizedState,t]},useRef:function(t){var e=pg();return t={current:t},e.memoizedState=t},useState:fOe,useDebugValue:Qre,useDeferredValue:function(t){return pg().memoizedState=t},useTransition:function(){var t=fOe(!1),e=t[0];return t=U_t.bind(null,t[1]),pg().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,n){var r=_i,o=pg();if(li){if(n===void 0)throw Error(Be(407));n=n()}else{if(n=e(),Na===null)throw Error(Be(349));(uT&30)!==0||zRe(r,e,n)}o.memoizedState=n;var i={value:n,getSnapshot:e};return o.queue=i,pOe(VRe.bind(null,r,i,t),[t]),r.flags|=2048,CF(9,jRe.bind(null,r,i,n,e),void 0,null),n},useId:function(){var t=pg(),e=Na.identifierPrefix;if(li){var n=dw,r=uw;n=(r&~(1<<32-Am(r)-1)).toString(32)+n,e=":"+e+"R"+n,n=xF++,0<n&&(e+="H"+n.toString(32)),e+=":"}else n=F_t++,e=":"+e+"r"+n.toString(32)+":";return t.memoizedState=e},unstable_isNewReconciler:!1},V_t={readContext:qf,useCallback:JRe,useContext:qf,useEffect:Xre,useImperativeHandle:ZRe,useInsertionEffect:qRe,useLayoutEffect:GRe,useMemo:XRe,useReducer:Sne,useRef:KRe,useState:function(){return Sne(bF)},useDebugValue:Qre,useDeferredValue:function(t){var e=Gf();return QRe(e,Us.memoizedState,t)},useTransition:function(){var t=Sne(bF)[0],e=Gf().memoizedState;return[t,e]},useMutableSource:URe,useSyncExternalStore:BRe,useId:eLe,unstable_isNewReconciler:!1},W_t={readContext:qf,useCallback:JRe,useContext:qf,useEffect:Xre,useImperativeHandle:ZRe,useInsertionEffect:qRe,useLayoutEffect:GRe,useMemo:XRe,useReducer:Tne,useRef:KRe,useState:function(){return Tne(bF)},useDebugValue:Qre,useDeferredValue:function(t){var e=Gf();return Us===null?e.memoizedState=t:QRe(e,Us.memoizedState,t)},useTransition:function(){var t=Tne(bF)[0],e=Gf().memoizedState;return[t,e]},useMutableSource:URe,useSyncExternalStore:BRe,useId:eLe,unstable_isNewReconciler:!1};function vk(t,e){try{var n="",r=e;do n+=xCt(r),r=r.return;while(r);var o=n}catch(i){o=`
Error generating stack: `+i.message+`
`+i.stack}return{value:t,source:e,stack:o,digest:null}}function Ine(t,e,n){return{value:t,source:null,stack:n??null,digest:e??null}}function lre(t,e){try{console.error(e.value)}catch(n){setTimeout(function(){throw n})}}var H_t=typeof WeakMap=="function"?WeakMap:Map;function oLe(t,e,n){n=fw(-1,n),n.tag=3,n.payload={element:null};var r=e.value;return n.callback=function(){t6||(t6=!0,wre=r),lre(t,e)},n}function iLe(t,e,n){n=fw(-1,n),n.tag=3;var r=t.type.getDerivedStateFromError;if(typeof r=="function"){var o=e.value;n.payload=function(){return r(o)},n.callback=function(){lre(t,e)}}var i=t.stateNode;return i!==null&&typeof i.componentDidCatch=="function"&&(n.callback=function(){lre(t,e),typeof r!="function"&&(yb===null?yb=new Set([this]):yb.add(this));var s=e.stack;this.componentDidCatch(e.value,{componentStack:s!==null?s:""})}),n}function mOe(t,e,n){var r=t.pingCache;if(r===null){r=t.pingCache=new H_t;var o=new Set;r.set(e,o)}else o=r.get(e),o===void 0&&(o=new Set,r.set(e,o));o.has(n)||(o.add(n),t=iSt.bind(null,t,e,n),e.then(t,t))}function hOe(t){do{var e;if((e=t.tag===13)&&(e=t.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return t;t=t.return}while(t!==null);return null}function gOe(t,e,n,r,o){return(t.mode&1)===0?(t===e?t.flags|=65536:(t.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(e=fw(-1,1),e.tag=2,gb(n,e,1))),n.lanes|=1),t):(t.flags|=65536,t.lanes=o,t)}var K_t=yw.ReactCurrentOwner,Mu=!1;function Dc(t,e,n,r){e.child=t===null?$Re(e,null,n,r):yk(e,t.child,n,r)}function yOe(t,e,n,r,o){n=n.render;var i=e.ref;return fk(e,o),r=Zre(t,e,n,r,i,o),n=Jre(),t!==null&&!Mu?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,gw(t,e,o)):(li&&n&&Fre(e),e.flags|=1,Dc(t,e,r,o),e.child)}function wOe(t,e,n,r,o){if(t===null){var i=n.type;return typeof i=="function"&&!aoe(i)&&i.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(e.tag=15,e.type=i,sLe(t,e,i,r,o)):(t=RH(n.type,null,r,e,e.mode,o),t.ref=e.ref,t.return=e,e.child=t)}if(i=t.child,(t.lanes&o)===0){var s=i.memoizedProps;if(n=n.compare,n=n!==null?n:mF,n(s,r)&&t.ref===e.ref)return gw(t,e,o)}return e.flags|=1,t=vb(i,r),t.ref=e.ref,t.return=e,e.child=t}function sLe(t,e,n,r,o){if(t!==null){var i=t.memoizedProps;if(mF(i,r)&&t.ref===e.ref)if(Mu=!1,e.pendingProps=r=i,(t.lanes&o)!==0)(t.flags&131072)!==0&&(Mu=!0);else return e.lanes=t.lanes,gw(t,e,o)}return cre(t,e,n,r,o)}function aLe(t,e,n){var r=e.pendingProps,o=r.children,i=t!==null?t.memoizedState:null;if(r.mode==="hidden")if((e.mode&1)===0)e.memoizedState={baseLanes:0,cachePool:null,transitions:null},Do(ak,Od),Od|=n;else{if((n&1073741824)===0)return t=i!==null?i.baseLanes|n:n,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:t,cachePool:null,transitions:null},e.updateQueue=null,Do(ak,Od),Od|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=i!==null?i.baseLanes:n,Do(ak,Od),Od|=r}else i!==null?(r=i.baseLanes|n,e.memoizedState=null):r=n,Do(ak,Od),Od|=r;return Dc(t,e,o,n),e.child}function lLe(t,e){var n=e.ref;(t===null&&n!==null||t!==null&&t.ref!==n)&&(e.flags|=512,e.flags|=2097152)}function cre(t,e,n,r,o){var i=Ou(n)?lT:Xl.current;return i=hk(e,i),fk(e,o),n=Zre(t,e,n,r,i,o),r=Jre(),t!==null&&!Mu?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~o,gw(t,e,o)):(li&&r&&Fre(e),e.flags|=1,Dc(t,e,n,o),e.child)}function vOe(t,e,n,r,o){if(Ou(n)){var i=!0;HH(e)}else i=!1;if(fk(e,o),e.stateNode===null)MH(t,e),LRe(e,n,r),are(e,n,r,o),r=!0;else if(t===null){var s=e.stateNode,a=e.memoizedProps;s.props=a;var l=s.context,c=n.contextType;typeof c=="object"&&c!==null?c=qf(c):(c=Ou(n)?lT:Xl.current,c=hk(e,c));var u=n.getDerivedStateFromProps,d=typeof u=="function"||typeof s.getSnapshotBeforeUpdate=="function";d||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==r||l!==c)&&uOe(e,s,r,c),ab=!1;var f=e.memoizedState;s.state=f,ZH(e,r,s,o),l=e.memoizedState,a!==r||f!==l||Nu.current||ab?(typeof u=="function"&&(sre(e,n,u,r),l=e.memoizedState),(a=ab||cOe(e,n,a,r,f,l,c))?(d||typeof s.UNSAFE_componentWillMount!="function"&&typeof s.componentWillMount!="function"||(typeof s.componentWillMount=="function"&&s.componentWillMount(),typeof s.UNSAFE_componentWillMount=="function"&&s.UNSAFE_componentWillMount()),typeof s.componentDidMount=="function"&&(e.flags|=4194308)):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=r,e.memoizedState=l),s.props=r,s.state=l,s.context=c,r=a):(typeof s.componentDidMount=="function"&&(e.flags|=4194308),r=!1)}else{s=e.stateNode,ORe(t,e),a=e.memoizedProps,c=e.type===e.elementType?a:Im(e.type,a),s.props=c,d=e.pendingProps,f=s.context,l=n.contextType,typeof l=="object"&&l!==null?l=qf(l):(l=Ou(n)?lT:Xl.current,l=hk(e,l));var p=n.getDerivedStateFromProps;(u=typeof p=="function"||typeof s.getSnapshotBeforeUpdate=="function")||typeof s.UNSAFE_componentWillReceiveProps!="function"&&typeof s.componentWillReceiveProps!="function"||(a!==d||f!==l)&&uOe(e,s,r,l),ab=!1,f=e.memoizedState,s.state=f,ZH(e,r,s,o);var m=e.memoizedState;a!==d||f!==m||Nu.current||ab?(typeof p=="function"&&(sre(e,n,p,r),m=e.memoizedState),(c=ab||cOe(e,n,c,r,f,m,l)||!1)?(u||typeof s.UNSAFE_componentWillUpdate!="function"&&typeof s.componentWillUpdate!="function"||(typeof s.componentWillUpdate=="function"&&s.componentWillUpdate(r,m,l),typeof s.UNSAFE_componentWillUpdate=="function"&&s.UNSAFE_componentWillUpdate(r,m,l)),typeof s.componentDidUpdate=="function"&&(e.flags|=4),typeof s.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof s.componentDidUpdate!="function"||a===t.memoizedProps&&f===t.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===t.memoizedProps&&f===t.memoizedState||(e.flags|=1024),e.memoizedProps=r,e.memoizedState=m),s.props=r,s.state=m,s.context=l,r=c):(typeof s.componentDidUpdate!="function"||a===t.memoizedProps&&f===t.memoizedState||(e.flags|=4),typeof s.getSnapshotBeforeUpdate!="function"||a===t.memoizedProps&&f===t.memoizedState||(e.flags|=1024),r=!1)}return ure(t,e,n,r,i,o)}function ure(t,e,n,r,o,i){lLe(t,e);var s=(e.flags&128)!==0;if(!r&&!s)return o&&oOe(e,n,!1),gw(t,e,i);r=e.stateNode,K_t.current=e;var a=s&&typeof n.getDerivedStateFromError!="function"?null:r.render();return e.flags|=1,t!==null&&s?(e.child=yk(e,t.child,null,i),e.child=yk(e,null,a,i)):Dc(t,e,a,i),e.memoizedState=r.state,o&&oOe(e,n,!0),e.child}function cLe(t){var e=t.stateNode;e.pendingContext?rOe(t,e.pendingContext,e.pendingContext!==e.context):e.context&&rOe(t,e.context,!1),Kre(t,e.containerInfo)}function xOe(t,e,n,r,o){return gk(),Bre(o),e.flags|=256,Dc(t,e,n,r),e.child}var dre={dehydrated:null,treeContext:null,retryLane:0};function fre(t){return{baseLanes:t,cachePool:null,transitions:null}}function uLe(t,e,n){var r=e.pendingProps,o=Ci.current,i=!1,s=(e.flags&128)!==0,a;if((a=s)||(a=t!==null&&t.memoizedState===null?!1:(o&2)!==0),a?(i=!0,e.flags&=-129):(t===null||t.memoizedState!==null)&&(o|=1),Do(Ci,o&1),t===null)return ore(e),t=e.memoizedState,t!==null&&(t=t.dehydrated,t!==null)?((e.mode&1)===0?e.lanes=1:t.data==="$!"?e.lanes=8:e.lanes=1073741824,null):(s=r.children,t=r.fallback,i?(r=e.mode,i=e.child,s={mode:"hidden",children:s},(r&1)===0&&i!==null?(i.childLanes=0,i.pendingProps=s):i=h6(s,r,0,null),t=aT(t,r,n,null),i.return=e,t.return=e,i.sibling=t,e.child=i,e.child.memoizedState=fre(n),e.memoizedState=dre,t):eoe(e,s));if(o=t.memoizedState,o!==null&&(a=o.dehydrated,a!==null))return q_t(t,e,s,r,a,o,n);if(i){i=r.fallback,s=e.mode,o=t.child,a=o.sibling;var l={mode:"hidden",children:r.children};return(s&1)===0&&e.child!==o?(r=e.child,r.childLanes=0,r.pendingProps=l,e.deletions=null):(r=vb(o,l),r.subtreeFlags=o.subtreeFlags&14680064),a!==null?i=vb(a,i):(i=aT(i,s,n,null),i.flags|=2),i.return=e,r.return=e,r.sibling=i,e.child=r,r=i,i=e.child,s=t.child.memoizedState,s=s===null?fre(n):{baseLanes:s.baseLanes|n,cachePool:null,transitions:s.transitions},i.memoizedState=s,i.childLanes=t.childLanes&~n,e.memoizedState=dre,r}return i=t.child,t=i.sibling,r=vb(i,{mode:"visible",children:r.children}),(e.mode&1)===0&&(r.lanes=n),r.return=e,r.sibling=null,t!==null&&(n=e.deletions,n===null?(e.deletions=[t],e.flags|=16):n.push(t)),e.child=r,e.memoizedState=null,r}function eoe(t,e){return e=h6({mode:"visible",children:e},t.mode,0,null),e.return=t,t.child=e}function CH(t,e,n,r){return r!==null&&Bre(r),yk(e,t.child,null,n),t=eoe(e,e.pendingProps.children),t.flags|=2,e.memoizedState=null,t}function q_t(t,e,n,r,o,i,s){if(n)return e.flags&256?(e.flags&=-257,r=Ine(Error(Be(422))),CH(t,e,s,r)):e.memoizedState!==null?(e.child=t.child,e.flags|=128,null):(i=r.fallback,o=e.mode,r=h6({mode:"visible",children:r.children},o,0,null),i=aT(i,o,s,null),i.flags|=2,r.return=e,i.return=e,r.sibling=i,e.child=r,(e.mode&1)!==0&&yk(e,t.child,null,s),e.child.memoizedState=fre(s),e.memoizedState=dre,i);if((e.mode&1)===0)return CH(t,e,s,null);if(o.data==="$!"){if(r=o.nextSibling&&o.nextSibling.dataset,r)var a=r.dgst;return r=a,i=Error(Be(419)),r=Ine(i,r,void 0),CH(t,e,s,r)}if(a=(s&t.childLanes)!==0,Mu||a){if(r=Na,r!==null){switch(s&-s){case 4:o=2;break;case 16:o=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:o=32;break;case 536870912:o=268435456;break;default:o=0}o=(o&(r.suspendedLanes|s))!==0?0:o,o!==0&&o!==i.retryLane&&(i.retryLane=o,hw(t,o),km(r,t,o,-1))}return soe(),r=Ine(Error(Be(421))),CH(t,e,s,r)}return o.data==="$?"?(e.flags|=128,e.child=t.child,e=sSt.bind(null,t),o._reactRetry=e,null):(t=i.treeContext,Rd=hb(o.nextSibling),Ld=e,li=!0,Em=null,t!==null&&(Vf[Wf++]=uw,Vf[Wf++]=dw,Vf[Wf++]=cT,uw=t.id,dw=t.overflow,cT=e),e=eoe(e,r.children),e.flags|=4096,e)}function bOe(t,e,n){t.lanes|=e;var r=t.alternate;r!==null&&(r.lanes|=e),ire(t.return,e,n)}function Pne(t,e,n,r,o){var i=t.memoizedState;i===null?t.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:o}:(i.isBackwards=e,i.rendering=null,i.renderingStartTime=0,i.last=r,i.tail=n,i.tailMode=o)}function dLe(t,e,n){var r=e.pendingProps,o=r.revealOrder,i=r.tail;if(Dc(t,e,r.children,n),r=Ci.current,(r&2)!==0)r=r&1|2,e.flags|=128;else{if(t!==null&&(t.flags&128)!==0)e:for(t=e.child;t!==null;){if(t.tag===13)t.memoizedState!==null&&bOe(t,n,e);else if(t.tag===19)bOe(t,n,e);else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break e;for(;t.sibling===null;){if(t.return===null||t.return===e)break e;t=t.return}t.sibling.return=t.return,t=t.sibling}r&=1}if(Do(Ci,r),(e.mode&1)===0)e.memoizedState=null;else switch(o){case"forwards":for(n=e.child,o=null;n!==null;)t=n.alternate,t!==null&&JH(t)===null&&(o=n),n=n.sibling;n=o,n===null?(o=e.child,e.child=null):(o=n.sibling,n.sibling=null),Pne(e,!1,o,n,i);break;case"backwards":for(n=null,o=e.child,e.child=null;o!==null;){if(t=o.alternate,t!==null&&JH(t)===null){e.child=o;break}t=o.sibling,o.sibling=n,n=o,o=t}Pne(e,!0,n,null,i);break;case"together":Pne(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function MH(t,e){(e.mode&1)===0&&t!==null&&(t.alternate=null,e.alternate=null,e.flags|=2)}function gw(t,e,n){if(t!==null&&(e.dependencies=t.dependencies),dT|=e.lanes,(n&e.childLanes)===0)return null;if(t!==null&&e.child!==t.child)throw Error(Be(153));if(e.child!==null){for(t=e.child,n=vb(t,t.pendingProps),e.child=n,n.return=e;t.sibling!==null;)t=t.sibling,n=n.sibling=vb(t,t.pendingProps),n.return=e;n.sibling=null}return e.child}function G_t(t,e,n){switch(e.tag){case 3:cLe(e),gk();break;case 5:FRe(e);break;case 1:Ou(e.type)&&HH(e);break;case 4:Kre(e,e.stateNode.containerInfo);break;case 10:var r=e.type._context,o=e.memoizedProps.value;Do(GH,r._currentValue),r._currentValue=o;break;case 13:if(r=e.memoizedState,r!==null)return r.dehydrated!==null?(Do(Ci,Ci.current&1),e.flags|=128,null):(n&e.child.childLanes)!==0?uLe(t,e,n):(Do(Ci,Ci.current&1),t=gw(t,e,n),t!==null?t.sibling:null);Do(Ci,Ci.current&1);break;case 19:if(r=(n&e.childLanes)!==0,(t.flags&128)!==0){if(r)return dLe(t,e,n);e.flags|=128}if(o=e.memoizedState,o!==null&&(o.rendering=null,o.tail=null,o.lastEffect=null),Do(Ci,Ci.current),r)break;return null;case 22:case 23:return e.lanes=0,aLe(t,e,n)}return gw(t,e,n)}var fLe,pre,pLe,mLe;fLe=function(t,e){for(var n=e.child;n!==null;){if(n.tag===5||n.tag===6)t.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};pre=function(){};pLe=function(t,e,n,r){var o=t.memoizedProps;if(o!==r){t=e.stateNode,iT(gg.current);var i=null;switch(n){case"input":o=Lne(t,o),r=Lne(t,r),i=[];break;case"select":o=Si({},o,{value:void 0}),r=Si({},r,{value:void 0}),i=[];break;case"textarea":o=Fne(t,o),r=Fne(t,r),i=[];break;default:typeof o.onClick!="function"&&typeof r.onClick=="function"&&(t.onclick=VH)}Bne(n,r);var s;n=null;for(c in o)if(!r.hasOwnProperty(c)&&o.hasOwnProperty(c)&&o[c]!=null)if(c==="style"){var a=o[c];for(s in a)a.hasOwnProperty(s)&&(n||(n={}),n[s]="")}else c!=="dangerouslySetInnerHTML"&&c!=="children"&&c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&c!=="autoFocus"&&(aF.hasOwnProperty(c)?i||(i=[]):(i=i||[]).push(c,null));for(c in r){var l=r[c];if(a=o?.[c],r.hasOwnProperty(c)&&l!==a&&(l!=null||a!=null))if(c==="style")if(a){for(s in a)!a.hasOwnProperty(s)||l&&l.hasOwnProperty(s)||(n||(n={}),n[s]="");for(s in l)l.hasOwnProperty(s)&&a[s]!==l[s]&&(n||(n={}),n[s]=l[s])}else n||(i||(i=[]),i.push(c,n)),n=l;else c==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,a=a?a.__html:void 0,l!=null&&a!==l&&(i=i||[]).push(c,l)):c==="children"?typeof l!="string"&&typeof l!="number"||(i=i||[]).push(c,""+l):c!=="suppressContentEditableWarning"&&c!=="suppressHydrationWarning"&&(aF.hasOwnProperty(c)?(l!=null&&c==="onScroll"&&qo("scroll",t),i||a===l||(i=[])):(i=i||[]).push(c,l))}n&&(i=i||[]).push("style",n);var c=i;(e.updateQueue=c)&&(e.flags|=4)}};mLe=function(t,e,n,r){n!==r&&(e.flags|=4)};function H$(t,e){if(!li)switch(t.tailMode){case"hidden":e=t.tail;for(var n=null;e!==null;)e.alternate!==null&&(n=e),e=e.sibling;n===null?t.tail=null:n.sibling=null;break;case"collapsed":n=t.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?e||t.tail===null?t.tail=null:t.tail.sibling=null:r.sibling=null}}function Zl(t){var e=t.alternate!==null&&t.alternate.child===t.child,n=0,r=0;if(e)for(var o=t.child;o!==null;)n|=o.lanes|o.childLanes,r|=o.subtreeFlags&14680064,r|=o.flags&14680064,o.return=t,o=o.sibling;else for(o=t.child;o!==null;)n|=o.lanes|o.childLanes,r|=o.subtreeFlags,r|=o.flags,o.return=t,o=o.sibling;return t.subtreeFlags|=r,t.childLanes=n,e}function Y_t(t,e,n){var r=e.pendingProps;switch(Ure(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Zl(e),null;case 1:return Ou(e.type)&&WH(),Zl(e),null;case 3:return r=e.stateNode,wk(),Go(Nu),Go(Xl),Gre(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(t===null||t.child===null)&&(xH(e)?e.flags|=4:t===null||t.memoizedState.isDehydrated&&(e.flags&256)===0||(e.flags|=1024,Em!==null&&(bre(Em),Em=null))),pre(t,e),Zl(e),null;case 5:qre(e);var o=iT(vF.current);if(n=e.type,t!==null&&e.stateNode!=null)pLe(t,e,n,r,o),t.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!r){if(e.stateNode===null)throw Error(Be(166));return Zl(e),null}if(t=iT(gg.current),xH(e)){r=e.stateNode,n=e.type;var i=e.memoizedProps;switch(r[mg]=e,r[yF]=i,t=(e.mode&1)!==0,n){case"dialog":qo("cancel",r),qo("close",r);break;case"iframe":case"object":case"embed":qo("load",r);break;case"video":case"audio":for(o=0;o<J$.length;o++)qo(J$[o],r);break;case"source":qo("error",r);break;case"img":case"image":case"link":qo("error",r),qo("load",r);break;case"details":qo("toggle",r);break;case"input":ANe(r,i),qo("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!i.multiple},qo("invalid",r);break;case"textarea":MNe(r,i),qo("invalid",r)}Bne(n,i),o=null;for(var s in i)if(i.hasOwnProperty(s)){var a=i[s];s==="children"?typeof a=="string"?r.textContent!==a&&(i.suppressHydrationWarning!==!0&&vH(r.textContent,a,t),o=["children",a]):typeof a=="number"&&r.textContent!==""+a&&(i.suppressHydrationWarning!==!0&&vH(r.textContent,a,t),o=["children",""+a]):aF.hasOwnProperty(s)&&a!=null&&s==="onScroll"&&qo("scroll",r)}switch(n){case"input":aH(r),kNe(r,i,!0);break;case"textarea":aH(r),NNe(r);break;case"select":case"option":break;default:typeof i.onClick=="function"&&(r.onclick=VH)}r=o,e.updateQueue=r,r!==null&&(e.flags|=4)}else{s=o.nodeType===9?o:o.ownerDocument,t==="http://www.w3.org/1999/xhtml"&&(t=zOe(n)),t==="http://www.w3.org/1999/xhtml"?n==="script"?(t=s.createElement("div"),t.innerHTML="<script><\/script>",t=t.removeChild(t.firstChild)):typeof r.is=="string"?t=s.createElement(n,{is:r.is}):(t=s.createElement(n),n==="select"&&(s=t,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):t=s.createElementNS(t,n),t[mg]=e,t[yF]=r,fLe(t,e,!1,!1),e.stateNode=t;e:{switch(s=zne(n,r),n){case"dialog":qo("cancel",t),qo("close",t),o=r;break;case"iframe":case"object":case"embed":qo("load",t),o=r;break;case"video":case"audio":for(o=0;o<J$.length;o++)qo(J$[o],t);o=r;break;case"source":qo("error",t),o=r;break;case"img":case"image":case"link":qo("error",t),qo("load",t),o=r;break;case"details":qo("toggle",t),o=r;break;case"input":ANe(t,r),o=Lne(t,r),qo("invalid",t);break;case"option":o=r;break;case"select":t._wrapperState={wasMultiple:!!r.multiple},o=Si({},r,{value:void 0}),qo("invalid",t);break;case"textarea":MNe(t,r),o=Fne(t,r),qo("invalid",t);break;default:o=r}Bne(n,o),a=o;for(i in a)if(a.hasOwnProperty(i)){var l=a[i];i==="style"?WOe(t,l):i==="dangerouslySetInnerHTML"?(l=l?l.__html:void 0,l!=null&&jOe(t,l)):i==="children"?typeof l=="string"?(n!=="textarea"||l!=="")&&lF(t,l):typeof l=="number"&&lF(t,""+l):i!=="suppressContentEditableWarning"&&i!=="suppressHydrationWarning"&&i!=="autoFocus"&&(aF.hasOwnProperty(i)?l!=null&&i==="onScroll"&&qo("scroll",t):l!=null&&Sre(t,i,l,s))}switch(n){case"input":aH(t),kNe(t,r,!1);break;case"textarea":aH(t),NNe(t);break;case"option":r.value!=null&&t.setAttribute("value",""+xb(r.value));break;case"select":t.multiple=!!r.multiple,i=r.value,i!=null?lk(t,!!r.multiple,i,!1):r.defaultValue!=null&&lk(t,!!r.multiple,r.defaultValue,!0);break;default:typeof o.onClick=="function"&&(t.onclick=VH)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return Zl(e),null;case 6:if(t&&e.stateNode!=null)mLe(t,e,t.memoizedProps,r);else{if(typeof r!="string"&&e.stateNode===null)throw Error(Be(166));if(n=iT(vF.current),iT(gg.current),xH(e)){if(r=e.stateNode,n=e.memoizedProps,r[mg]=e,(i=r.nodeValue!==n)&&(t=Ld,t!==null))switch(t.tag){case 3:vH(r.nodeValue,n,(t.mode&1)!==0);break;case 5:t.memoizedProps.suppressHydrationWarning!==!0&&vH(r.nodeValue,n,(t.mode&1)!==0)}i&&(e.flags|=4)}else r=(n.nodeType===9?n:n.ownerDocument).createTextNode(r),r[mg]=e,e.stateNode=r}return Zl(e),null;case 13:if(Go(Ci),r=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(li&&Rd!==null&&(e.mode&1)!==0&&(e.flags&128)===0)MRe(),gk(),e.flags|=98560,i=!1;else if(i=xH(e),r!==null&&r.dehydrated!==null){if(t===null){if(!i)throw Error(Be(318));if(i=e.memoizedState,i=i!==null?i.dehydrated:null,!i)throw Error(Be(317));i[mg]=e}else gk(),(e.flags&128)===0&&(e.memoizedState=null),e.flags|=4;Zl(e),i=!1}else Em!==null&&(bre(Em),Em=null),i=!0;if(!i)return e.flags&65536?e:null}return(e.flags&128)!==0?(e.lanes=n,e):(r=r!==null,r!==(t!==null&&t.memoizedState!==null)&&r&&(e.child.flags|=8192,(e.mode&1)!==0&&(t===null||(Ci.current&1)!==0?Bs===0&&(Bs=3):soe())),e.updateQueue!==null&&(e.flags|=4),Zl(e),null);case 4:return wk(),pre(t,e),t===null&&hF(e.stateNode.containerInfo),Zl(e),null;case 10:return Vre(e.type._context),Zl(e),null;case 17:return Ou(e.type)&&WH(),Zl(e),null;case 19:if(Go(Ci),i=e.memoizedState,i===null)return Zl(e),null;if(r=(e.flags&128)!==0,s=i.rendering,s===null)if(r)H$(i,!1);else{if(Bs!==0||t!==null&&(t.flags&128)!==0)for(t=e.child;t!==null;){if(s=JH(t),s!==null){for(e.flags|=128,H$(i,!1),r=s.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),e.subtreeFlags=0,r=n,n=e.child;n!==null;)i=n,t=r,i.flags&=14680066,s=i.alternate,s===null?(i.childLanes=0,i.lanes=t,i.child=null,i.subtreeFlags=0,i.memoizedProps=null,i.memoizedState=null,i.updateQueue=null,i.dependencies=null,i.stateNode=null):(i.childLanes=s.childLanes,i.lanes=s.lanes,i.child=s.child,i.subtreeFlags=0,i.deletions=null,i.memoizedProps=s.memoizedProps,i.memoizedState=s.memoizedState,i.updateQueue=s.updateQueue,i.type=s.type,t=s.dependencies,i.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),n=n.sibling;return Do(Ci,Ci.current&1|2),e.child}t=t.sibling}i.tail!==null&&ts()>xk&&(e.flags|=128,r=!0,H$(i,!1),e.lanes=4194304)}else{if(!r)if(t=JH(s),t!==null){if(e.flags|=128,r=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),H$(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!li)return Zl(e),null}else 2*ts()-i.renderingStartTime>xk&&n!==1073741824&&(e.flags|=128,r=!0,H$(i,!1),e.lanes=4194304);i.isBackwards?(s.sibling=e.child,e.child=s):(n=i.last,n!==null?n.sibling=s:e.child=s,i.last=s)}return i.tail!==null?(e=i.tail,i.rendering=e,i.tail=e.sibling,i.renderingStartTime=ts(),e.sibling=null,n=Ci.current,Do(Ci,r?n&1|2:n&1),e):(Zl(e),null);case 22:case 23:return ioe(),r=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==r&&(e.flags|=8192),r&&(e.mode&1)!==0?(Od&1073741824)!==0&&(Zl(e),e.subtreeFlags&6&&(e.flags|=8192)):Zl(e),null;case 24:return null;case 25:return null}throw Error(Be(156,e.tag))}function Z_t(t,e){switch(Ure(e),e.tag){case 1:return Ou(e.type)&&WH(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return wk(),Go(Nu),Go(Xl),Gre(),t=e.flags,(t&65536)!==0&&(t&128)===0?(e.flags=t&-65537|128,e):null;case 5:return qre(e),null;case 13:if(Go(Ci),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(Be(340));gk()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Go(Ci),null;case 4:return wk(),null;case 10:return Vre(e.type._context),null;case 22:case 23:return ioe(),null;case 24:return null;default:return null}}var _H=!1,Jl=!1,J_t=typeof WeakSet=="function"?WeakSet:Set,Lt=null;function sk(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){$i(t,e,r)}else n.current=null}function mre(t,e,n){try{n()}catch(r){$i(t,e,r)}}var COe=!1;function X_t(t,e){if(Jne=BH,t=wRe(),$re(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var o=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var s=0,a=-1,l=-1,c=0,u=0,d=t,f=null;t:for(;;){for(var p;d!==n||o!==0&&d.nodeType!==3||(a=s+o),d!==i||r!==0&&d.nodeType!==3||(l=s+r),d.nodeType===3&&(s+=d.nodeValue.length),(p=d.firstChild)!==null;)f=d,d=p;for(;;){if(d===t)break t;if(f===n&&++c===o&&(a=s),f===i&&++u===r&&(l=s),(p=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=p}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(Xne={focusedElem:t,selectionRange:n},BH=!1,Lt=e;Lt!==null;)if(e=Lt,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,Lt=t;else for(;Lt!==null;){e=Lt;try{var m=e.alternate;if((e.flags&1024)!==0)switch(e.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var h=m.memoizedProps,g=m.memoizedState,y=e.stateNode,w=y.getSnapshotBeforeUpdate(e.elementType===e.type?h:Im(e.type,h),g);y.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var v=e.stateNode.containerInfo;v.nodeType===1?v.textContent="":v.nodeType===9&&v.documentElement&&v.removeChild(v.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Be(163))}}catch(x){$i(e,e.return,x)}if(t=e.sibling,t!==null){t.return=e.return,Lt=t;break}Lt=e.return}return m=COe,COe=!1,m}function oF(t,e,n){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&t)===t){var i=o.destroy;o.destroy=void 0,i!==void 0&&mre(e,n,i)}o=o.next}while(o!==r)}}function p6(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var r=n.create;n.destroy=r()}n=n.next}while(n!==e)}}function hre(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function hLe(t){var e=t.alternate;e!==null&&(t.alternate=null,hLe(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[mg],delete e[yF],delete e[tre],delete e[R_t],delete e[L_t])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function gLe(t){return t.tag===5||t.tag===3||t.tag===4}function _Oe(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||gLe(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function gre(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=VH));else if(r!==4&&(t=t.child,t!==null))for(gre(t,e,n),t=t.sibling;t!==null;)gre(t,e,n),t=t.sibling}function yre(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(t=t.child,t!==null))for(yre(t,e,n),t=t.sibling;t!==null;)yre(t,e,n),t=t.sibling}var fl=null,Pm=!1;function ib(t,e,n){for(n=n.child;n!==null;)yLe(t,e,n),n=n.sibling}function yLe(t,e,n){if(hg&&typeof hg.onCommitFiberUnmount=="function")try{hg.onCommitFiberUnmount(i6,n)}catch{}switch(n.tag){case 5:Jl||sk(n,e);case 6:var r=fl,o=Pm;fl=null,ib(t,e,n),fl=r,Pm=o,fl!==null&&(Pm?(t=fl,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):fl.removeChild(n.stateNode));break;case 18:fl!==null&&(Pm?(t=fl,n=n.stateNode,t.nodeType===8?xne(t.parentNode,n):t.nodeType===1&&xne(t,n),fF(t)):xne(fl,n.stateNode));break;case 4:r=fl,o=Pm,fl=n.stateNode.containerInfo,Pm=!0,ib(t,e,n),fl=r,Pm=o;break;case 0:case 11:case 14:case 15:if(!Jl&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){o=r=r.next;do{var i=o,s=i.destroy;i=i.tag,s!==void 0&&((i&2)!==0||(i&4)!==0)&&mre(n,e,s),o=o.next}while(o!==r)}ib(t,e,n);break;case 1:if(!Jl&&(sk(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){$i(n,e,a)}ib(t,e,n);break;case 21:ib(t,e,n);break;case 22:n.mode&1?(Jl=(r=Jl)||n.memoizedState!==null,ib(t,e,n),Jl=r):ib(t,e,n);break;default:ib(t,e,n)}}function SOe(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new J_t),e.forEach(function(r){var o=aSt.bind(null,t,r);n.has(r)||(n.add(r),r.then(o,o))})}}function Tm(t,e){var n=e.deletions;if(n!==null)for(var r=0;r<n.length;r++){var o=n[r];try{var i=t,s=e,a=s;e:for(;a!==null;){switch(a.tag){case 5:fl=a.stateNode,Pm=!1;break e;case 3:fl=a.stateNode.containerInfo,Pm=!0;break e;case 4:fl=a.stateNode.containerInfo,Pm=!0;break e}a=a.return}if(fl===null)throw Error(Be(160));yLe(i,s,o),fl=null,Pm=!1;var l=o.alternate;l!==null&&(l.return=null),o.return=null}catch(c){$i(o,e,c)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)wLe(e,t),e=e.sibling}function wLe(t,e){var n=t.alternate,r=t.flags;switch(t.tag){case 0:case 11:case 14:case 15:if(Tm(e,t),fg(t),r&4){try{oF(3,t,t.return),p6(3,t)}catch(h){$i(t,t.return,h)}try{oF(5,t,t.return)}catch(h){$i(t,t.return,h)}}break;case 1:Tm(e,t),fg(t),r&512&&n!==null&&sk(n,n.return);break;case 5:if(Tm(e,t),fg(t),r&512&&n!==null&&sk(n,n.return),t.flags&32){var o=t.stateNode;try{lF(o,"")}catch(h){$i(t,t.return,h)}}if(r&4&&(o=t.stateNode,o!=null)){var i=t.memoizedProps,s=n!==null?n.memoizedProps:i,a=t.type,l=t.updateQueue;if(t.updateQueue=null,l!==null)try{a==="input"&&i.type==="radio"&&i.name!=null&&UOe(o,i),zne(a,s);var c=zne(a,i);for(s=0;s<l.length;s+=2){var u=l[s],d=l[s+1];u==="style"?WOe(o,d):u==="dangerouslySetInnerHTML"?jOe(o,d):u==="children"?lF(o,d):Sre(o,u,d,c)}switch(a){case"input":Dne(o,i);break;case"textarea":BOe(o,i);break;case"select":var f=o._wrapperState.wasMultiple;o._wrapperState.wasMultiple=!!i.multiple;var p=i.value;p!=null?lk(o,!!i.multiple,p,!1):f!==!!i.multiple&&(i.defaultValue!=null?lk(o,!!i.multiple,i.defaultValue,!0):lk(o,!!i.multiple,i.multiple?[]:"",!1))}o[yF]=i}catch(h){$i(t,t.return,h)}}break;case 6:if(Tm(e,t),fg(t),r&4){if(t.stateNode===null)throw Error(Be(162));o=t.stateNode,i=t.memoizedProps;try{o.nodeValue=i}catch(h){$i(t,t.return,h)}}break;case 3:if(Tm(e,t),fg(t),r&4&&n!==null&&n.memoizedState.isDehydrated)try{fF(e.containerInfo)}catch(h){$i(t,t.return,h)}break;case 4:Tm(e,t),fg(t);break;case 13:Tm(e,t),fg(t),o=t.child,o.flags&8192&&(i=o.memoizedState!==null,o.stateNode.isHidden=i,!i||o.alternate!==null&&o.alternate.memoizedState!==null||(roe=ts())),r&4&&SOe(t);break;case 22:if(u=n!==null&&n.memoizedState!==null,t.mode&1?(Jl=(c=Jl)||u,Tm(e,t),Jl=c):Tm(e,t),fg(t),r&8192){if(c=t.memoizedState!==null,(t.stateNode.isHidden=c)&&!u&&(t.mode&1)!==0)for(Lt=t,u=t.child;u!==null;){for(d=Lt=u;Lt!==null;){switch(f=Lt,p=f.child,f.tag){case 0:case 11:case 14:case 15:oF(4,f,f.return);break;case 1:sk(f,f.return);var m=f.stateNode;if(typeof m.componentWillUnmount=="function"){r=f,n=f.return;try{e=r,m.props=e.memoizedProps,m.state=e.memoizedState,m.componentWillUnmount()}catch(h){$i(r,n,h)}}break;case 5:sk(f,f.return);break;case 22:if(f.memoizedState!==null){IOe(d);continue}}p!==null?(p.return=f,Lt=p):IOe(d)}u=u.sibling}e:for(u=null,d=t;;){if(d.tag===5){if(u===null){u=d;try{o=d.stateNode,c?(i=o.style,typeof i.setProperty=="function"?i.setProperty("display","none","important"):i.display="none"):(a=d.stateNode,l=d.memoizedProps.style,s=l!=null&&l.hasOwnProperty("display")?l.display:null,a.style.display=VOe("display",s))}catch(h){$i(t,t.return,h)}}}else if(d.tag===6){if(u===null)try{d.stateNode.nodeValue=c?"":d.memoizedProps}catch(h){$i(t,t.return,h)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===t)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===t)break e;for(;d.sibling===null;){if(d.return===null||d.return===t)break e;u===d&&(u=null),d=d.return}u===d&&(u=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:Tm(e,t),fg(t),r&4&&SOe(t);break;case 21:break;default:Tm(e,t),fg(t)}}function fg(t){var e=t.flags;if(e&2){try{e:{for(var n=t.return;n!==null;){if(gLe(n)){var r=n;break e}n=n.return}throw Error(Be(160))}switch(r.tag){case 5:var o=r.stateNode;r.flags&32&&(lF(o,""),r.flags&=-33);var i=_Oe(t);yre(t,i,o);break;case 3:case 4:var s=r.stateNode.containerInfo,a=_Oe(t);gre(t,a,s);break;default:throw Error(Be(161))}}catch(l){$i(t,t.return,l)}t.flags&=-3}e&4096&&(t.flags&=-4097)}function Q_t(t,e,n){Lt=t,vLe(t,e,n)}function vLe(t,e,n){for(var r=(t.mode&1)!==0;Lt!==null;){var o=Lt,i=o.child;if(o.tag===22&&r){var s=o.memoizedState!==null||_H;if(!s){var a=o.alternate,l=a!==null&&a.memoizedState!==null||Jl;a=_H;var c=Jl;if(_H=s,(Jl=l)&&!c)for(Lt=o;Lt!==null;)s=Lt,l=s.child,s.tag===22&&s.memoizedState!==null?POe(o):l!==null?(l.return=s,Lt=l):POe(o);for(;i!==null;)Lt=i,vLe(i,e,n),i=i.sibling;Lt=o,_H=a,Jl=c}TOe(t,e,n)}else(o.subtreeFlags&8772)!==0&&i!==null?(i.return=o,Lt=i):TOe(t,e,n)}}function TOe(t){for(;Lt!==null;){var e=Lt;if((e.flags&8772)!==0){var n=e.alternate;try{if((e.flags&8772)!==0)switch(e.tag){case 0:case 11:case 15:Jl||p6(5,e);break;case 1:var r=e.stateNode;if(e.flags&4&&!Jl)if(n===null)r.componentDidMount();else{var o=e.elementType===e.type?n.memoizedProps:Im(e.type,n.memoizedProps);r.componentDidUpdate(o,n.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var i=e.updateQueue;i!==null&&lOe(e,i,r);break;case 3:var s=e.updateQueue;if(s!==null){if(n=null,e.child!==null)switch(e.child.tag){case 5:n=e.child.stateNode;break;case 1:n=e.child.stateNode}lOe(e,s,n)}break;case 5:var a=e.stateNode;if(n===null&&e.flags&4){n=a;var l=e.memoizedProps;switch(e.type){case"button":case"input":case"select":case"textarea":l.autoFocus&&n.focus();break;case"img":l.src&&(n.src=l.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(e.memoizedState===null){var c=e.alternate;if(c!==null){var u=c.memoizedState;if(u!==null){var d=u.dehydrated;d!==null&&fF(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(Be(163))}Jl||e.flags&512&&hre(e)}catch(f){$i(e,e.return,f)}}if(e===t){Lt=null;break}if(n=e.sibling,n!==null){n.return=e.return,Lt=n;break}Lt=e.return}}function IOe(t){for(;Lt!==null;){var e=Lt;if(e===t){Lt=null;break}var n=e.sibling;if(n!==null){n.return=e.return,Lt=n;break}Lt=e.return}}function POe(t){for(;Lt!==null;){var e=Lt;try{switch(e.tag){case 0:case 11:case 15:var n=e.return;try{p6(4,e)}catch(l){$i(e,n,l)}break;case 1:var r=e.stateNode;if(typeof r.componentDidMount=="function"){var o=e.return;try{r.componentDidMount()}catch(l){$i(e,o,l)}}var i=e.return;try{hre(e)}catch(l){$i(e,i,l)}break;case 5:var s=e.return;try{hre(e)}catch(l){$i(e,s,l)}}}catch(l){$i(e,e.return,l)}if(e===t){Lt=null;break}var a=e.sibling;if(a!==null){a.return=e.return,Lt=a;break}Lt=e.return}}var eSt=Math.ceil,e6=yw.ReactCurrentDispatcher,toe=yw.ReactCurrentOwner,Kf=yw.ReactCurrentBatchConfig,zr=0,Na=null,ys=null,pl=0,Od=0,ak=_b(0),Bs=0,_F=null,dT=0,m6=0,noe=0,iF=null,ku=null,roe=0,xk=1/0,lw=null,t6=!1,wre=null,yb=null,SH=!1,db=null,n6=0,sF=0,vre=null,NH=-1,OH=0;function $c(){return(zr&6)!==0?ts():NH!==-1?NH:NH=ts()}function wb(t){return(t.mode&1)===0?1:(zr&2)!==0&&pl!==0?pl&-pl:$_t.transition!==null?(OH===0&&(OH=nRe()),OH):(t=po,t!==0||(t=window.event,t=t===void 0?16:cRe(t.type)),t)}function km(t,e,n,r){if(50<sF)throw sF=0,vre=null,Error(Be(185));SF(t,n,r),((zr&2)===0||t!==Na)&&(t===Na&&((zr&2)===0&&(m6|=n),Bs===4&&cb(t,pl)),Ru(t,r),n===1&&zr===0&&(e.mode&1)===0&&(xk=ts()+500,u6&&Sb()))}function Ru(t,e){var n=t.callbackNode;UCt(t,e);var r=UH(t,t===Na?pl:0);if(r===0)n!==null&&LNe(n),t.callbackNode=null,t.callbackPriority=0;else if(e=r&-r,t.callbackPriority!==e){if(n!=null&&LNe(n),e===1)t.tag===0?D_t(EOe.bind(null,t)):ERe(EOe.bind(null,t)),N_t(function(){(zr&6)===0&&Sb()}),n=null;else{switch(rRe(r)){case 1:n=Are;break;case 4:n=eRe;break;case 16:n=FH;break;case 536870912:n=tRe;break;default:n=FH}n=PLe(n,xLe.bind(null,t))}t.callbackPriority=e,t.callbackNode=n}}function xLe(t,e){if(NH=-1,OH=0,(zr&6)!==0)throw Error(Be(327));var n=t.callbackNode;if(pk()&&t.callbackNode!==n)return null;var r=UH(t,t===Na?pl:0);if(r===0)return null;if((r&30)!==0||(r&t.expiredLanes)!==0||e)e=r6(t,r);else{e=r;var o=zr;zr|=2;var i=CLe();(Na!==t||pl!==e)&&(lw=null,xk=ts()+500,sT(t,e));do try{rSt();break}catch(a){bLe(t,a)}while(!0);jre(),e6.current=i,zr=o,ys!==null?e=0:(Na=null,pl=0,e=Bs)}if(e!==0){if(e===2&&(o=Kne(t),o!==0&&(r=o,e=xre(t,o))),e===1)throw n=_F,sT(t,0),cb(t,r),Ru(t,ts()),n;if(e===6)cb(t,r);else{if(o=t.current.alternate,(r&30)===0&&!tSt(o)&&(e=r6(t,r),e===2&&(i=Kne(t),i!==0&&(r=i,e=xre(t,i))),e===1))throw n=_F,sT(t,0),cb(t,r),Ru(t,ts()),n;switch(t.finishedWork=o,t.finishedLanes=r,e){case 0:case 1:throw Error(Be(345));case 2:nT(t,ku,lw);break;case 3:if(cb(t,r),(r&130023424)===r&&(e=roe+500-ts(),10<e)){if(UH(t,0)!==0)break;if(o=t.suspendedLanes,(o&r)!==r){$c(),t.pingedLanes|=t.suspendedLanes&o;break}t.timeoutHandle=ere(nT.bind(null,t,ku,lw),e);break}nT(t,ku,lw);break;case 4:if(cb(t,r),(r&4194240)===r)break;for(e=t.eventTimes,o=-1;0<r;){var s=31-Am(r);i=1<<s,s=e[s],s>o&&(o=s),r&=~i}if(r=o,r=ts()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*eSt(r/1960))-r,10<r){t.timeoutHandle=ere(nT.bind(null,t,ku,lw),r);break}nT(t,ku,lw);break;case 5:nT(t,ku,lw);break;default:throw Error(Be(329))}}}return Ru(t,ts()),t.callbackNode===n?xLe.bind(null,t):null}function xre(t,e){var n=iF;return t.current.memoizedState.isDehydrated&&(sT(t,e).flags|=256),t=r6(t,e),t!==2&&(e=ku,ku=n,e!==null&&bre(e)),t}function bre(t){ku===null?ku=t:ku.push.apply(ku,t)}function tSt(t){for(var e=t;;){if(e.flags&16384){var n=e.updateQueue;if(n!==null&&(n=n.stores,n!==null))for(var r=0;r<n.length;r++){var o=n[r],i=o.getSnapshot;o=o.value;try{if(!Mm(i(),o))return!1}catch{return!1}}}if(n=e.child,e.subtreeFlags&16384&&n!==null)n.return=e,e=n;else{if(e===t)break;for(;e.sibling===null;){if(e.return===null||e.return===t)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function cb(t,e){for(e&=~noe,e&=~m6,t.suspendedLanes|=e,t.pingedLanes&=~e,t=t.expirationTimes;0<e;){var n=31-Am(e),r=1<<n;t[n]=-1,e&=~r}}function EOe(t){if((zr&6)!==0)throw Error(Be(327));pk();var e=UH(t,0);if((e&1)===0)return Ru(t,ts()),null;var n=r6(t,e);if(t.tag!==0&&n===2){var r=Kne(t);r!==0&&(e=r,n=xre(t,r))}if(n===1)throw n=_F,sT(t,0),cb(t,e),Ru(t,ts()),n;if(n===6)throw Error(Be(345));return t.finishedWork=t.current.alternate,t.finishedLanes=e,nT(t,ku,lw),Ru(t,ts()),null}function ooe(t,e){var n=zr;zr|=1;try{return t(e)}finally{zr=n,zr===0&&(xk=ts()+500,u6&&Sb())}}function fT(t){db!==null&&db.tag===0&&(zr&6)===0&&pk();var e=zr;zr|=1;var n=Kf.transition,r=po;try{if(Kf.transition=null,po=1,t)return t()}finally{po=r,Kf.transition=n,zr=e,(zr&6)===0&&Sb()}}function ioe(){Od=ak.current,Go(ak)}function sT(t,e){t.finishedWork=null,t.finishedLanes=0;var n=t.timeoutHandle;if(n!==-1&&(t.timeoutHandle=-1,M_t(n)),ys!==null)for(n=ys.return;n!==null;){var r=n;switch(Ure(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&WH();break;case 3:wk(),Go(Nu),Go(Xl),Gre();break;case 5:qre(r);break;case 4:wk();break;case 13:Go(Ci);break;case 19:Go(Ci);break;case 10:Vre(r.type._context);break;case 22:case 23:ioe()}n=n.return}if(Na=t,ys=t=vb(t.current,null),pl=Od=e,Bs=0,_F=null,noe=m6=dT=0,ku=iF=null,oT!==null){for(e=0;e<oT.length;e++)if(n=oT[e],r=n.interleaved,r!==null){n.interleaved=null;var o=r.next,i=n.pending;if(i!==null){var s=i.next;i.next=o,r.next=s}n.pending=r}oT=null}return t}function bLe(t,e){do{var n=ys;try{if(jre(),AH.current=QH,XH){for(var r=_i.memoizedState;r!==null;){var o=r.queue;o!==null&&(o.pending=null),r=r.next}XH=!1}if(uT=0,Ma=Us=_i=null,rF=!1,xF=0,toe.current=null,n===null||n.return===null){Bs=1,_F=e,ys=null;break}e:{var i=t,s=n.return,a=n,l=e;if(e=pl,a.flags|=32768,l!==null&&typeof l=="object"&&typeof l.then=="function"){var c=l,u=a,d=u.tag;if((u.mode&1)===0&&(d===0||d===11||d===15)){var f=u.alternate;f?(u.updateQueue=f.updateQueue,u.memoizedState=f.memoizedState,u.lanes=f.lanes):(u.updateQueue=null,u.memoizedState=null)}var p=hOe(s);if(p!==null){p.flags&=-257,gOe(p,s,a,i,e),p.mode&1&&mOe(i,c,e),e=p,l=c;var m=e.updateQueue;if(m===null){var h=new Set;h.add(l),e.updateQueue=h}else m.add(l);break e}else{if((e&1)===0){mOe(i,c,e),soe();break e}l=Error(Be(426))}}else if(li&&a.mode&1){var g=hOe(s);if(g!==null){(g.flags&65536)===0&&(g.flags|=256),gOe(g,s,a,i,e),Bre(vk(l,a));break e}}i=l=vk(l,a),Bs!==4&&(Bs=2),iF===null?iF=[i]:iF.push(i),i=s;do{switch(i.tag){case 3:i.flags|=65536,e&=-e,i.lanes|=e;var y=oLe(i,l,e);aOe(i,y);break e;case 1:a=l;var w=i.type,v=i.stateNode;if((i.flags&128)===0&&(typeof w.getDerivedStateFromError=="function"||v!==null&&typeof v.componentDidCatch=="function"&&(yb===null||!yb.has(v)))){i.flags|=65536,e&=-e,i.lanes|=e;var x=iLe(i,a,e);aOe(i,x);break e}}i=i.return}while(i!==null)}SLe(n)}catch(b){e=b,ys===n&&n!==null&&(ys=n=n.return);continue}break}while(!0)}function CLe(){var t=e6.current;return e6.current=QH,t===null?QH:t}function soe(){(Bs===0||Bs===3||Bs===2)&&(Bs=4),Na===null||(dT&268435455)===0&&(m6&268435455)===0||cb(Na,pl)}function r6(t,e){var n=zr;zr|=2;var r=CLe();(Na!==t||pl!==e)&&(lw=null,sT(t,e));do try{nSt();break}catch(o){bLe(t,o)}while(!0);if(jre(),zr=n,e6.current=r,ys!==null)throw Error(Be(261));return Na=null,pl=0,Bs}function nSt(){for(;ys!==null;)_Le(ys)}function rSt(){for(;ys!==null&&!kCt();)_Le(ys)}function _Le(t){var e=ILe(t.alternate,t,Od);t.memoizedProps=t.pendingProps,e===null?SLe(t):ys=e,toe.current=null}function SLe(t){var e=t;do{var n=e.alternate;if(t=e.return,(e.flags&32768)===0){if(n=Y_t(n,e,Od),n!==null){ys=n;return}}else{if(n=Z_t(n,e),n!==null){n.flags&=32767,ys=n;return}if(t!==null)t.flags|=32768,t.subtreeFlags=0,t.deletions=null;else{Bs=6,ys=null;return}}if(e=e.sibling,e!==null){ys=e;return}ys=e=t}while(e!==null);Bs===0&&(Bs=5)}function nT(t,e,n){var r=po,o=Kf.transition;try{Kf.transition=null,po=1,oSt(t,e,n,r)}finally{Kf.transition=o,po=r}return null}function oSt(t,e,n,r){do pk();while(db!==null);if((zr&6)!==0)throw Error(Be(327));n=t.finishedWork;var o=t.finishedLanes;if(n===null)return null;if(t.finishedWork=null,t.finishedLanes=0,n===t.current)throw Error(Be(177));t.callbackNode=null,t.callbackPriority=0;var i=n.lanes|n.childLanes;if(BCt(t,i),t===Na&&(ys=Na=null,pl=0),(n.subtreeFlags&2064)===0&&(n.flags&2064)===0||SH||(SH=!0,PLe(FH,function(){return pk(),null})),i=(n.flags&15990)!==0,(n.subtreeFlags&15990)!==0||i){i=Kf.transition,Kf.transition=null;var s=po;po=1;var a=zr;zr|=4,toe.current=null,X_t(t,n),wLe(n,t),I_t(Xne),BH=!!Jne,Xne=Jne=null,t.current=n,Q_t(n,t,o),MCt(),zr=a,po=s,Kf.transition=i}else t.current=n;if(SH&&(SH=!1,db=t,n6=o),i=t.pendingLanes,i===0&&(yb=null),RCt(n.stateNode,r),Ru(t,ts()),e!==null)for(r=t.onRecoverableError,n=0;n<e.length;n++)o=e[n],r(o.value,{componentStack:o.stack,digest:o.digest});if(t6)throw t6=!1,t=wre,wre=null,t;return(n6&1)!==0&&t.tag!==0&&pk(),i=t.pendingLanes,(i&1)!==0?t===vre?sF++:(sF=0,vre=t):sF=0,Sb(),null}function pk(){if(db!==null){var t=rRe(n6),e=Kf.transition,n=po;try{if(Kf.transition=null,po=16>t?16:t,db===null)var r=!1;else{if(t=db,db=null,n6=0,(zr&6)!==0)throw Error(Be(331));var o=zr;for(zr|=4,Lt=t.current;Lt!==null;){var i=Lt,s=i.child;if((Lt.flags&16)!==0){var a=i.deletions;if(a!==null){for(var l=0;l<a.length;l++){var c=a[l];for(Lt=c;Lt!==null;){var u=Lt;switch(u.tag){case 0:case 11:case 15:oF(8,u,i)}var d=u.child;if(d!==null)d.return=u,Lt=d;else for(;Lt!==null;){u=Lt;var f=u.sibling,p=u.return;if(hLe(u),u===c){Lt=null;break}if(f!==null){f.return=p,Lt=f;break}Lt=p}}}var m=i.alternate;if(m!==null){var h=m.child;if(h!==null){m.child=null;do{var g=h.sibling;h.sibling=null,h=g}while(h!==null)}}Lt=i}}if((i.subtreeFlags&2064)!==0&&s!==null)s.return=i,Lt=s;else e:for(;Lt!==null;){if(i=Lt,(i.flags&2048)!==0)switch(i.tag){case 0:case 11:case 15:oF(9,i,i.return)}var y=i.sibling;if(y!==null){y.return=i.return,Lt=y;break e}Lt=i.return}}var w=t.current;for(Lt=w;Lt!==null;){s=Lt;var v=s.child;if((s.subtreeFlags&2064)!==0&&v!==null)v.return=s,Lt=v;else e:for(s=w;Lt!==null;){if(a=Lt,(a.flags&2048)!==0)try{switch(a.tag){case 0:case 11:case 15:p6(9,a)}}catch(b){$i(a,a.return,b)}if(a===s){Lt=null;break e}var x=a.sibling;if(x!==null){x.return=a.return,Lt=x;break e}Lt=a.return}}if(zr=o,Sb(),hg&&typeof hg.onPostCommitFiberRoot=="function")try{hg.onPostCommitFiberRoot(i6,t)}catch{}r=!0}return r}finally{po=n,Kf.transition=e}}return!1}function AOe(t,e,n){e=vk(n,e),e=oLe(t,e,1),t=gb(t,e,1),e=$c(),t!==null&&(SF(t,1,e),Ru(t,e))}function $i(t,e,n){if(t.tag===3)AOe(t,t,n);else for(;e!==null;){if(e.tag===3){AOe(e,t,n);break}else if(e.tag===1){var r=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(yb===null||!yb.has(r))){t=vk(n,t),t=iLe(e,t,1),e=gb(e,t,1),t=$c(),e!==null&&(SF(e,1,t),Ru(e,t));break}}e=e.return}}function iSt(t,e,n){var r=t.pingCache;r!==null&&r.delete(e),e=$c(),t.pingedLanes|=t.suspendedLanes&n,Na===t&&(pl&n)===n&&(Bs===4||Bs===3&&(pl&130023424)===pl&&500>ts()-roe?sT(t,0):noe|=n),Ru(t,e)}function TLe(t,e){e===0&&((t.mode&1)===0?e=1:(e=uH,uH<<=1,(uH&130023424)===0&&(uH=4194304)));var n=$c();t=hw(t,e),t!==null&&(SF(t,e,n),Ru(t,n))}function sSt(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),TLe(t,n)}function aSt(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,o=t.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=t.stateNode;break;default:throw Error(Be(314))}r!==null&&r.delete(e),TLe(t,n)}var ILe;ILe=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||Nu.current)Mu=!0;else{if((t.lanes&n)===0&&(e.flags&128)===0)return Mu=!1,G_t(t,e,n);Mu=(t.flags&131072)!==0}else Mu=!1,li&&(e.flags&1048576)!==0&&ARe(e,qH,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;MH(t,e),t=e.pendingProps;var o=hk(e,Xl.current);fk(e,n),o=Zre(null,e,r,t,o,n);var i=Jre();return e.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,Ou(r)?(i=!0,HH(e)):i=!1,e.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Hre(e),o.updater=d6,e.stateNode=o,o._reactInternals=e,are(e,r,t,n),e=ure(null,e,r,!0,i,n)):(e.tag=0,li&&i&&Fre(e),Dc(null,e,o,n),e=e.child),e;case 16:r=e.elementType;e:{switch(MH(t,e),t=e.pendingProps,o=r._init,r=o(r._payload),e.type=r,o=e.tag=cSt(r),t=Im(r,t),o){case 0:e=cre(null,e,r,t,n);break e;case 1:e=vOe(null,e,r,t,n);break e;case 11:e=yOe(null,e,r,t,n);break e;case 14:e=wOe(null,e,r,Im(r.type,t),n);break e}throw Error(Be(306,r,""))}return e;case 0:return r=e.type,o=e.pendingProps,o=e.elementType===r?o:Im(r,o),cre(t,e,r,o,n);case 1:return r=e.type,o=e.pendingProps,o=e.elementType===r?o:Im(r,o),vOe(t,e,r,o,n);case 3:e:{if(cLe(e),t===null)throw Error(Be(387));r=e.pendingProps,i=e.memoizedState,o=i.element,ORe(t,e),ZH(e,r,null,n);var s=e.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},e.updateQueue.baseState=i,e.memoizedState=i,e.flags&256){o=vk(Error(Be(423)),e),e=xOe(t,e,r,n,o);break e}else if(r!==o){o=vk(Error(Be(424)),e),e=xOe(t,e,r,n,o);break e}else for(Rd=hb(e.stateNode.containerInfo.firstChild),Ld=e,li=!0,Em=null,n=$Re(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(gk(),r===o){e=gw(t,e,n);break e}Dc(t,e,r,n)}e=e.child}return e;case 5:return FRe(e),t===null&&ore(e),r=e.type,o=e.pendingProps,i=t!==null?t.memoizedProps:null,s=o.children,Qne(r,o)?s=null:i!==null&&Qne(r,i)&&(e.flags|=32),lLe(t,e),Dc(t,e,s,n),e.child;case 6:return t===null&&ore(e),null;case 13:return uLe(t,e,n);case 4:return Kre(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=yk(e,null,r,n):Dc(t,e,r,n),e.child;case 11:return r=e.type,o=e.pendingProps,o=e.elementType===r?o:Im(r,o),yOe(t,e,r,o,n);case 7:return Dc(t,e,e.pendingProps,n),e.child;case 8:return Dc(t,e,e.pendingProps.children,n),e.child;case 12:return Dc(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(r=e.type._context,o=e.pendingProps,i=e.memoizedProps,s=o.value,Do(GH,r._currentValue),r._currentValue=s,i!==null)if(Mm(i.value,s)){if(i.children===o.children&&!Nu.current){e=gw(t,e,n);break e}}else for(i=e.child,i!==null&&(i.return=e);i!==null;){var a=i.dependencies;if(a!==null){s=i.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(i.tag===1){l=fw(-1,n&-n),l.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var u=c.pending;u===null?l.next=l:(l.next=u.next,u.next=l),c.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),ire(i.return,n,e),a.lanes|=n;break}l=l.next}}else if(i.tag===10)s=i.type===e.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(Be(341));s.lanes|=n,a=s.alternate,a!==null&&(a.lanes|=n),ire(s,n,e),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===e){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dc(t,e,o.children,n),e=e.child}return e;case 9:return o=e.type,r=e.pendingProps.children,fk(e,n),o=qf(o),r=r(o),e.flags|=1,Dc(t,e,r,n),e.child;case 14:return r=e.type,o=Im(r,e.pendingProps),o=Im(r.type,o),wOe(t,e,r,o,n);case 15:return sLe(t,e,e.type,e.pendingProps,n);case 17:return r=e.type,o=e.pendingProps,o=e.elementType===r?o:Im(r,o),MH(t,e),e.tag=1,Ou(r)?(t=!0,HH(e)):t=!1,fk(e,n),LRe(e,r,o),are(e,r,o,n),ure(null,e,r,!0,t,n);case 19:return dLe(t,e,n);case 22:return aLe(t,e,n)}throw Error(Be(156,e.tag))};function PLe(t,e){return QOe(t,e)}function lSt(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Hf(t,e,n,r){return new lSt(t,e,n,r)}function aoe(t){return t=t.prototype,!(!t||!t.isReactComponent)}function cSt(t){if(typeof t=="function")return aoe(t)?1:0;if(t!=null){if(t=t.$$typeof,t===Ire)return 11;if(t===Pre)return 14}return 2}function vb(t,e){var n=t.alternate;return n===null?(n=Hf(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function RH(t,e,n,r,o,i){var s=2;if(r=t,typeof t=="function")aoe(t)&&(s=1);else if(typeof t=="string")s=5;else e:switch(t){case JA:return aT(n.children,o,i,e);case Tre:s=8,o|=8;break;case Mne:return t=Hf(12,n,e,o|2),t.elementType=Mne,t.lanes=i,t;case Nne:return t=Hf(13,n,e,o),t.elementType=Nne,t.lanes=i,t;case One:return t=Hf(19,n,e,o),t.elementType=One,t.lanes=i,t;case DOe:return h6(n,o,i,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case ROe:s=10;break e;case LOe:s=9;break e;case Ire:s=11;break e;case Pre:s=14;break e;case sb:s=16,r=null;break e}throw Error(Be(130,t==null?t:typeof t,""))}return e=Hf(s,n,e,o),e.elementType=t,e.type=r,e.lanes=i,e}function aT(t,e,n,r){return t=Hf(7,t,r,e),t.lanes=n,t}function h6(t,e,n,r){return t=Hf(22,t,r,e),t.elementType=DOe,t.lanes=n,t.stateNode={isHidden:!1},t}function Ene(t,e,n){return t=Hf(6,t,null,e),t.lanes=n,t}function Ane(t,e,n){return e=Hf(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function uSt(t,e,n,r,o){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=fne(0),this.expirationTimes=fne(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=fne(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function loe(t,e,n,r,o,i,s,a,l){return t=new uSt(t,e,n,a,l),e===1?(e=1,i===!0&&(e|=8)):e=0,i=Hf(3,null,null,e),t.current=i,i.stateNode=t,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Hre(i),t}function dSt(t,e,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:ZA,key:r==null?null:""+r,children:t,containerInfo:e,implementation:n}}function ELe(t){if(!t)return bb;t=t._reactInternals;e:{if(mT(t)!==t||t.tag!==1)throw Error(Be(170));var e=t;do{switch(e.tag){case 3:e=e.stateNode.context;break e;case 1:if(Ou(e.type)){e=e.stateNode.__reactInternalMemoizedMergedChildContext;break e}}e=e.return}while(e!==null);throw Error(Be(171))}if(t.tag===1){var n=t.type;if(Ou(n))return PRe(t,n,e)}return e}function ALe(t,e,n,r,o,i,s,a,l){return t=loe(n,r,!0,t,o,i,s,a,l),t.context=ELe(null),n=t.current,r=$c(),o=wb(n),i=fw(r,o),i.callback=e??null,gb(n,i,o),t.current.lanes=o,SF(t,o,r),Ru(t,r),t}function g6(t,e,n,r){var o=e.current,i=$c(),s=wb(o);return n=ELe(n),e.context===null?e.context=n:e.pendingContext=n,e=fw(i,s),e.payload={element:t},r=r===void 0?null:r,r!==null&&(e.callback=r),t=gb(o,e,s),t!==null&&(km(t,o,s,i),EH(t,o,s)),s}function o6(t){if(t=t.current,!t.child)return null;switch(t.child.tag){case 5:return t.child.stateNode;default:return t.child.stateNode}}function kOe(t,e){if(t=t.memoizedState,t!==null&&t.dehydrated!==null){var n=t.retryLane;t.retryLane=n!==0&&n<e?n:e}}function coe(t,e){kOe(t,e),(t=t.alternate)&&kOe(t,e)}function fSt(){return null}var kLe=typeof reportError=="function"?reportError:function(t){console.error(t)};function uoe(t){this._internalRoot=t}y6.prototype.render=uoe.prototype.render=function(t){var e=this._internalRoot;if(e===null)throw Error(Be(409));g6(t,e,null,null)};y6.prototype.unmount=uoe.prototype.unmount=function(){var t=this._internalRoot;if(t!==null){this._internalRoot=null;var e=t.containerInfo;fT(function(){g6(null,t,null,null)}),e[mw]=null}};function y6(t){this._internalRoot=t}y6.prototype.unstable_scheduleHydration=function(t){if(t){var e=sRe();t={blockedOn:null,target:t,priority:e};for(var n=0;n<lb.length&&e!==0&&e<lb[n].priority;n++);lb.splice(n,0,t),n===0&&lRe(t)}};function doe(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}function w6(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11&&(t.nodeType!==8||t.nodeValue!==" react-mount-point-unstable "))}function MOe(){}function pSt(t,e,n,r,o){if(o){if(typeof r=="function"){var i=r;r=function(){var c=o6(s);i.call(c)}}var s=ALe(e,r,t,0,null,!1,!1,"",MOe);return t._reactRootContainer=s,t[mw]=s.current,hF(t.nodeType===8?t.parentNode:t),fT(),s}for(;o=t.lastChild;)t.removeChild(o);if(typeof r=="function"){var a=r;r=function(){var c=o6(l);a.call(c)}}var l=loe(t,0,!1,null,null,!1,!1,"",MOe);return t._reactRootContainer=l,t[mw]=l.current,hF(t.nodeType===8?t.parentNode:t),fT(function(){g6(e,l,n,r)}),l}function v6(t,e,n,r,o){var i=n._reactRootContainer;if(i){var s=i;if(typeof o=="function"){var a=o;o=function(){var l=o6(s);a.call(l)}}g6(e,s,t,o)}else s=pSt(n,e,t,o,r);return o6(s)}oRe=function(t){switch(t.tag){case 3:var e=t.stateNode;if(e.current.memoizedState.isDehydrated){var n=Z$(e.pendingLanes);n!==0&&(kre(e,n|1),Ru(e,ts()),(zr&6)===0&&(xk=ts()+500,Sb()))}break;case 13:fT(function(){var r=hw(t,1);if(r!==null){var o=$c();km(r,t,1,o)}}),coe(t,1)}};Mre=function(t){if(t.tag===13){var e=hw(t,134217728);if(e!==null){var n=$c();km(e,t,134217728,n)}coe(t,134217728)}};iRe=function(t){if(t.tag===13){var e=wb(t),n=hw(t,e);if(n!==null){var r=$c();km(n,t,e,r)}coe(t,e)}};sRe=function(){return po};aRe=function(t,e){var n=po;try{return po=t,e()}finally{po=n}};Vne=function(t,e,n){switch(e){case"input":if(Dne(t,n),e=n.name,n.type==="radio"&&e!=null){for(n=t;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+e)+'][type="radio"]'),e=0;e<n.length;e++){var r=n[e];if(r!==t&&r.form===t.form){var o=c6(r);if(!o)throw Error(Be(90));FOe(r),Dne(r,o)}}}break;case"textarea":BOe(t,n);break;case"select":e=n.value,e!=null&&lk(t,!!n.multiple,e,!1)}};qOe=ooe;GOe=fT;var mSt={usingClientEntryPoint:!1,Events:[IF,tk,c6,HOe,KOe,ooe]},K$={findFiberByHostInstance:rT,bundleType:0,version:"18.2.0",rendererPackageName:"react-dom"},hSt={bundleType:K$.bundleType,version:K$.version,rendererPackageName:K$.rendererPackageName,rendererConfig:K$.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:yw.ReactCurrentDispatcher,findHostInstanceByFiber:function(t){return t=JOe(t),t===null?null:t.stateNode},findFiberByHostInstance:K$.findFiberByHostInstance||fSt,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.2.0-next-9e3b772b8-20220608"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&(q$=__REACT_DEVTOOLS_GLOBAL_HOOK__,!q$.isDisabled&&q$.supportsFiber))try{i6=q$.inject(hSt),hg=q$}catch{}var q$;Fd.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=mSt;Fd.createPortal=function(t,e){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!doe(e))throw Error(Be(200));return dSt(t,e,null,n)};Fd.createRoot=function(t,e){if(!doe(t))throw Error(Be(299));var n=!1,r="",o=kLe;return e!=null&&(e.unstable_strictMode===!0&&(n=!0),e.identifierPrefix!==void 0&&(r=e.identifierPrefix),e.onRecoverableError!==void 0&&(o=e.onRecoverableError)),e=loe(t,1,!1,null,null,n,!1,r,o),t[mw]=e.current,hF(t.nodeType===8?t.parentNode:t),new uoe(e)};Fd.findDOMNode=function(t){if(t==null)return null;if(t.nodeType===1)return t;var e=t._reactInternals;if(e===void 0)throw typeof t.render=="function"?Error(Be(188)):(t=Object.keys(t).join(","),Error(Be(268,t)));return t=JOe(e),t=t===null?null:t.stateNode,t};Fd.flushSync=function(t){return fT(t)};Fd.hydrate=function(t,e,n){if(!w6(e))throw Error(Be(200));return v6(null,t,e,!0,n)};Fd.hydrateRoot=function(t,e,n){if(!doe(t))throw Error(Be(405));var r=n!=null&&n.hydratedSources||null,o=!1,i="",s=kLe;if(n!=null&&(n.unstable_strictMode===!0&&(o=!0),n.identifierPrefix!==void 0&&(i=n.identifierPrefix),n.onRecoverableError!==void 0&&(s=n.onRecoverableError)),e=ALe(e,null,t,1,n??null,o,!1,i,s),t[mw]=e.current,hF(t),r)for(t=0;t<r.length;t++)n=r[t],o=n._getVersion,o=o(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,o]:e.mutableSourceEagerHydrationData.push(n,o);return new y6(e)};Fd.render=function(t,e,n){if(!w6(e))throw Error(Be(200));return v6(null,t,e,!1,n)};Fd.unmountComponentAtNode=function(t){if(!w6(t))throw Error(Be(40));return t._reactRootContainer?(fT(function(){v6(null,null,t,!1,function(){t._reactRootContainer=null,t[mw]=null})}),!0):!1};Fd.unstable_batchedUpdates=ooe;Fd.unstable_renderSubtreeIntoContainer=function(t,e,n,r){if(!w6(n))throw Error(Be(200));if(t==null||t._reactInternals===void 0)throw Error(Be(38));return v6(t,e,n,!1,r)};Fd.version="18.2.0-next-9e3b772b8-20220608"});var yo=Tt((fpn,OLe)=>{"use strict";function NLe(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(NLe)}catch(t){console.error(t)}}NLe(),OLe.exports=MLe()});var LLe=Tt(foe=>{"use strict";var RLe=yo();foe.createRoot=RLe.createRoot,foe.hydrateRoot=RLe.hydrateRoot;var ppn});function sr(t,e){let n=(0,$Le.createRoot)(t);return{render(r){n.render(DLe.default.createElement(D$.Provider,{value:e},r))},unmount(){n.unmount()}}}var DLe,$Le,ws=C(()=>{bi();DLe=N(U()),$Le=N(LLe())});function gSt({onCancel:t}){let e=q(),n=poe(e.defaultModelKey)&&poe(e.embeddingModelKey);return yg.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},yg.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},yg.default.createElement("div",null,"Your Copilot Plus license key is no longer valid. Please renew your subscription to continue using Copilot Plus."),n&&yg.default.createElement("div",{className:"tw-text-sm tw-text-warning"},"The Copilot Plus exclusive models will stop working. You can switch to the default models in the Settings.")),yg.default.createElement("div",{className:"tw-flex tw-w-full tw-justify-end tw-gap-2"},yg.default.createElement(X,{variant:"ghost",onClick:t},"Close"),yg.default.createElement(X,{variant:"default",onClick:()=>{hT(Vy.EXPIRED_MODAL)}},"Renew Now ",yg.default.createElement(rw,{className:"tw-size-4"}))))}var yg,FLe,x6,ULe=C(()=>{yg=N(U()),FLe=require("obsidian");rn();ns();It();vt();Se();ws();x6=class extends FLe.Modal{constructor(e){super(e),this.setTitle("Thanks for being a Copilot Plus user \u{1F44B}")}onOpen(){let{contentEl:e}=this;this.root=sr(e,this.app);let n=()=>{this.close()};this.root.render(yg.default.createElement(gSt,{onCancel:n}))}onClose(){this.root.unmount()}}});var BLe,Dn,$n=C(()=>{BLe=Object.defineProperty,Dn=(t,e)=>{let n={};for(var r in t)BLe(n,r,{get:t[r],enumerable:!0});return e||BLe(n,Symbol.toStringTag,{value:"Module"}),n}});function ce(t,e,n){function r(a,l){var c;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(c=a._zod).traits??(c.traits=new Set),a._zod.traits.add(t),e(a,l);for(let u in s.prototype)u in a||Object.defineProperty(a,u,{value:s.prototype[u].bind(a)});a._zod.constr=s,a._zod.def=l}let o=n?.Parent??Object;class i extends o{}Object.defineProperty(i,"name",{value:t});function s(a){var l;let c=n?.Parent?new i:this;r(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(s,"name",{value:t}),s}function vs(t){return t&&Object.assign(EF,t),EF}var moe,hoe,wg,EF,_k=C(()=>{moe=Object.freeze({status:"aborted"});hoe=Symbol("zod_brand"),wg=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},EF={}});var Qe={};zn(Qe,{BIGINT_FORMAT_RANGES:()=>Toe,Class:()=>yoe,NUMBER_FORMAT_RANGES:()=>Soe,aborted:()=>yT,allowsEval:()=>boe,assert:()=>bSt,assertEqual:()=>ySt,assertIs:()=>vSt,assertNever:()=>xSt,assertNotEqual:()=>wSt,assignProp:()=>xoe,cached:()=>MF,captureStackTrace:()=>b6,cleanEnum:()=>RSt,cleanRegex:()=>NF,clone:()=>xs,createTransparentProxy:()=>PSt,defineLazy:()=>Zr,esc:()=>gT,escapeRegex:()=>ww,extend:()=>kSt,finalizeIssue:()=>Ud,floatSafeRemainder:()=>voe,getElementAtPath:()=>CSt,getEnumValues:()=>kF,getLengthableOrigin:()=>LF,getParsedType:()=>ISt,getSizableOrigin:()=>RF,isObject:()=>Sk,isPlainObject:()=>Tk,issue:()=>Ioe,joinValues:()=>be,jsonStringifyReplacer:()=>woe,merge:()=>MSt,normalizeParams:()=>We,nullish:()=>Tb,numKeys:()=>TSt,omit:()=>ASt,optionalKeys:()=>_oe,partial:()=>NSt,pick:()=>ESt,prefixIssues:()=>Lu,primitiveTypes:()=>Coe,promiseAllObject:()=>_St,propertyKeyTypes:()=>OF,randomString:()=>SSt,required:()=>OSt,stringifyPrimitive:()=>ot,unwrapMessage:()=>AF});function ySt(t){return t}function wSt(t){return t}function vSt(t){}function xSt(t){throw new Error}function bSt(t){}function kF(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function be(t,e="|"){return t.map(n=>ot(n)).join(e)}function woe(t,e){return typeof e=="bigint"?e.toString():e}function MF(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Tb(t){return t==null}function NF(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function voe(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}function Zr(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function xoe(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function CSt(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function _St(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let i=0;i<e.length;i++)o[e[i]]=r[i];return o})}function SSt(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function gT(t){return JSON.stringify(t)}function Sk(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Tk(t){if(Sk(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(Sk(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function TSt(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}function ww(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xs(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function We(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function PSt(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,i){return e??(e=t()),Reflect.set(e,r,o,i)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function ot(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function _oe(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function ESt(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return xs(t,{...t._zod.def,shape:n,checks:[]})}function ASt(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return xs(t,{...t._zod.def,shape:n,checks:[]})}function kSt(t,e){if(!Tk(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return xoe(this,"shape",r),r},checks:[]};return xs(t,n)}function MSt(t,e){return xs(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return xoe(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function NSt(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let i in n){if(!(i in r))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=t?new t({type:"optional",innerType:r[i]}):r[i])}else for(let i in r)o[i]=t?new t({type:"optional",innerType:r[i]}):r[i];return xs(e,{...e._zod.def,shape:o,checks:[]})}function OSt(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let i in n){if(!(i in o))throw new Error(`Unrecognized key: "${i}"`);n[i]&&(o[i]=new t({type:"nonoptional",innerType:r[i]}))}else for(let i in r)o[i]=new t({type:"nonoptional",innerType:r[i]});return xs(e,{...e._zod.def,shape:o,checks:[]})}function yT(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function Lu(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function AF(t){return typeof t=="string"?t:t?.message}function Ud(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=AF(t.inst?._zod.def?.error?.(t))??AF(e?.error?.(t))??AF(n.customError?.(t))??AF(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function RF(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function LF(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Ioe(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function RSt(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var b6,boe,ISt,OF,Coe,Soe,Toe,yoe,An=C(()=>{b6=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};boe=MF(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});ISt=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},OF=new Set(["string","number","symbol"]),Coe=new Set(["string","number","bigint","boolean","symbol","undefined"]);Soe={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Toe={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};yoe=class{constructor(...e){}}});function $F(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function FF(t,e){let n=e||function(i){return i.message},r={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>o({issues:a}));else if(s.code==="invalid_key")o({issues:s.issues});else if(s.code==="invalid_element")o({issues:s.issues});else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(t),r}function Poe(t,e){let n=e||function(i){return i.message},r={errors:[]},o=(i,s=[])=>{var a,l;for(let c of i.issues)if(c.code==="invalid_union"&&c.errors.length)c.errors.map(u=>o({issues:u},c.path));else if(c.code==="invalid_key")o({issues:c.issues},c.path);else if(c.code==="invalid_element")o({issues:c.issues},c.path);else{let u=[...s,...c.path];if(u.length===0){r.errors.push(n(c));continue}let d=r,f=0;for(;f<u.length;){let p=u[f],m=f===u.length-1;typeof p=="string"?(d.properties??(d.properties={}),(a=d.properties)[p]??(a[p]={errors:[]}),d=d.properties[p]):(d.items??(d.items=[]),(l=d.items)[p]??(l[p]={errors:[]}),d=d.items[p]),m&&d.errors.push(n(c)),f++}}};return o(t),r}function jLe(t){let e=[];for(let n of t)typeof n=="number"?e.push(`[${n}]`):typeof n=="symbol"?e.push(`[${JSON.stringify(String(n))}]`):/[^\w$]/.test(n)?e.push(`[${JSON.stringify(n)}]`):(e.length&&e.push("."),e.push(n));return e.join("")}function Eoe(t){let e=[],n=[...t.issues].sort((r,o)=>r.path.length-o.path.length);for(let r of n)e.push(`\u2716 ${r.message}`),r.path?.length&&e.push(`  \u2192 at ${jLe(r.path)}`);return e.join(`
`)}var zLe,DF,Ik,Aoe=C(()=>{_k();An();zLe=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,woe,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},DF=ce("$ZodError",zLe),Ik=ce("$ZodError",zLe,{Parent:Error})});var C6,wT,_6,vT,S6,koe,T6,Moe,I6=C(()=>{_k();Aoe();An();C6=t=>(e,n,r,o)=>{let i=r?Object.assign(r,{async:!1}):{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new wg;if(s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>Ud(l,i,vs())));throw b6(a,o?.callee),a}return s.value},wT=C6(Ik),_6=t=>async(e,n,r,o)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(o?.Err??t)(s.issues.map(l=>Ud(l,i,vs())));throw b6(a,o?.callee),a}return s.value},vT=_6(Ik),S6=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new wg;return i.issues.length?{success:!1,error:new(t??DF)(i.issues.map(s=>Ud(s,o,vs())))}:{success:!0,data:i.value}},koe=S6(Ik),T6=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new t(i.issues.map(s=>Ud(s,o,vs())))}:{success:!0,data:i.value}},Moe=T6(Ik)});var bT={};zn(bT,{_emoji:()=>VLe,base64:()=>Koe,base64url:()=>P6,bigint:()=>Qoe,boolean:()=>nie,browserEmail:()=>VSt,cidrv4:()=>Woe,cidrv6:()=>Hoe,cuid:()=>Noe,cuid2:()=>Ooe,date:()=>Yoe,datetime:()=>Joe,domain:()=>WSt,duration:()=>Foe,e164:()=>Goe,email:()=>Boe,emoji:()=>zoe,extendedDuration:()=>DSt,guid:()=>Uoe,hostname:()=>qoe,html5Email:()=>BSt,integer:()=>eie,ipv4:()=>joe,ipv6:()=>Voe,ksuid:()=>Doe,lowercase:()=>iie,nanoid:()=>$oe,null:()=>rie,number:()=>tie,rfc5322Email:()=>zSt,string:()=>Xoe,time:()=>Zoe,ulid:()=>Roe,undefined:()=>oie,unicodeEmail:()=>jSt,uppercase:()=>sie,uuid:()=>xT,uuid4:()=>$St,uuid6:()=>FSt,uuid7:()=>USt,xid:()=>Loe});function zoe(){return new RegExp(VLe,"u")}function HLe(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Zoe(t){return new RegExp(`^${HLe(t)}$`)}function Joe(t){let e=HLe({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${WLe}T(?:${r})$`)}var Noe,Ooe,Roe,Loe,Doe,$oe,Foe,DSt,Uoe,xT,$St,FSt,USt,Boe,BSt,zSt,jSt,VSt,VLe,joe,Voe,Woe,Hoe,Koe,P6,qoe,WSt,Goe,WLe,Yoe,Xoe,Qoe,eie,tie,nie,rie,oie,iie,sie,E6=C(()=>{Noe=/^[cC][^\s-]{8,}$/,Ooe=/^[0-9a-z]+$/,Roe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Loe=/^[0-9a-vA-V]{20}$/,Doe=/^[A-Za-z0-9]{27}$/,$oe=/^[a-zA-Z0-9_-]{21}$/,Foe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,DSt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Uoe=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,xT=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,$St=xT(4),FSt=xT(6),USt=xT(7),Boe=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,BSt=/^[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])?)*$/,zSt=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,jSt=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,VSt=/^[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])?)*$/,VLe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";joe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Voe=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Woe=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Hoe=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Koe=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,P6=/^[A-Za-z0-9_-]*$/,qoe=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,WSt=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Goe=/^\+(?:[0-9]){6,14}[0-9]$/,WLe="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Yoe=new RegExp(`^${WLe}$`);Xoe=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Qoe=/^\d+n?$/,eie=/^\d+$/,tie=/^-?\d+(?:\.\d+)?/i,nie=/true|false/i,rie=/null/i,oie=/undefined/i,iie=/^[^A-Z]*$/,sie=/^[^a-z]*$/});function KLe(t,e,n){t.issues.length&&e.issues.push(...Lu(n,t.issues))}var Ti,qLe,A6,k6,aie,lie,cie,uie,die,fie,pie,mie,hie,Pk,gie,yie,wie,vie,xie,bie,Cie,_ie,Sie,M6=C(()=>{_k();E6();An();Ti=ce("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),qLe={number:"number",bigint:"bigint",object:"date"},A6=ce("$ZodCheckLessThan",(t,e)=>{Ti.init(t,e);let n=qLe[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,i=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<i&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),k6=ce("$ZodCheckGreaterThan",(t,e)=>{Ti.init(t,e);let n=qLe[typeof e.value];t._zod.onattach.push(r=>{let o=r._zod.bag,i=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>i&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),aie=ce("$ZodCheckMultipleOf",(t,e)=>{Ti.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):voe(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),lie=ce("$ZodCheckNumberFormat",(t,e)=>{Ti.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,i]=Soe[e.format];t._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=o,a.maximum=i,n&&(a.pattern=eie)}),t._zod.check=s=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,continue:!e.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inst:t})}}),cie=ce("$ZodCheckBigIntFormat",(t,e)=>{Ti.init(t,e);let[n,r]=Toe[e.format];t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,i.minimum=n,i.maximum=r}),t._zod.check=o=>{let i=o.value;i<n&&o.issues.push({origin:"bigint",input:i,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),i>r&&o.issues.push({origin:"bigint",input:i,code:"too_big",maximum:r,inst:t})}}),uie=ce("$ZodCheckMaxSize",(t,e)=>{var n;Ti.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Tb(o)&&o.size!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;o.size<=e.maximum||r.issues.push({origin:RF(o),code:"too_big",maximum:e.maximum,input:o,inst:t,continue:!e.abort})}}),die=ce("$ZodCheckMinSize",(t,e)=>{var n;Ti.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Tb(o)&&o.size!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;o.size>=e.minimum||r.issues.push({origin:RF(o),code:"too_small",minimum:e.minimum,input:o,inst:t,continue:!e.abort})}}),fie=ce("$ZodCheckSizeEquals",(t,e)=>{var n;Ti.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Tb(o)&&o.size!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.size,o.maximum=e.size,o.size=e.size}),t._zod.check=r=>{let o=r.value,i=o.size;if(i===e.size)return;let s=i>e.size;r.issues.push({origin:RF(o),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),pie=ce("$ZodCheckMaxLength",(t,e)=>{var n;Ti.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Tb(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let s=LF(o);r.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),mie=ce("$ZodCheckMinLength",(t,e)=>{var n;Ti.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Tb(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let s=LF(o);r.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),hie=ce("$ZodCheckLengthEquals",(t,e)=>{var n;Ti.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Tb(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,i=o.length;if(i===e.length)return;let s=LF(o),a=i>e.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Pk=ce("$ZodCheckStringFormat",(t,e)=>{var n,r;Ti.init(t,e),t._zod.onattach.push(o=>{let i=o._zod.bag;i.format=e.format,e.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),gie=ce("$ZodCheckRegex",(t,e)=>{Pk.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),yie=ce("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=iie),Pk.init(t,e)}),wie=ce("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=sie),Pk.init(t,e)}),vie=ce("$ZodCheckIncludes",(t,e)=>{Ti.init(t,e);let n=ww(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let i=o._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),xie=ce("$ZodCheckStartsWith",(t,e)=>{Ti.init(t,e);let n=new RegExp(`^${ww(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),bie=ce("$ZodCheckEndsWith",(t,e)=>{Ti.init(t,e);let n=new RegExp(`.*${ww(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});Cie=ce("$ZodCheckProperty",(t,e)=>{Ti.init(t,e),t._zod.check=n=>{let r=e.schema._zod.run({value:n.value[e.property],issues:[]},{});if(r instanceof Promise)return r.then(o=>KLe(o,n,e.property));KLe(r,n,e.property)}}),_ie=ce("$ZodCheckMimeType",(t,e)=>{Ti.init(t,e);let n=new Set(e.mime);t._zod.onattach.push(r=>{r._zod.bag.mime=e.mime}),t._zod.check=r=>{n.has(r.value.type)||r.issues.push({code:"invalid_value",values:e.mime,input:r.value.type,inst:t})}}),Sie=ce("$ZodCheckOverwrite",(t,e)=>{Ti.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}})});var UF,Tie=C(()=>{UF=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
`).filter(s=>s),o=Math.min(...r.map(s=>s.length-s.trimStart().length)),i=r.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let e=Function,n=this?.args,o=[...(this?.content??[""]).map(i=>`  ${i}`)];return new e(...n,o.join(`
`))}}});var Iie,Pie=C(()=>{Iie={major:4,minor:0,patch:0}});function Gie(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function s1e(t){if(!P6.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return Gie(n)}function a1e(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function YLe(t,e,n){t.issues.length&&e.issues.push(...Lu(n,t.issues)),e.value[n]=t.value}function N6(t,e,n){t.issues.length&&e.issues.push(...Lu(n,t.issues)),e.value[n]=t.value}function ZLe(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...Lu(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}function JLe(t,e,n,r){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(o=>o.issues.map(i=>Ud(i,r,vs())))}),e}function Eie(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Tk(t)&&Tk(e)){let n=Object.keys(e),r=Object.keys(t).filter(i=>n.indexOf(i)!==-1),o={...t,...e};for(let i of r){let s=Eie(t[i],e[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<t.length;r++){let o=t[r],i=e[r],s=Eie(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function XLe(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),yT(t))return t;let r=Eie(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}function O6(t,e,n){t.issues.length&&e.issues.push(...Lu(n,t.issues)),e.value[n]=t.value}function QLe(t,e,n,r,o,i,s){t.issues.length&&(OF.has(typeof r)?n.issues.push(...Lu(r,t.issues)):n.issues.push({origin:"map",code:"invalid_key",input:o,inst:i,issues:t.issues.map(a=>Ud(a,s,vs()))})),e.issues.length&&(OF.has(typeof r)?n.issues.push(...Lu(r,e.issues)):n.issues.push({origin:"map",code:"invalid_element",input:o,inst:i,key:r,issues:e.issues.map(a=>Ud(a,s,vs()))})),n.value.set(t.value,e.value)}function e1e(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function t1e(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function n1e(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function r1e(t,e,n){return yT(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}function o1e(t){return t.value=Object.freeze(t.value),t}function i1e(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(Ioe(o))}}var jn,CT,_o,Aie,kie,Mie,Nie,Oie,Rie,Lie,Die,$ie,Fie,Uie,Bie,zie,jie,Vie,Wie,Hie,Kie,qie,Yie,Zie,Jie,Xie,Qie,R6,ese,BF,L6,tse,nse,rse,ose,ise,_T,zF,sse,ase,jF,lse,D6,cse,use,ST,dse,fse,pse,mse,hse,gse,VF,$6,yse,wse,vse,xse,bse,Cse,_se,WF,Sse,Tse,Ise,Pse,Ese,HF=C(()=>{M6();_k();Tie();I6();E6();An();Pie();An();jn=ce("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Iie;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let i of o._zod.onattach)i(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(i,s,a)=>{let l=yT(i),c;for(let u of s){if(u._zod.def.when){if(!u._zod.def.when(i))continue}else if(l)continue;let d=i.issues.length,f=u._zod.check(i);if(f instanceof Promise&&a?.async===!1)throw new wg;if(c||f instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await f,i.issues.length!==d&&(l||(l=yT(i,d)))});else{if(i.issues.length===d)continue;l||(l=yT(i,d))}}return c?c.then(()=>i):i};t._zod.run=(i,s)=>{let a=t._zod.parse(i,s);if(a instanceof Promise){if(s.async===!1)throw new wg;return a.then(l=>o(l,r,s))}return o(a,r,s)}}t["~standard"]={validate:o=>{try{let i=koe(t,o);return i.success?{value:i.data}:{issues:i.error?.issues}}catch{return Moe(t,o).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}}),CT=ce("$ZodString",(t,e)=>{jn.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Xoe(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),_o=ce("$ZodStringFormat",(t,e)=>{Pk.init(t,e),CT.init(t,e)}),Aie=ce("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Uoe),_o.init(t,e)}),kie=ce("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=xT(r))}else e.pattern??(e.pattern=xT());_o.init(t,e)}),Mie=ce("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Boe),_o.init(t,e)}),Nie=ce("$ZodURL",(t,e)=>{_o.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),i=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:qoe.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&i.endsWith("/")?n.value=i.slice(0,-1):n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),Oie=ce("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=zoe()),_o.init(t,e)}),Rie=ce("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=$oe),_o.init(t,e)}),Lie=ce("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Noe),_o.init(t,e)}),Die=ce("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ooe),_o.init(t,e)}),$ie=ce("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Roe),_o.init(t,e)}),Fie=ce("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Loe),_o.init(t,e)}),Uie=ce("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Doe),_o.init(t,e)}),Bie=ce("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Joe(e)),_o.init(t,e)}),zie=ce("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Yoe),_o.init(t,e)}),jie=ce("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Zoe(e)),_o.init(t,e)}),Vie=ce("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Foe),_o.init(t,e)}),Wie=ce("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=joe),_o.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),Hie=ce("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Voe),_o.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),Kie=ce("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Woe),_o.init(t,e)}),qie=ce("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Hoe),_o.init(t,e),t._zod.check=n=>{let[r,o]=n.value.split("/");try{if(!o)throw new Error;let i=Number(o);if(`${i}`!==o)throw new Error;if(i<0||i>128)throw new Error;new URL(`http://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});Yie=ce("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Koe),_o.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{Gie(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});Zie=ce("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=P6),_o.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{s1e(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Jie=ce("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Goe),_o.init(t,e)});Xie=ce("$ZodJWT",(t,e)=>{_o.init(t,e),t._zod.check=n=>{a1e(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),Qie=ce("$ZodCustomStringFormat",(t,e)=>{_o.init(t,e),t._zod.check=n=>{e.fn(n.value)||n.issues.push({code:"invalid_format",format:e.format,input:n.value,inst:t,continue:!e.abort})}}),R6=ce("$ZodNumber",(t,e)=>{jn.init(t,e),t._zod.pattern=t._zod.bag.pattern??tie,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...i?{received:i}:{}}),n}}),ese=ce("$ZodNumber",(t,e)=>{lie.init(t,e),R6.init(t,e)}),BF=ce("$ZodBoolean",(t,e)=>{jn.init(t,e),t._zod.pattern=nie,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}}),L6=ce("$ZodBigInt",(t,e)=>{jn.init(t,e),t._zod.pattern=Qoe,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=BigInt(n.value)}catch{}return typeof n.value=="bigint"||n.issues.push({expected:"bigint",code:"invalid_type",input:n.value,inst:t}),n}}),tse=ce("$ZodBigInt",(t,e)=>{cie.init(t,e),L6.init(t,e)}),nse=ce("$ZodSymbol",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;return typeof o=="symbol"||n.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:t}),n}}),rse=ce("$ZodUndefined",(t,e)=>{jn.init(t,e),t._zod.pattern=oie,t._zod.values=new Set([void 0]),t._zod.optin="optional",t._zod.optout="optional",t._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:t}),n}}),ose=ce("$ZodNull",(t,e)=>{jn.init(t,e),t._zod.pattern=rie,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}}),ise=ce("$ZodAny",(t,e)=>{jn.init(t,e),t._zod.parse=n=>n}),_T=ce("$ZodUnknown",(t,e)=>{jn.init(t,e),t._zod.parse=n=>n}),zF=ce("$ZodNever",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)}),sse=ce("$ZodVoid",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;return typeof o>"u"||n.issues.push({expected:"void",code:"invalid_type",input:o,inst:t}),n}}),ase=ce("$ZodDate",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=new Date(n.value)}catch{}let o=n.value,i=o instanceof Date;return i&&!Number.isNaN(o.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:o,...i?{received:"Invalid Date"}:{},inst:t}),n}});jF=ce("$ZodArray",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.value=Array(o.length);let i=[];for(let s=0;s<o.length;s++){let a=o[s],l=e.element._zod.run({value:a,issues:[]},r);l instanceof Promise?i.push(l.then(c=>YLe(c,n,s))):YLe(l,n,s)}return i.length?Promise.all(i).then(()=>n):n}});lse=ce("$ZodObject",(t,e)=>{jn.init(t,e);let n=MF(()=>{let d=Object.keys(e.shape);for(let p of d)if(!(e.shape[p]instanceof jn))throw new Error(`Invalid element at key "${p}": expected a Zod schema`);let f=_oe(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});Zr(t._zod,"propValues",()=>{let d=e.shape,f={};for(let p in d){let m=d[p]._zod;if(m.values){f[p]??(f[p]=new Set);for(let h of m.values)f[p].add(h)}}return f});let r=d=>{let f=new UF(["shape","payload","ctx"]),p=n.value,m=w=>{let v=gT(w);return`shape[${v}]._zod.run({ value: input[${v}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),g=0;for(let w of p.keys)h[w]=`key_${g++}`;f.write("const newResult = {}");for(let w of p.keys)if(p.optionalKeys.has(w)){let v=h[w];f.write(`const ${v} = ${m(w)};`);let x=gT(w);f.write(`
        if (${v}.issues.length) {
          if (input[${x}] === undefined) {
            if (${x} in input) {
              newResult[${x}] = undefined;
            }
          } else {
            payload.issues = payload.issues.concat(
              ${v}.issues.map((iss) => ({
                ...iss,
                path: iss.path ? [${x}, ...iss.path] : [${x}],
              }))
            );
          }
        } else if (${v}.value === undefined) {
          if (${x} in input) newResult[${x}] = undefined;
        } else {
          newResult[${x}] = ${v}.value;
        }
        `)}else{let v=h[w];f.write(`const ${v} = ${m(w)};`),f.write(`
          if (${v}.issues.length) payload.issues = payload.issues.concat(${v}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${gT(w)}, ...iss.path] : [${gT(w)}]
          })));`),f.write(`newResult[${gT(w)}] = ${v}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(w,v)=>y(d,w,v)},o,i=Sk,s=!EF.jitless,l=s&&boe.value,c=e.catchall,u;t._zod.parse=(d,f)=>{u??(u=n.value);let p=d.value;if(!i(p))return d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d;let m=[];if(s&&l&&f?.async===!1&&f.jitless!==!0)o||(o=r(e.shape)),d=o(d,f);else{d.value={};let v=u.shape;for(let x of u.keys){let b=v[x],_=b._zod.run({value:p[x],issues:[]},f),T=b._zod.optin==="optional"&&b._zod.optout==="optional";_ instanceof Promise?m.push(_.then(S=>T?ZLe(S,d,x,p):N6(S,d,x))):T?ZLe(_,d,x,p):N6(_,d,x)}}if(!c)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=u.keySet,y=c._zod,w=y.def.type;for(let v of Object.keys(p)){if(g.has(v))continue;if(w==="never"){h.push(v);continue}let x=y.run({value:p[v],issues:[]},f);x instanceof Promise?m.push(x.then(b=>N6(b,d,v))):N6(x,d,v)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:p,inst:t}),m.length?Promise.all(m).then(()=>d):d}});D6=ce("$ZodUnion",(t,e)=>{jn.init(t,e),Zr(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),Zr(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),Zr(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),Zr(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>NF(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,i=[];for(let s of e.options){let a=s._zod.run({value:n.value,issues:[]},r);if(a instanceof Promise)i.push(a),o=!0;else{if(a.issues.length===0)return a;i.push(a)}}return o?Promise.all(i).then(s=>JLe(s,n,t,r)):JLe(i,n,t,r)}}),cse=ce("$ZodDiscriminatedUnion",(t,e)=>{D6.init(t,e);let n=t._zod.parse;Zr(t._zod,"propValues",()=>{let o={};for(let i of e.options){let s=i._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let[a,l]of Object.entries(s)){o[a]||(o[a]=new Set);for(let c of l)o[a].add(c)}}return o});let r=MF(()=>{let o=e.options,i=new Map;for(let s of o){let a=s._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of a){if(i.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);i.set(l,s)}}return i});t._zod.parse=(o,i)=>{let s=o.value;if(!Sk(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:t}),o;let a=r.value.get(s?.[e.discriminator]);return a?a._zod.run(o,i):e.unionFallback?n(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:s,path:[e.discriminator],inst:t}),o)}}),use=ce("$ZodIntersection",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,i=e.left._zod.run({value:o,issues:[]},r),s=e.right._zod.run({value:o,issues:[]},r);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([l,c])=>XLe(n,l,c)):XLe(n,i,s)}});ST=ce("$ZodTuple",(t,e)=>{jn.init(t,e);let n=e.items,r=n.length-[...n].reverse().findIndex(o=>o._zod.optin!=="optional");t._zod.parse=(o,i)=>{let s=o.value;if(!Array.isArray(s))return o.issues.push({input:s,inst:t,expected:"tuple",code:"invalid_type"}),o;o.value=[];let a=[];if(!e.rest){let c=s.length>n.length,u=s.length<r-1;if(c||u)return o.issues.push({input:s,inst:t,origin:"array",...c?{code:"too_big",maximum:n.length}:{code:"too_small",minimum:n.length}}),o}let l=-1;for(let c of n){if(l++,l>=s.length&&l>=r)continue;let u=c._zod.run({value:s[l],issues:[]},i);u instanceof Promise?a.push(u.then(d=>O6(d,o,l))):O6(u,o,l)}if(e.rest){let c=s.slice(n.length);for(let u of c){l++;let d=e.rest._zod.run({value:u,issues:[]},i);d instanceof Promise?a.push(d.then(f=>O6(f,o,l))):O6(d,o,l)}}return a.length?Promise.all(a).then(()=>o):o}});dse=ce("$ZodRecord",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Tk(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let i=[];if(e.keyType._zod.values){let s=e.keyType._zod.values;n.value={};for(let l of s)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){let c=e.valueType._zod.run({value:o[l],issues:[]},r);c instanceof Promise?i.push(c.then(u=>{u.issues.length&&n.issues.push(...Lu(l,u.issues)),n.value[l]=u.value})):(c.issues.length&&n.issues.push(...Lu(l,c.issues)),n.value[l]=c.value)}let a;for(let l in o)s.has(l)||(a=a??[],a.push(l));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let s of Reflect.ownKeys(o)){if(s==="__proto__")continue;let a=e.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(c=>Ud(c,r,vs())),input:s,path:[s],inst:t}),n.value[a.value]=a.value;continue}let l=e.valueType._zod.run({value:o[s],issues:[]},r);l instanceof Promise?i.push(l.then(c=>{c.issues.length&&n.issues.push(...Lu(s,c.issues)),n.value[a.value]=c.value})):(l.issues.length&&n.issues.push(...Lu(s,l.issues)),n.value[a.value]=l.value)}}return i.length?Promise.all(i).then(()=>n):n}}),fse=ce("$ZodMap",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!(o instanceof Map))return n.issues.push({expected:"map",code:"invalid_type",input:o,inst:t}),n;let i=[];n.value=new Map;for(let[s,a]of o){let l=e.keyType._zod.run({value:s,issues:[]},r),c=e.valueType._zod.run({value:a,issues:[]},r);l instanceof Promise||c instanceof Promise?i.push(Promise.all([l,c]).then(([u,d])=>{QLe(u,d,n,s,o,t,r)})):QLe(l,c,n,s,o,t,r)}return i.length?Promise.all(i).then(()=>n):n}});pse=ce("$ZodSet",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!(o instanceof Set))return n.issues.push({input:o,inst:t,expected:"set",code:"invalid_type"}),n;let i=[];n.value=new Set;for(let s of o){let a=e.valueType._zod.run({value:s,issues:[]},r);a instanceof Promise?i.push(a.then(l=>e1e(l,n))):e1e(a,n)}return i.length?Promise.all(i).then(()=>n):n}});mse=ce("$ZodEnum",(t,e)=>{jn.init(t,e);let n=kF(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>OF.has(typeof r)).map(r=>typeof r=="string"?ww(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let i=r.value;return t._zod.values.has(i)||r.issues.push({code:"invalid_value",values:n,input:i,inst:t}),r}}),hse=ce("$ZodLiteral",(t,e)=>{jn.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?ww(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}}),gse=ce("$ZodFile",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;return o instanceof File||n.issues.push({expected:"file",code:"invalid_type",input:o,inst:t}),n}}),VF=ce("$ZodTransform",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(n.value=s,n));if(o instanceof Promise)throw new wg;return n.value=o,n}}),$6=ce("$ZodOptional",(t,e)=>{jn.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Zr(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Zr(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${NF(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),yse=ce("$ZodNullable",(t,e)=>{jn.init(t,e),Zr(t._zod,"optin",()=>e.innerType._zod.optin),Zr(t._zod,"optout",()=>e.innerType._zod.optout),Zr(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${NF(n.source)}|null)$`):void 0}),Zr(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),wse=ce("$ZodDefault",(t,e)=>{jn.init(t,e),t._zod.optin="optional",Zr(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>t1e(i,e)):t1e(o,e)}});vse=ce("$ZodPrefault",(t,e)=>{jn.init(t,e),t._zod.optin="optional",Zr(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),xse=ce("$ZodNonOptional",(t,e)=>{jn.init(t,e),Zr(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>n1e(i,t)):n1e(o,t)}});bse=ce("$ZodSuccess",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.issues.length===0,n)):(n.value=o.issues.length===0,n)}}),Cse=ce("$ZodCatch",(t,e)=>{jn.init(t,e),t._zod.optin="optional",Zr(t._zod,"optout",()=>e.innerType._zod.optout),Zr(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(i=>(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(s=>Ud(s,r,vs()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(i=>Ud(i,r,vs()))},input:n.value}),n.issues=[]),n)}}),_se=ce("$ZodNaN",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>((typeof n.value!="number"||!Number.isNaN(n.value))&&n.issues.push({input:n.value,inst:t,expected:"nan",code:"invalid_type"}),n)}),WF=ce("$ZodPipe",(t,e)=>{jn.init(t,e),Zr(t._zod,"values",()=>e.in._zod.values),Zr(t._zod,"optin",()=>e.in._zod.optin),Zr(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(i=>r1e(i,e,r)):r1e(o,e,r)}});Sse=ce("$ZodReadonly",(t,e)=>{jn.init(t,e),Zr(t._zod,"propValues",()=>e.innerType._zod.propValues),Zr(t._zod,"values",()=>e.innerType._zod.values),Zr(t._zod,"optin",()=>e.innerType._zod.optin),Zr(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(o1e):o1e(o)}});Tse=ce("$ZodTemplateLiteral",(t,e)=>{jn.init(t,e);let n=[];for(let r of e.parts)if(r instanceof jn){if(!r._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...r._zod.traits].shift()}`);let o=r._zod.pattern instanceof RegExp?r._zod.pattern.source:r._zod.pattern;if(!o)throw new Error(`Invalid template literal part: ${r._zod.traits}`);let i=o.startsWith("^")?1:0,s=o.endsWith("$")?o.length-1:o.length;n.push(o.slice(i,s))}else if(r===null||Coe.has(typeof r))n.push(ww(`${r}`));else throw new Error(`Invalid template literal part: ${r}`);t._zod.pattern=new RegExp(`^${n.join("")}$`),t._zod.parse=(r,o)=>typeof r.value!="string"?(r.issues.push({input:r.value,inst:t,expected:"template_literal",code:"invalid_type"}),r):(t._zod.pattern.lastIndex=0,t._zod.pattern.test(r.value)||r.issues.push({input:r.value,inst:t,code:"invalid_format",format:"template_literal",pattern:t._zod.pattern.source}),r)}),Ise=ce("$ZodPromise",(t,e)=>{jn.init(t,e),t._zod.parse=(n,r)=>Promise.resolve(n.value).then(o=>e.innerType._zod.run({value:o,issues:[]},r))}),Pse=ce("$ZodLazy",(t,e)=>{jn.init(t,e),Zr(t._zod,"innerType",()=>e.getter()),Zr(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Zr(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Zr(t._zod,"optin",()=>t._zod.innerType._zod.optin),Zr(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(n,r)=>t._zod.innerType._zod.run(n,r)}),Ese=ce("$ZodCustom",(t,e)=>{Ti.init(t,e),jn.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(i=>i1e(i,n,r,t));i1e(o,n,r,t)}})});function c1e(){return{localeError:HSt()}}var HSt,u1e=C(()=>{An();HSt=()=>{let t={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"};return o=>{switch(o.code){case"invalid_type":return`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${o.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${ot(o.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${o.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${i} ${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${o.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${o.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${i} ${o.minimum.toString()} ${s.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${o.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${o.prefix}"`:i.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${i.suffix}"`:i.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${i.includes}"`:i.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${i.pattern}`:`${r[i.format]??o.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${o.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${o.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${o.keys.length>1?"\u0629":""}: ${be(o.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${o.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${o.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}}});function d1e(){return{localeError:KSt()}}var KSt,f1e=C(()=>{An();KSt=()=>{let t={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${o.expected}, daxil olan ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${ot(o.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${i}${o.maximum.toString()} ${s.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${o.origin??"d\u0259y\u0259r"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${i.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:i.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${i.suffix}" il\u0259 bitm\u0259lidir`:i.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${i.includes}" daxil olmal\u0131d\u0131r`:i.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${i.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${r[i.format]??o.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${o.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${o.keys.length>1?"lar":""}: ${be(o.keys,", ")}`;case"invalid_key":return`${o.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${o.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}}});function p1e(t,e,n,r){let o=Math.abs(t),i=o%10,s=o%100;return s>=11&&s<=19?r:i===1?e:i>=2&&i<=4?n:r}function m1e(){return{localeError:qSt()}}var qSt,h1e=C(()=>{An();qSt=()=>{let t={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u043B\u0456\u043A";case"object":{if(Array.isArray(o))return"\u043C\u0430\u0441\u0456\u045E";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"};return o=>{switch(o.code){case"invalid_type":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${o.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${ot(o.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);if(s){let a=Number(o.maximum),l=p1e(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${i}${o.maximum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);if(s){let a=Number(o.minimum),l=p1e(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${i}${o.minimum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${o.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${i.includes}"`:i.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${r[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${o.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${be(o.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${o.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${o.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}}});function g1e(){return{localeError:GSt()}}var GSt,y1e=C(()=>{An();GSt=()=>{let t={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"entrada",email:"adre\xE7a electr\xF2nica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return o=>{switch(o.code){case"invalid_type":return`Tipus inv\xE0lid: s'esperava ${o.expected}, s'ha rebut ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Valor inv\xE0lid: s'esperava ${ot(o.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${be(o.values," o ")}`;case"too_big":{let i=o.inclusive?"com a m\xE0xim":"menys de",s=e(o.origin);return s?`Massa gran: s'esperava que ${o.origin??"el valor"} contingu\xE9s ${i} ${o.maximum.toString()} ${s.unit??"elements"}`:`Massa gran: s'esperava que ${o.origin??"el valor"} fos ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?"com a m\xEDnim":"m\xE9s de",s=e(o.origin);return s?`Massa petit: s'esperava que ${o.origin} contingu\xE9s ${i} ${o.minimum.toString()} ${s.unit}`:`Massa petit: s'esperava que ${o.origin} fos ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${i.prefix}"`:i.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${i.suffix}"`:i.format==="includes"?`Format inv\xE0lid: ha d'incloure "${i.includes}"`:i.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${i.pattern}`:`Format inv\xE0lid per a ${r[i.format]??o.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${o.divisor}`;case"unrecognized_keys":return`Clau${o.keys.length>1?"s":""} no reconeguda${o.keys.length>1?"s":""}: ${be(o.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${o.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${o.origin}`;default:return"Entrada inv\xE0lida"}}}});function w1e(){return{localeError:YSt()}}var YSt,v1e=C(()=>{An();YSt=()=>{let t={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u010D\xEDslo";case"string":return"\u0159et\u011Bzec";case"boolean":return"boolean";case"bigint":return"bigint";case"function":return"funkce";case"symbol":return"symbol";case"undefined":return"undefined";case"object":{if(Array.isArray(o))return"pole";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"};return o=>{switch(o.code){case"invalid_type":return`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${o.expected}, obdr\u017Eeno ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${ot(o.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${i}${o.maximum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED m\xEDt ${i}${o.minimum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${o.origin??"hodnota"} mus\xED b\xFDt ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${i.prefix}"`:i.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${i.suffix}"`:i.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${i.includes}"`:i.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${i.pattern}`:`Neplatn\xFD form\xE1t ${r[i.format]??o.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${o.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${be(o.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${o.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${o.origin}`;default:return"Neplatn\xFD vstup"}}}});function x1e(){return{localeError:ZSt()}}var ZSt,b1e=C(()=>{An();ZSt=()=>{let t={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"Zahl";case"object":{if(Array.isArray(o))return"Array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"};return o=>{switch(o.code){case"invalid_type":return`Ung\xFCltige Eingabe: erwartet ${o.expected}, erhalten ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Ung\xFCltige Eingabe: erwartet ${ot(o.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${i}${o.maximum.toString()} ${s.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${o.origin??"Wert"} ${i}${o.maximum.toString()} ist`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Zu klein: erwartet, dass ${o.origin} ${i}${o.minimum.toString()} ${s.unit} hat`:`Zu klein: erwartet, dass ${o.origin} ${i}${o.minimum.toString()} ist`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ung\xFCltiger String: muss mit "${i.prefix}" beginnen`:i.format==="ends_with"?`Ung\xFCltiger String: muss mit "${i.suffix}" enden`:i.format==="includes"?`Ung\xFCltiger String: muss "${i.includes}" enthalten`:i.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${i.pattern} entsprechen`:`Ung\xFCltig: ${r[i.format]??o.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${o.divisor} sein`;case"unrecognized_keys":return`${o.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${be(o.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${o.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${o.origin}`;default:return"Ung\xFCltige Eingabe"}}}});function F6(){return{localeError:XSt()}}var JSt,XSt,Ase=C(()=>{An();JSt=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},XSt=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(r){return t[r]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${JSt(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${ot(r.values[0])}`:`Invalid option: expected one of ${be(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",i=e(r.origin);return i?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${i.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",i=e(r.origin);return i?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${i.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${be(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}}});function C1e(){return{localeError:eTt()}}var QSt,eTt,_1e=C(()=>{An();QSt=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"nombro";case"object":{if(Array.isArray(t))return"tabelo";if(t===null)return"senvalora";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},eTt=()=>{let t={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function e(r){return t[r]??null}let n={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"};return r=>{switch(r.code){case"invalid_type":return`Nevalida enigo: atendi\u011Dis ${r.expected}, ricevi\u011Dis ${QSt(r.input)}`;case"invalid_value":return r.values.length===1?`Nevalida enigo: atendi\u011Dis ${ot(r.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${be(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",i=e(r.origin);return i?`Tro granda: atendi\u011Dis ke ${r.origin??"valoro"} havu ${o}${r.maximum.toString()} ${i.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${r.origin??"valoro"} havu ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",i=e(r.origin);return i?`Tro malgranda: atendi\u011Dis ke ${r.origin} havu ${o}${r.minimum.toString()} ${i.unit}`:`Tro malgranda: atendi\u011Dis ke ${r.origin} estu ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${o.prefix}"`:o.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${o.suffix}"`:o.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${o.includes}"`:o.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${o.pattern}`:`Nevalida ${n[o.format]??r.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${r.divisor}`;case"unrecognized_keys":return`Nekonata${r.keys.length>1?"j":""} \u015Dlosilo${r.keys.length>1?"j":""}: ${be(r.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${r.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${r.origin}`;default:return"Nevalida enigo"}}}});function S1e(){return{localeError:tTt()}}var tTt,T1e=C(()=>{An();tTt=()=>{let t={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(o))return"arreglo";if(o===null)return"nulo";if(Object.getPrototypeOf(o)!==Object.prototype)return o.constructor.name}}return i},r={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return o=>{switch(o.code){case"invalid_type":return`Entrada inv\xE1lida: se esperaba ${o.expected}, recibido ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: se esperaba ${ot(o.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Demasiado grande: se esperaba que ${o.origin??"valor"} tuviera ${i}${o.maximum.toString()} ${s.unit??"elementos"}`:`Demasiado grande: se esperaba que ${o.origin??"valor"} fuera ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Demasiado peque\xF1o: se esperaba que ${o.origin} tuviera ${i}${o.minimum.toString()} ${s.unit}`:`Demasiado peque\xF1o: se esperaba que ${o.origin} fuera ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${i.prefix}"`:i.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${i.suffix}"`:i.format==="includes"?`Cadena inv\xE1lida: debe incluir "${i.includes}"`:i.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${i.pattern}`:`Inv\xE1lido ${r[i.format]??o.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${o.divisor}`;case"unrecognized_keys":return`Llave${o.keys.length>1?"s":""} desconocida${o.keys.length>1?"s":""}: ${be(o.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${o.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${o.origin}`;default:return"Entrada inv\xE1lida"}}}});function I1e(){return{localeError:nTt()}}var nTt,P1e=C(()=>{An();nTt=()=>{let t={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(o))return"\u0622\u0631\u0627\u06CC\u0647";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"};return o=>{switch(o.code){case"invalid_type":return`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${o.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${n(o.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;case"invalid_value":return o.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${ot(o.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${be(o.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${o.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${o.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} ${s.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:i.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${i.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:i.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${i.includes}" \u0628\u0627\u0634\u062F`:i.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${i.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${r[i.format]??o.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${o.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${o.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${be(o.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${o.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${o.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}}});function E1e(){return{localeError:rTt()}}var rTt,A1e=C(()=>{An();rTt=()=>{let t={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"};return o=>{switch(o.code){case"invalid_type":return`Virheellinen tyyppi: odotettiin ${o.expected}, oli ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${ot(o.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Liian suuri: ${s.subject} t\xE4ytyy olla ${i}${o.maximum.toString()} ${s.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Liian pieni: ${s.subject} t\xE4ytyy olla ${i}${o.minimum.toString()} ${s.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${i.prefix}"`:i.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${i.suffix}"`:i.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${i.includes}"`:i.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${i.pattern}`:`Virheellinen ${r[i.format]??o.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${o.divisor} monikerta`;case"unrecognized_keys":return`${o.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${be(o.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}}});function k1e(){return{localeError:oTt()}}var oTt,M1e=C(()=>{An();oTt=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"nombre";case"object":{if(Array.isArray(o))return"tableau";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"entr\xE9e",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return o=>{switch(o.code){case"invalid_type":return`Entr\xE9e invalide : ${o.expected} attendu, ${n(o.input)} re\xE7u`;case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : ${ot(o.values[0])} attendu`:`Option invalide : une valeur parmi ${be(o.values,"|")} attendue`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Trop grand : ${o.origin??"valeur"} doit ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${o.origin??"valeur"} doit \xEAtre ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Trop petit : ${o.origin} doit ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Trop petit : ${o.origin} doit \xEAtre ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${i.pattern}`:`${r[i.format]??o.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${o.divisor}`;case"unrecognized_keys":return`Cl\xE9${o.keys.length>1?"s":""} non reconnue${o.keys.length>1?"s":""} : ${be(o.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${o.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${o.origin}`;default:return"Entr\xE9e invalide"}}}});function N1e(){return{localeError:iTt()}}var iTt,O1e=C(()=>{An();iTt=()=>{let t={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"entr\xE9e",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"};return o=>{switch(o.code){case"invalid_type":return`Entr\xE9e invalide : attendu ${o.expected}, re\xE7u ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Entr\xE9e invalide : attendu ${ot(o.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"\u2264":"<",s=e(o.origin);return s?`Trop grand : attendu que ${o.origin??"la valeur"} ait ${i}${o.maximum.toString()} ${s.unit}`:`Trop grand : attendu que ${o.origin??"la valeur"} soit ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?"\u2265":">",s=e(o.origin);return s?`Trop petit : attendu que ${o.origin} ait ${i}${o.minimum.toString()} ${s.unit}`:`Trop petit : attendu que ${o.origin} soit ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Cha\xEEne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${i.pattern}`:`${r[i.format]??o.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${o.divisor}`;case"unrecognized_keys":return`Cl\xE9${o.keys.length>1?"s":""} non reconnue${o.keys.length>1?"s":""} : ${be(o.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${o.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${o.origin}`;default:return"Entr\xE9e invalide"}}}});function R1e(){return{localeError:sTt()}}var sTt,L1e=C(()=>{An();sTt=()=>{let t={string:{unit:"\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",verb:"\u05DC\u05DB\u05DC\u05D5\u05DC"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u05E7\u05DC\u05D8",email:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",url:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",emoji:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",date:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",time:"\u05D6\u05DE\u05DF ISO",duration:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",ipv4:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",ipv6:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",cidrv4:"\u05D8\u05D5\u05D5\u05D7 IPv4",cidrv6:"\u05D8\u05D5\u05D5\u05D7 IPv6",base64:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",base64url:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",json_string:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",e164:"\u05DE\u05E1\u05E4\u05E8 E.164",jwt:"JWT",template_literal:"\u05E7\u05DC\u05D8"};return o=>{switch(o.code){case"invalid_type":return`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${o.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${ot(o.values[0])}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA  ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${o.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${i}${o.maximum.toString()} ${s.unit??"elements"}`:`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${o.origin??"value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${o.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${i}${o.minimum.toString()} ${s.unit}`:`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${o.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${i.prefix}"`:i.format==="ends_with"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${i.suffix}"`:i.format==="includes"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${i.includes}"`:i.format==="regex"?`\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${i.pattern}`:`${r[i.format]??o.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${o.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${o.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${o.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${be(o.keys,", ")}`;case"invalid_key":return`\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${o.origin}`;case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${o.origin}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}}});function D1e(){return{localeError:aTt()}}var aTt,$1e=C(()=>{An();aTt=()=>{let t={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"sz\xE1m";case"object":{if(Array.isArray(o))return"t\xF6mb";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"bemenet",email:"email c\xEDm",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"};return o=>{switch(o.code){case"invalid_type":return`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${o.expected}, a kapott \xE9rt\xE9k ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${ot(o.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`T\xFAl nagy: ${o.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${i}${o.maximum.toString()} ${s.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${o.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} m\xE9rete t\xFAl kicsi ${i}${o.minimum.toString()} ${s.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${o.origin} t\xFAl kicsi ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\xC9rv\xE9nytelen string: "${i.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:i.format==="ends_with"?`\xC9rv\xE9nytelen string: "${i.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:i.format==="includes"?`\xC9rv\xE9nytelen string: "${i.includes}" \xE9rt\xE9ket kell tartalmaznia`:i.format==="regex"?`\xC9rv\xE9nytelen string: ${i.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${r[i.format]??o.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${o.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${o.keys.length>1?"s":""}: ${be(o.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${o.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${o.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}}});function F1e(){return{localeError:lTt()}}var lTt,U1e=C(()=>{An();lTt=()=>{let t={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Input tidak valid: diharapkan ${o.expected}, diterima ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Input tidak valid: diharapkan ${ot(o.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Terlalu besar: diharapkan ${o.origin??"value"} memiliki ${i}${o.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: diharapkan ${o.origin??"value"} menjadi ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Terlalu kecil: diharapkan ${o.origin} memiliki ${i}${o.minimum.toString()} ${s.unit}`:`Terlalu kecil: diharapkan ${o.origin} menjadi ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`String tidak valid: harus dimulai dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak valid: harus berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak valid: harus menyertakan "${i.includes}"`:i.format==="regex"?`String tidak valid: harus sesuai pola ${i.pattern}`:`${r[i.format]??o.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${o.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${o.keys.length>1?"s":""}: ${be(o.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${o.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${o.origin}`;default:return"Input tidak valid"}}}});function B1e(){return{localeError:cTt()}}var cTt,z1e=C(()=>{An();cTt=()=>{let t={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"numero";case"object":{if(Array.isArray(o))return"vettore";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Input non valido: atteso ${o.expected}, ricevuto ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Input non valido: atteso ${ot(o.values[0])}`:`Opzione non valida: atteso uno tra ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Troppo grande: ${o.origin??"valore"} deve avere ${i}${o.maximum.toString()} ${s.unit??"elementi"}`:`Troppo grande: ${o.origin??"valore"} deve essere ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Troppo piccolo: ${o.origin} deve avere ${i}${o.minimum.toString()} ${s.unit}`:`Troppo piccolo: ${o.origin} deve essere ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Stringa non valida: deve iniziare con "${i.prefix}"`:i.format==="ends_with"?`Stringa non valida: deve terminare con "${i.suffix}"`:i.format==="includes"?`Stringa non valida: deve includere "${i.includes}"`:i.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${o.divisor}`;case"unrecognized_keys":return`Chiav${o.keys.length>1?"i":"e"} non riconosciut${o.keys.length>1?"e":"a"}: ${be(o.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${o.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${o.origin}`;default:return"Input non valido"}}}});function j1e(){return{localeError:uTt()}}var uTt,V1e=C(()=>{An();uTt=()=>{let t={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u6570\u5024";case"object":{if(Array.isArray(o))return"\u914D\u5217";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"};return o=>{switch(o.code){case"invalid_type":return`\u7121\u52B9\u306A\u5165\u529B: ${o.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${n(o.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;case"invalid_value":return o.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${ot(o.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${be(o.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let i=o.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",s=e(o.origin);return s?`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${s.unit??"\u8981\u7D20"}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${o.origin??"\u5024"}\u306F${o.maximum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let i=o.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",s=e(o.origin);return s?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${s.unit}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${o.origin}\u306F${o.minimum.toString()}${i}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${i.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:i.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${i.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${r[i.format]??o.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${o.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${o.keys.length>1?"\u7FA4":""}: ${be(o.keys,"\u3001")}`;case"invalid_key":return`${o.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${o.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}}});function W1e(){return{localeError:dTt()}}var dTt,H1e=C(()=>{An();dTt=()=>{let t={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)":"\u179B\u17C1\u1781";case"object":{if(Array.isArray(o))return"\u17A2\u17B6\u179A\u17C1 (Array)";if(o===null)return"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"};return o=>{switch(o.code){case"invalid_type":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${ot(o.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${i} ${o.maximum.toString()} ${s.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${i} ${o.minimum.toString()} ${s.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o.origin} ${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${i.prefix}"`:i.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${i.suffix}"`:i.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${i.includes}"`:i.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${i.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${o.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${be(o.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${o.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${o.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}}});function K1e(){return{localeError:fTt()}}var fTt,q1e=C(()=>{An();fTt=()=>{let t={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"};return o=>{switch(o.code){case"invalid_type":return`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${o.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${n(o.input)}\uC785\uB2C8\uB2E4`;case"invalid_value":return o.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${ot(o.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${be(o.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let i=o.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",s=i==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(o.origin),l=a?.unit??"\uC694\uC18C";return a?`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${o.maximum.toString()}${l} ${i}${s}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${o.maximum.toString()} ${i}${s}`}case"too_small":{let i=o.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",s=i==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(o.origin),l=a?.unit??"\uC694\uC18C";return a?`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${o.minimum.toString()}${l} ${i}${s}`:`${o.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${o.minimum.toString()} ${i}${s}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:i.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${i.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:i.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${i.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${r[i.format]??o.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${o.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${be(o.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${o.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${o.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}}});function G1e(){return{localeError:pTt()}}var pTt,Y1e=C(()=>{An();pTt=()=>{let t={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0431\u0440\u043E\u0458";case"object":{if(Array.isArray(o))return"\u043D\u0438\u0437\u0430";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"};return o=>{switch(o.code){case"invalid_type":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Invalid input: expected ${ot(o.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${i}${o.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin} \u0434\u0430 \u0438\u043C\u0430 ${i}${o.minimum.toString()} ${s.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${i.pattern}`:`Invalid ${r[i.format]??o.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${be(o.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${o.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${o.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}}});function Z1e(){return{localeError:mTt()}}var mTt,J1e=C(()=>{An();mTt=()=>{let t={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"nombor";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Input tidak sah: dijangka ${o.expected}, diterima ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Input tidak sah: dijangka ${ot(o.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Terlalu besar: dijangka ${o.origin??"nilai"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: dijangka ${o.origin??"nilai"} adalah ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Terlalu kecil: dijangka ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Terlalu kecil: dijangka ${o.origin} adalah ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`String tidak sah: mesti bermula dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak sah: mesti mengandungi "${i.includes}"`:i.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${i.pattern}`:`${r[i.format]??o.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${o.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${be(o.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${o.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${o.origin}`;default:return"Input tidak sah"}}}});function X1e(){return{localeError:hTt()}}var hTt,Q1e=C(()=>{An();hTt=()=>{let t={string:{unit:"tekens"},file:{unit:"bytes"},array:{unit:"elementen"},set:{unit:"elementen"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"getal";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"};return o=>{switch(o.code){case"invalid_type":return`Ongeldige invoer: verwacht ${o.expected}, ontving ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Ongeldige invoer: verwacht ${ot(o.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Te lang: verwacht dat ${o.origin??"waarde"} ${i}${o.maximum.toString()} ${s.unit??"elementen"} bevat`:`Te lang: verwacht dat ${o.origin??"waarde"} ${i}${o.maximum.toString()} is`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Te kort: verwacht dat ${o.origin} ${i}${o.minimum.toString()} ${s.unit} bevat`:`Te kort: verwacht dat ${o.origin} ${i}${o.minimum.toString()} is`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ongeldige tekst: moet met "${i.prefix}" beginnen`:i.format==="ends_with"?`Ongeldige tekst: moet op "${i.suffix}" eindigen`:i.format==="includes"?`Ongeldige tekst: moet "${i.includes}" bevatten`:i.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${i.pattern}`:`Ongeldig: ${r[i.format]??o.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${o.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${o.keys.length>1?"s":""}: ${be(o.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${o.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${o.origin}`;default:return"Ongeldige invoer"}}}});function eDe(){return{localeError:gTt()}}var gTt,tDe=C(()=>{An();gTt=()=>{let t={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"tall";case"object":{if(Array.isArray(o))return"liste";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`Ugyldig input: forventet ${o.expected}, fikk ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Ugyldig verdi: forventet ${ot(o.values[0])}`:`Ugyldig valg: forventet en av ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${i}${o.maximum.toString()} ${s.unit??"elementer"}`:`For stor(t): forventet ${o.origin??"value"} til \xE5 ha ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`For lite(n): forventet ${o.origin} til \xE5 ha ${i}${o.minimum.toString()} ${s.unit}`:`For lite(n): forventet ${o.origin} til \xE5 ha ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${i.pattern}`:`Ugyldig ${r[i.format]??o.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${be(o.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${o.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${o.origin}`;default:return"Ugyldig input"}}}});function nDe(){return{localeError:yTt()}}var yTt,rDe=C(()=>{An();yTt=()=>{let t={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"numara";case"object":{if(Array.isArray(o))return"saf";if(o===null)return"gayb";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"giren",email:"epostag\xE2h",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"};return o=>{switch(o.code){case"invalid_type":return`F\xE2sit giren: umulan ${o.expected}, al\u0131nan ${n(o.input)}`;case"invalid_value":return o.values.length===1?`F\xE2sit giren: umulan ${ot(o.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${i}${o.maximum.toString()} ${s.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${o.origin??"value"}, ${i}${o.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${i}${o.minimum.toString()} ${s.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${o.origin}, ${i}${o.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let i=o;return i.format==="starts_with"?`F\xE2sit metin: "${i.prefix}" ile ba\u015Flamal\u0131.`:i.format==="ends_with"?`F\xE2sit metin: "${i.suffix}" ile bitmeli.`:i.format==="includes"?`F\xE2sit metin: "${i.includes}" ihtiv\xE2 etmeli.`:i.format==="regex"?`F\xE2sit metin: ${i.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${r[i.format]??o.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${o.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${o.keys.length>1?"s":""}: ${be(o.keys,", ")}`;case"invalid_key":return`${o.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${o.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}}});function oDe(){return{localeError:wTt()}}var wTt,iDe=C(()=>{An();wTt=()=>{let t={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0639\u062F\u062F";case"object":{if(Array.isArray(o))return"\u0627\u0631\u06D0";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"};return o=>{switch(o.code){case"invalid_type":return`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${o.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${n(o.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;case"invalid_value":return o.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${ot(o.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${be(o.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${o.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${o.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${i}${o.maximum.toString()} \u0648\u064A`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} ${s.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${o.origin} \u0628\u0627\u06CC\u062F ${i}${o.minimum.toString()} \u0648\u064A`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:i.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${i.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:i.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${i.includes}" \u0648\u0644\u0631\u064A`:i.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${i.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${r[i.format]??o.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${o.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${o.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${be(o.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${o.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${o.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}}});function sDe(){return{localeError:vTt()}}var vTt,aDe=C(()=>{An();vTt=()=>{let t={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"liczba";case"object":{if(Array.isArray(o))return"tablica";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"wyra\u017Cenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"};return o=>{switch(o.code){case"invalid_type":return`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${o.expected}, otrzymano ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${ot(o.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${o.maximum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${i}${o.minimum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${o.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${i.prefix}"`:i.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${i.suffix}"`:i.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${i.includes}"`:i.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${i.pattern}`:`Nieprawid\u0142ow(y/a/e) ${r[i.format]??o.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${o.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${o.keys.length>1?"s":""}: ${be(o.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${o.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${o.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}}});function lDe(){return{localeError:xTt()}}var xTt,cDe=C(()=>{An();xTt=()=>{let t={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"n\xFAmero";case"object":{if(Array.isArray(o))return"array";if(o===null)return"nulo";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"padr\xE3o",email:"endere\xE7o de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"};return o=>{switch(o.code){case"invalid_type":return`Tipo inv\xE1lido: esperado ${o.expected}, recebido ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Entrada inv\xE1lida: esperado ${ot(o.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Muito grande: esperado que ${o.origin??"valor"} tivesse ${i}${o.maximum.toString()} ${s.unit??"elementos"}`:`Muito grande: esperado que ${o.origin??"valor"} fosse ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Muito pequeno: esperado que ${o.origin} tivesse ${i}${o.minimum.toString()} ${s.unit}`:`Muito pequeno: esperado que ${o.origin} fosse ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${i.prefix}"`:i.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${i.suffix}"`:i.format==="includes"?`Texto inv\xE1lido: deve incluir "${i.includes}"`:i.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${i.pattern}`:`${r[i.format]??o.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${o.divisor}`;case"unrecognized_keys":return`Chave${o.keys.length>1?"s":""} desconhecida${o.keys.length>1?"s":""}: ${be(o.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${o.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${o.origin}`;default:return"Campo inv\xE1lido"}}}});function uDe(t,e,n,r){let o=Math.abs(t),i=o%10,s=o%100;return s>=11&&s<=19?r:i===1?e:i>=2&&i<=4?n:r}function dDe(){return{localeError:bTt()}}var bTt,fDe=C(()=>{An();bTt=()=>{let t={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(o))return"\u043C\u0430\u0441\u0441\u0438\u0432";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"};return o=>{switch(o.code){case"invalid_type":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${o.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${ot(o.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);if(s){let a=Number(o.maximum),l=uDe(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${i}${o.maximum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);if(s){let a=Number(o.minimum),l=uDe(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${i}${o.minimum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${o.origin} \u0431\u0443\u0434\u0435\u0442 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${o.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${o.keys.length>1?"\u0438":""}: ${be(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${o.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}}});function pDe(){return{localeError:CTt()}}var CTt,mDe=C(()=>{An();CTt=()=>{let t={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0161tevilo";case"object":{if(Array.isArray(o))return"tabela";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"vnos",email:"e-po\u0161tni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"};return o=>{switch(o.code){case"invalid_type":return`Neveljaven vnos: pri\u010Dakovano ${o.expected}, prejeto ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${ot(o.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} imelo ${i}${o.maximum.toString()} ${s.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${o.origin??"vrednost"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Premajhno: pri\u010Dakovano, da bo ${o.origin} imelo ${i}${o.minimum.toString()} ${s.unit}`:`Premajhno: pri\u010Dakovano, da bo ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${i.prefix}"`:i.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${i.suffix}"`:i.format==="includes"?`Neveljaven niz: mora vsebovati "${i.includes}"`:i.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${i.pattern}`:`Neveljaven ${r[i.format]??o.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${o.divisor}`;case"unrecognized_keys":return`Neprepoznan${o.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${be(o.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${o.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${o.origin}`;default:return"Neveljaven vnos"}}}});function hDe(){return{localeError:_Tt()}}var _Tt,gDe=C(()=>{An();_Tt=()=>{let t={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"antal";case"object":{if(Array.isArray(o))return"lista";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"regulj\xE4rt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"};return o=>{switch(o.code){case"invalid_type":return`Ogiltig inmatning: f\xF6rv\xE4ntat ${o.expected}, fick ${n(o.input)}`;case"invalid_value":return o.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${ot(o.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`F\xF6r stor(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.maximum.toString()} ${s.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${o.origin??"v\xE4rdet"} att ha ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.minimum.toString()} ${s.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${o.origin??"v\xE4rdet"} att ha ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${i.prefix}"`:i.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${i.suffix}"`:i.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${i.includes}"`:i.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${i.pattern}"`:`Ogiltig(t) ${r[i.format]??o.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${o.divisor}`;case"unrecognized_keys":return`${o.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${be(o.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${o.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${o.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}}});function yDe(){return{localeError:STt()}}var STt,wDe=C(()=>{An();STt=()=>{let t={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1":"\u0B8E\u0BA3\u0BCD";case"object":{if(Array.isArray(o))return"\u0B85\u0BA3\u0BBF";if(o===null)return"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"};return o=>{switch(o.code){case"invalid_type":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${ot(o.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${be(o.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${i}${o.maximum.toString()} ${s.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${i}${o.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin} ${i}${o.minimum.toString()} ${s.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o.origin} ${i}${o.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${i.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:i.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${i.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${o.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${o.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${be(o.keys,", ")}`;case"invalid_key":return`${o.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${o.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}}});function vDe(){return{localeError:TTt()}}var TTt,xDe=C(()=>{An();TTt=()=>{let t={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)":"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";case"object":{if(Array.isArray(o))return"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";if(o===null)return"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"};return o=>{switch(o.code){case"invalid_type":return`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${o.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${ot(o.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",s=e(o.origin);return s?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.maximum.toString()} ${s.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",s=e(o.origin);return s?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.minimum.toString()} ${s.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${o.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${i} ${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${i.prefix}"`:i.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${i.suffix}"`:i.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${i.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:i.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${i.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${r[i.format]??o.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${o.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${be(o.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${o.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${o.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}}});function bDe(){return{localeError:PTt()}}var ITt,PTt,CDe=C(()=>{An();ITt=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},PTt=()=>{let t={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function e(r){return t[r]??null}let n={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"};return r=>{switch(r.code){case"invalid_type":return`Ge\xE7ersiz de\u011Fer: beklenen ${r.expected}, al\u0131nan ${ITt(r.input)}`;case"invalid_value":return r.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${ot(r.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${be(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",i=e(r.origin);return i?`\xC7ok b\xFCy\xFCk: beklenen ${r.origin??"de\u011Fer"} ${o}${r.maximum.toString()} ${i.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${r.origin??"de\u011Fer"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",i=e(r.origin);return i?`\xC7ok k\xFC\xE7\xFCk: beklenen ${r.origin} ${o}${r.minimum.toString()} ${i.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ge\xE7ersiz metin: "${o.prefix}" ile ba\u015Flamal\u0131`:o.format==="ends_with"?`Ge\xE7ersiz metin: "${o.suffix}" ile bitmeli`:o.format==="includes"?`Ge\xE7ersiz metin: "${o.includes}" i\xE7ermeli`:o.format==="regex"?`Ge\xE7ersiz metin: ${o.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${n[o.format]??r.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${r.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${r.keys.length>1?"lar":""}: ${be(r.keys,", ")}`;case"invalid_key":return`${r.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${r.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}}});function _De(){return{localeError:ETt()}}var ETt,SDe=C(()=>{An();ETt=()=>{let t={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0447\u0438\u0441\u043B\u043E";case"object":{if(Array.isArray(o))return"\u043C\u0430\u0441\u0438\u0432";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"};return o=>{switch(o.code){case"invalid_type":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${o.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${ot(o.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${o.origin} \u0431\u0443\u0434\u0435 ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${i.prefix}"`:i.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${i.suffix}"`:i.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${i.includes}"`:i.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${i.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${o.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${o.keys.length>1?"\u0456":""}: ${be(o.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${o.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${o.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}}});function TDe(){return{localeError:ATt()}}var ATt,IDe=C(()=>{An();ATt=()=>{let t={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"\u0646\u0645\u0628\u0631";case"object":{if(Array.isArray(o))return"\u0622\u0631\u06D2";if(o===null)return"\u0646\u0644";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"};return o=>{switch(o.code){case"invalid_type":return`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${o.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${n(o.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;case"invalid_value":return o.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${ot(o.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${be(o.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${o.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${i}${o.maximum.toString()} ${s.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${o.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${i}${o.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${o.origin} \u06A9\u06D2 ${i}${o.minimum.toString()} ${s.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${o.origin} \u06A9\u0627 ${i}${o.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${i.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:i.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${i.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${o.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${o.keys.length>1?"\u0632":""}: ${be(o.keys,"\u060C ")}`;case"invalid_key":return`${o.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${o.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}}});function PDe(){return{localeError:kTt()}}var kTt,EDe=C(()=>{An();kTt=()=>{let t={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"s\u1ED1";case"object":{if(Array.isArray(o))return"m\u1EA3ng";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"};return o=>{switch(o.code){case"invalid_type":return`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${o.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${ot(o.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${s.verb} ${i}${o.maximum.toString()} ${s.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${o.origin??"gi\xE1 tr\u1ECB"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${s.verb} ${i}${o.minimum.toString()} ${s.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${i.prefix}"`:i.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${i.suffix}"`:i.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${i.includes}"`:i.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${i.pattern}`:`${r[i.format]??o.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${o.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${be(o.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${o.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${o.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}}});function ADe(){return{localeError:MTt()}}var MTt,kDe=C(()=>{An();MTt=()=>{let t={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"\u975E\u6570\u5B57(NaN)":"\u6570\u5B57";case"object":{if(Array.isArray(o))return"\u6570\u7EC4";if(o===null)return"\u7A7A\u503C(null)";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"};return o=>{switch(o.code){case"invalid_type":return`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${o.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${ot(o.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${i}${o.maximum.toString()} ${s.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${o.origin??"\u503C"} ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${i}${o.minimum.toString()} ${s.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${o.origin} ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.prefix}" \u5F00\u5934`:i.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${i.suffix}" \u7ED3\u5C3E`:i.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${i.pattern}`:`\u65E0\u6548${r[i.format]??o.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${o.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${be(o.keys,", ")}`;case"invalid_key":return`${o.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${o.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}}});function MDe(){return{localeError:NTt()}}var NTt,NDe=C(()=>{An();NTt=()=>{let t={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function e(o){return t[o]??null}let n=o=>{let i=typeof o;switch(i){case"number":return Number.isNaN(o)?"NaN":"number";case"object":{if(Array.isArray(o))return"array";if(o===null)return"null";if(Object.getPrototypeOf(o)!==Object.prototype&&o.constructor)return o.constructor.name}}return i},r={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"};return o=>{switch(o.code){case"invalid_type":return`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${o.expected}\uFF0C\u4F46\u6536\u5230 ${n(o.input)}`;case"invalid_value":return o.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${ot(o.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${be(o.values,"|")}`;case"too_big":{let i=o.inclusive?"<=":"<",s=e(o.origin);return s?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${i}${o.maximum.toString()} ${s.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${o.origin??"\u503C"} \u61C9\u70BA ${i}${o.maximum.toString()}`}case"too_small":{let i=o.inclusive?">=":">",s=e(o.origin);return s?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${i}${o.minimum.toString()} ${s.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${o.origin} \u61C9\u70BA ${i}${o.minimum.toString()}`}case"invalid_format":{let i=o;return i.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.prefix}" \u958B\u982D`:i.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${i.suffix}" \u7D50\u5C3E`:i.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${i.includes}"`:i.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${i.pattern}`:`\u7121\u6548\u7684 ${r[i.format]??o.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${o.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${o.keys.length>1?"\u5011":""}\uFF1A${be(o.keys,"\u3001")}`;case"invalid_key":return`${o.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${o.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}}});var KF={};zn(KF,{ar:()=>c1e,az:()=>d1e,be:()=>m1e,ca:()=>g1e,cs:()=>w1e,de:()=>x1e,en:()=>F6,eo:()=>C1e,es:()=>S1e,fa:()=>I1e,fi:()=>E1e,fr:()=>k1e,frCA:()=>N1e,he:()=>R1e,hu:()=>D1e,id:()=>F1e,it:()=>B1e,ja:()=>j1e,kh:()=>W1e,ko:()=>K1e,mk:()=>G1e,ms:()=>Z1e,nl:()=>X1e,no:()=>eDe,ota:()=>nDe,pl:()=>sDe,ps:()=>oDe,pt:()=>lDe,ru:()=>dDe,sl:()=>pDe,sv:()=>hDe,ta:()=>yDe,th:()=>vDe,tr:()=>bDe,ua:()=>_De,ur:()=>TDe,vi:()=>PDe,zhCN:()=>ADe,zhTW:()=>MDe});var kse=C(()=>{u1e();f1e();h1e();y1e();v1e();b1e();Ase();_1e();T1e();P1e();A1e();M1e();O1e();L1e();$1e();U1e();z1e();V1e();H1e();q1e();Y1e();J1e();Q1e();tDe();rDe();iDe();aDe();cDe();fDe();mDe();gDe();wDe();xDe();CDe();SDe();IDe();EDe();kDe();NDe()});function U6(){return new Ek}var Mse,Nse,Ek,Oa,Ose=C(()=>{Mse=Symbol("ZodOutput"),Nse=Symbol("ZodInput"),Ek=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};Oa=U6()});function Rse(t,e){return new t({type:"string",...We(e)})}function Lse(t,e){return new t({type:"string",coerce:!0,...We(e)})}function B6(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...We(e)})}function qF(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...We(e)})}function z6(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...We(e)})}function j6(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...We(e)})}function V6(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...We(e)})}function W6(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...We(e)})}function H6(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...We(e)})}function K6(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...We(e)})}function q6(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...We(e)})}function G6(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...We(e)})}function Y6(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...We(e)})}function Z6(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...We(e)})}function J6(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...We(e)})}function X6(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...We(e)})}function Q6(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...We(e)})}function e3(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...We(e)})}function t3(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...We(e)})}function n3(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...We(e)})}function r3(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...We(e)})}function o3(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...We(e)})}function i3(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...We(e)})}function s3(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...We(e)})}function $se(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...We(e)})}function Fse(t,e){return new t({type:"string",format:"date",check:"string_format",...We(e)})}function Use(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...We(e)})}function Bse(t,e){return new t({type:"string",format:"duration",check:"string_format",...We(e)})}function zse(t,e){return new t({type:"number",checks:[],...We(e)})}function jse(t,e){return new t({type:"number",coerce:!0,checks:[],...We(e)})}function Vse(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...We(e)})}function Wse(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float32",...We(e)})}function Hse(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"float64",...We(e)})}function Kse(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"int32",...We(e)})}function qse(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"uint32",...We(e)})}function Gse(t,e){return new t({type:"boolean",...We(e)})}function Yse(t,e){return new t({type:"boolean",coerce:!0,...We(e)})}function Zse(t,e){return new t({type:"bigint",...We(e)})}function Jse(t,e){return new t({type:"bigint",coerce:!0,...We(e)})}function Xse(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...We(e)})}function Qse(t,e){return new t({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...We(e)})}function eae(t,e){return new t({type:"symbol",...We(e)})}function tae(t,e){return new t({type:"undefined",...We(e)})}function nae(t,e){return new t({type:"null",...We(e)})}function rae(t){return new t({type:"any"})}function TT(t){return new t({type:"unknown"})}function GF(t,e){return new t({type:"never",...We(e)})}function oae(t,e){return new t({type:"void",...We(e)})}function iae(t,e){return new t({type:"date",...We(e)})}function sae(t,e){return new t({type:"date",coerce:!0,...We(e)})}function aae(t,e){return new t({type:"nan",...We(e)})}function vw(t,e){return new A6({check:"less_than",...We(e),value:t,inclusive:!1})}function Yf(t,e){return new A6({check:"less_than",...We(e),value:t,inclusive:!0})}function xw(t,e){return new k6({check:"greater_than",...We(e),value:t,inclusive:!1})}function Du(t,e){return new k6({check:"greater_than",...We(e),value:t,inclusive:!0})}function lae(t){return xw(0,t)}function cae(t){return vw(0,t)}function uae(t){return Yf(0,t)}function dae(t){return Du(0,t)}function IT(t,e){return new aie({check:"multiple_of",...We(e),value:t})}function Ak(t,e){return new uie({check:"max_size",...We(e),maximum:t})}function PT(t,e){return new die({check:"min_size",...We(e),minimum:t})}function YF(t,e){return new fie({check:"size_equals",...We(e),size:t})}function kk(t,e){return new pie({check:"max_length",...We(e),maximum:t})}function Ib(t,e){return new mie({check:"min_length",...We(e),minimum:t})}function Mk(t,e){return new hie({check:"length_equals",...We(e),length:t})}function ZF(t,e){return new gie({check:"string_format",format:"regex",...We(e),pattern:t})}function JF(t){return new yie({check:"string_format",format:"lowercase",...We(t)})}function XF(t){return new wie({check:"string_format",format:"uppercase",...We(t)})}function QF(t,e){return new vie({check:"string_format",format:"includes",...We(e),includes:t})}function e2(t,e){return new xie({check:"string_format",format:"starts_with",...We(e),prefix:t})}function t2(t,e){return new bie({check:"string_format",format:"ends_with",...We(e),suffix:t})}function fae(t,e,n){return new Cie({check:"property",property:t,schema:e,...We(n)})}function n2(t,e){return new _ie({check:"mime_type",mime:t,...We(e)})}function bw(t){return new Sie({check:"overwrite",tx:t})}function r2(t){return bw(e=>e.normalize(t))}function o2(){return bw(t=>t.trim())}function i2(){return bw(t=>t.toLowerCase())}function s2(){return bw(t=>t.toUpperCase())}function a2(t,e,n){return new t({type:"array",element:e,...We(n)})}function OTt(t,e,n){return new t({type:"union",options:e,...We(n)})}function RTt(t,e,n,r){return new t({type:"union",options:n,discriminator:e,...We(r)})}function LTt(t,e,n){return new t({type:"intersection",left:e,right:n})}function pae(t,e,n,r){let o=n instanceof jn,i=o?r:n,s=o?n:null;return new t({type:"tuple",items:e,rest:s,...We(i)})}function DTt(t,e,n,r){return new t({type:"record",keyType:e,valueType:n,...We(r)})}function $Tt(t,e,n,r){return new t({type:"map",keyType:e,valueType:n,...We(r)})}function FTt(t,e,n){return new t({type:"set",valueType:e,...We(n)})}function UTt(t,e,n){let r=Array.isArray(e)?Object.fromEntries(e.map(o=>[o,o])):e;return new t({type:"enum",entries:r,...We(n)})}function BTt(t,e,n){return new t({type:"enum",entries:e,...We(n)})}function zTt(t,e,n){return new t({type:"literal",values:Array.isArray(e)?e:[e],...We(n)})}function mae(t,e){return new t({type:"file",...We(e)})}function jTt(t,e){return new t({type:"transform",transform:e})}function VTt(t,e){return new t({type:"optional",innerType:e})}function WTt(t,e){return new t({type:"nullable",innerType:e})}function HTt(t,e,n){return new t({type:"default",innerType:e,get defaultValue(){return typeof n=="function"?n():n}})}function KTt(t,e,n){return new t({type:"nonoptional",innerType:e,...We(n)})}function qTt(t,e){return new t({type:"success",innerType:e})}function GTt(t,e,n){return new t({type:"catch",innerType:e,catchValue:typeof n=="function"?n:()=>n})}function YTt(t,e,n){return new t({type:"pipe",in:e,out:n})}function ZTt(t,e){return new t({type:"readonly",innerType:e})}function JTt(t,e,n){return new t({type:"template_literal",parts:e,...We(n)})}function XTt(t,e){return new t({type:"lazy",getter:e})}function QTt(t,e){return new t({type:"promise",innerType:e})}function hae(t,e,n){let r=We(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function gae(t,e,n){return new t({type:"custom",check:"custom",fn:e,...We(n)})}function yae(t,e){let n=We(e),r=n.truthy??["true","1","yes","on","y","enabled"],o=n.falsy??["false","0","no","off","n","disabled"];n.case!=="sensitive"&&(r=r.map(m=>typeof m=="string"?m.toLowerCase():m),o=o.map(m=>typeof m=="string"?m.toLowerCase():m));let i=new Set(r),s=new Set(o),a=t.Pipe??WF,l=t.Boolean??BF,c=t.String??CT,u=t.Transform??VF,d=new u({type:"transform",transform:(m,h)=>{let g=m;return n.case!=="sensitive"&&(g=g.toLowerCase()),i.has(g)?!0:s.has(g)?!1:(h.issues.push({code:"invalid_value",expected:"stringbool",values:[...i,...s],input:h.value,inst:d}),{})},error:n.error}),f=new a({type:"pipe",in:new c({type:"string",error:n.error}),out:d,error:n.error});return new a({type:"pipe",in:f,out:new l({type:"boolean",error:n.error}),error:n.error})}function wae(t,e,n,r={}){let o=We(r),i={...We(r),check:"string_format",type:"string",format:e,fn:typeof n=="function"?n:a=>n.test(a),...o};return n instanceof RegExp&&(i.pattern=n),new t(i)}var Dse,vae=C(()=>{M6();HF();An();Dse={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function xae(t){return new a3({type:"function",input:Array.isArray(t?.input)?pae(ST,t?.input):t?.input??a2(jF,TT(_T)),output:t?.output??TT(_T)})}var a3,ODe=C(()=>{vae();I6();HF();HF();a3=class{constructor(e){this._def=e,this.def=e}implement(e){if(typeof e!="function")throw new Error("implement() must be called with a function");let n=(...r)=>{let o=this._def.input?wT(this._def.input,r,void 0,{callee:n}):r;if(!Array.isArray(o))throw new Error("Invalid arguments schema: not an array or tuple schema.");let i=e(...o);return this._def.output?wT(this._def.output,i,void 0,{callee:n}):i};return n}implementAsync(e){if(typeof e!="function")throw new Error("implement() must be called with a function");let n=async(...r)=>{let o=this._def.input?await vT(this._def.input,r,void 0,{callee:n}):r;if(!Array.isArray(o))throw new Error("Invalid arguments schema: not an array or tuple schema.");let i=await e(...o);return this._def.output?vT(this._def.output,i,void 0,{callee:n}):i};return n}input(...e){let n=this.constructor;return Array.isArray(e[0])?new n({type:"function",input:new ST({type:"tuple",items:e[0],rest:e[1]}),output:this._def.output}):new n({type:"function",input:e[0],output:this._def.output})}output(e){let n=this.constructor;return new n({type:"function",input:this._def.input,output:e})}}});function Pb(t,e){if(t instanceof Ek){let r=new l2(e),o={};for(let a of t._idmap.entries()){let[l,c]=a;r.process(c)}let i={},s={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[l,c]=a;i[l]=r.emit(c,{...e,external:s})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";i.__shared={[a]:o}}return{schemas:i}}let n=new l2(e);return n.process(t),n.emit(t,e)}function zs(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return zs(o.element,n);case"object":{for(let i in o.shape)if(zs(o.shape[i],n))return!0;return!1}case"union":{for(let i of o.options)if(zs(i,n))return!0;return!1}case"intersection":return zs(o.left,n)||zs(o.right,n);case"tuple":{for(let i of o.items)if(zs(i,n))return!0;return!!(o.rest&&zs(o.rest,n))}case"record":return zs(o.keyType,n)||zs(o.valueType,n);case"map":return zs(o.keyType,n)||zs(o.valueType,n);case"set":return zs(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return zs(o.innerType,n);case"lazy":return zs(o.getter(),n);case"default":return zs(o.innerType,n);case"prefault":return zs(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return zs(o.in,n)||zs(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var l2,RDe=C(()=>{Ose();An();l2=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Oa,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,i={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},s=this.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let l=e._zod.toJSONSchema?.();if(l)a.schema=l;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let p=a.schema;switch(o.type){case"string":{let m=p;m.type="string";let{minimum:h,maximum:g,format:y,patterns:w,contentEncoding:v}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof g=="number"&&(m.maxLength=g),y&&(m.format=i[y]??y,m.format===""&&delete m.format),v&&(m.contentEncoding=v),w&&w.size>0){let x=[...w];x.length===1?m.pattern=x[0].source:x.length>1&&(a.schema.allOf=[...x.map(b=>({...this.target==="draft-7"?{type:"string"}:{},pattern:b.source}))])}break}case"number":{let m=p,{minimum:h,maximum:g,format:y,multipleOf:w,exclusiveMaximum:v,exclusiveMinimum:x}=e._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof x=="number"&&(m.exclusiveMinimum=x),typeof h=="number"&&(m.minimum=h,typeof x=="number"&&(x>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof v=="number"&&(m.exclusiveMaximum=v),typeof g=="number"&&(m.maximum=g,typeof v=="number"&&(v<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof w=="number"&&(m.multipleOf=w);break}case"boolean":{let m=p;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{p.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{p.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=p,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=p;m.type="object",m.properties={};let h=o.shape;for(let w in h)m.properties[w]=this.process(h[w],{...d,path:[...d.path,"properties",w]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(w=>{let v=o.shape[w]._zod;return this.io==="input"?v.optin===void 0:v.optout===void 0}));y.size>0&&(m.required=Array.from(y)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=p;m.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=p,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=v=>"allOf"in v&&Object.keys(v).length===1,w=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];m.allOf=w;break}case"tuple":{let m=p;m.type="array";let h=o.items.map((w,v)=>this.process(w,{...d,path:[...d.path,"prefixItems",v]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,o.rest){let w=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=w:m.additionalItems=w}o.rest&&(m.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=p;m.type="object",m.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=p,h=kF(o.entries);h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=p,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];m.type=g===null?"null":typeof g,m.const=g}else h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),h.every(g=>typeof g=="boolean")&&(m.type="string"),h.every(g=>g===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=p,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:w}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),w?w.length===1?(h.contentMediaType=w[0],Object.assign(m,h)):m.anyOf=w.map(v=>({...h,contentMediaType:v})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,d);p.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let m=p;m.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,p.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(p._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}p.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=p,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,p.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,d),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let c=this.metadataRegistry.get(e);return c&&Object.assign(a.schema,c),this.io==="input"&&zs(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=u=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){let h=r.external.registry.get(u[0])?.id,g=r.external.uri??(w=>w);if(h)return{ref:g(h)};let y=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(u[1]===o)return{ref:"#"};let p=`#/${d}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:p+m}},s=u=>{if(u[1].schema.$ref)return;let d=u[1],{ref:f,defId:p}=i(u);d.def={...d.schema},p&&(d.defId=p);let m=d.schema;for(let h in m)delete m[h];m.$ref=f};if(r.cycles==="throw")for(let u of this.seen.entries()){let d=u[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let d=u[1];if(e===u[0]){s(u);continue}if(r.external){let p=r.external.registry.get(u[0])?.id;if(e!==u[0]&&p){s(u);continue}}if(this.metadataRegistry.get(u[0])?.id){s(u);continue}if(d.cycle){s(u);continue}if(d.count>1&&r.reused==="ref"){s(u);continue}}let a=(u,d)=>{let f=this.seen.get(u),p=f.def??f.schema,m={...p};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(p.allOf=p.allOf??[],p.allOf.push(g)):(Object.assign(p,g),Object.assign(p,m))}f.isParent||this.override({zodSchema:u,jsonSchema:p,path:f.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let l={};if(this.target==="draft-2020-12"?l.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?l.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){let u=r.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");l.$id=r.external.uri(u)}Object.assign(l,o.def);let c=r.external?.defs??{};for(let u of this.seen.entries()){let d=u[1];d.def&&d.defId&&(c[d.defId]=d.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?l.$defs=c:l.definitions=c);try{return JSON.parse(JSON.stringify(l))}catch{throw new Error("Error converting schema to JSON.")}}}});var LDe={};var DDe=C(()=>{});var Cw={};zn(Cw,{$ZodAny:()=>ise,$ZodArray:()=>jF,$ZodAsyncError:()=>wg,$ZodBase64:()=>Yie,$ZodBase64URL:()=>Zie,$ZodBigInt:()=>L6,$ZodBigIntFormat:()=>tse,$ZodBoolean:()=>BF,$ZodCIDRv4:()=>Kie,$ZodCIDRv6:()=>qie,$ZodCUID:()=>Lie,$ZodCUID2:()=>Die,$ZodCatch:()=>Cse,$ZodCheck:()=>Ti,$ZodCheckBigIntFormat:()=>cie,$ZodCheckEndsWith:()=>bie,$ZodCheckGreaterThan:()=>k6,$ZodCheckIncludes:()=>vie,$ZodCheckLengthEquals:()=>hie,$ZodCheckLessThan:()=>A6,$ZodCheckLowerCase:()=>yie,$ZodCheckMaxLength:()=>pie,$ZodCheckMaxSize:()=>uie,$ZodCheckMimeType:()=>_ie,$ZodCheckMinLength:()=>mie,$ZodCheckMinSize:()=>die,$ZodCheckMultipleOf:()=>aie,$ZodCheckNumberFormat:()=>lie,$ZodCheckOverwrite:()=>Sie,$ZodCheckProperty:()=>Cie,$ZodCheckRegex:()=>gie,$ZodCheckSizeEquals:()=>fie,$ZodCheckStartsWith:()=>xie,$ZodCheckStringFormat:()=>Pk,$ZodCheckUpperCase:()=>wie,$ZodCustom:()=>Ese,$ZodCustomStringFormat:()=>Qie,$ZodDate:()=>ase,$ZodDefault:()=>wse,$ZodDiscriminatedUnion:()=>cse,$ZodE164:()=>Jie,$ZodEmail:()=>Mie,$ZodEmoji:()=>Oie,$ZodEnum:()=>mse,$ZodError:()=>DF,$ZodFile:()=>gse,$ZodFunction:()=>a3,$ZodGUID:()=>Aie,$ZodIPv4:()=>Wie,$ZodIPv6:()=>Hie,$ZodISODate:()=>zie,$ZodISODateTime:()=>Bie,$ZodISODuration:()=>Vie,$ZodISOTime:()=>jie,$ZodIntersection:()=>use,$ZodJWT:()=>Xie,$ZodKSUID:()=>Uie,$ZodLazy:()=>Pse,$ZodLiteral:()=>hse,$ZodMap:()=>fse,$ZodNaN:()=>_se,$ZodNanoID:()=>Rie,$ZodNever:()=>zF,$ZodNonOptional:()=>xse,$ZodNull:()=>ose,$ZodNullable:()=>yse,$ZodNumber:()=>R6,$ZodNumberFormat:()=>ese,$ZodObject:()=>lse,$ZodOptional:()=>$6,$ZodPipe:()=>WF,$ZodPrefault:()=>vse,$ZodPromise:()=>Ise,$ZodReadonly:()=>Sse,$ZodRealError:()=>Ik,$ZodRecord:()=>dse,$ZodRegistry:()=>Ek,$ZodSet:()=>pse,$ZodString:()=>CT,$ZodStringFormat:()=>_o,$ZodSuccess:()=>bse,$ZodSymbol:()=>nse,$ZodTemplateLiteral:()=>Tse,$ZodTransform:()=>VF,$ZodTuple:()=>ST,$ZodType:()=>jn,$ZodULID:()=>$ie,$ZodURL:()=>Nie,$ZodUUID:()=>kie,$ZodUndefined:()=>rse,$ZodUnion:()=>D6,$ZodUnknown:()=>_T,$ZodVoid:()=>sse,$ZodXID:()=>Fie,$brand:()=>hoe,$constructor:()=>ce,$input:()=>Nse,$output:()=>Mse,Doc:()=>UF,JSONSchema:()=>LDe,JSONSchemaGenerator:()=>l2,NEVER:()=>moe,TimePrecision:()=>Dse,_any:()=>rae,_array:()=>a2,_base64:()=>r3,_base64url:()=>o3,_bigint:()=>Zse,_boolean:()=>Gse,_catch:()=>GTt,_cidrv4:()=>t3,_cidrv6:()=>n3,_coercedBigint:()=>Jse,_coercedBoolean:()=>Yse,_coercedDate:()=>sae,_coercedNumber:()=>jse,_coercedString:()=>Lse,_cuid:()=>G6,_cuid2:()=>Y6,_custom:()=>hae,_date:()=>iae,_default:()=>HTt,_discriminatedUnion:()=>RTt,_e164:()=>i3,_email:()=>B6,_emoji:()=>K6,_endsWith:()=>t2,_enum:()=>UTt,_file:()=>mae,_float32:()=>Wse,_float64:()=>Hse,_gt:()=>xw,_gte:()=>Du,_guid:()=>qF,_includes:()=>QF,_int:()=>Vse,_int32:()=>Kse,_int64:()=>Xse,_intersection:()=>LTt,_ipv4:()=>Q6,_ipv6:()=>e3,_isoDate:()=>Fse,_isoDateTime:()=>$se,_isoDuration:()=>Bse,_isoTime:()=>Use,_jwt:()=>s3,_ksuid:()=>X6,_lazy:()=>XTt,_length:()=>Mk,_literal:()=>zTt,_lowercase:()=>JF,_lt:()=>vw,_lte:()=>Yf,_map:()=>$Tt,_max:()=>Yf,_maxLength:()=>kk,_maxSize:()=>Ak,_mime:()=>n2,_min:()=>Du,_minLength:()=>Ib,_minSize:()=>PT,_multipleOf:()=>IT,_nan:()=>aae,_nanoid:()=>q6,_nativeEnum:()=>BTt,_negative:()=>cae,_never:()=>GF,_nonnegative:()=>dae,_nonoptional:()=>KTt,_nonpositive:()=>uae,_normalize:()=>r2,_null:()=>nae,_nullable:()=>WTt,_number:()=>zse,_optional:()=>VTt,_overwrite:()=>bw,_parse:()=>C6,_parseAsync:()=>_6,_pipe:()=>YTt,_positive:()=>lae,_promise:()=>QTt,_property:()=>fae,_readonly:()=>ZTt,_record:()=>DTt,_refine:()=>gae,_regex:()=>ZF,_safeParse:()=>S6,_safeParseAsync:()=>T6,_set:()=>FTt,_size:()=>YF,_startsWith:()=>e2,_string:()=>Rse,_stringFormat:()=>wae,_stringbool:()=>yae,_success:()=>qTt,_symbol:()=>eae,_templateLiteral:()=>JTt,_toLowerCase:()=>i2,_toUpperCase:()=>s2,_transform:()=>jTt,_trim:()=>o2,_tuple:()=>pae,_uint32:()=>qse,_uint64:()=>Qse,_ulid:()=>Z6,_undefined:()=>tae,_union:()=>OTt,_unknown:()=>TT,_uppercase:()=>XF,_url:()=>H6,_uuid:()=>z6,_uuidv4:()=>j6,_uuidv6:()=>V6,_uuidv7:()=>W6,_void:()=>oae,_xid:()=>J6,clone:()=>xs,config:()=>vs,flattenError:()=>$F,formatError:()=>FF,function:()=>xae,globalConfig:()=>EF,globalRegistry:()=>Oa,isValidBase64:()=>Gie,isValidBase64URL:()=>s1e,isValidJWT:()=>a1e,locales:()=>KF,parse:()=>wT,parseAsync:()=>vT,prettifyError:()=>Eoe,regexes:()=>bT,registry:()=>U6,safeParse:()=>koe,safeParseAsync:()=>Moe,toDotPath:()=>jLe,toJSONSchema:()=>Pb,treeifyError:()=>Poe,util:()=>Qe,version:()=>Iie});var Ql=C(()=>{_k();I6();Aoe();HF();M6();Pie();An();E6();kse();Ose();Tie();ODe();vae();RDe();DDe()});function hl(t){if(typeof t!="object"||t===null)return!1;let e=t;if(!("_zod"in e))return!1;let n=e._zod;return typeof n=="object"&&n!==null&&"def"in n}function Zf(t){if(typeof t!="object"||t===null)return!1;let e=t;if(!("_def"in e)||"_zod"in e)return!1;let n=e._def;return typeof n=="object"&&n!=null&&"typeName"in n}function jr(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(hl(t)||Zf(t))}async function kT(t,e){if(hl(t))try{return{success:!0,data:await vT(t,e)}}catch(n){return{success:!1,error:n}}if(Zf(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function MT(t,e){if(hl(t))return await vT(t,e);if(Zf(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function NT(t){if(hl(t))return Oa.get(t)?.description;if(Zf(t)||"description"in t&&typeof t.description=="string")return t.description}function u2(t){return jr(t)?Zf(t)?t._def.typeName==="ZodString":hl(t)?t._zod.def.type==="string":!1:!1}function $De(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function AT(t){return hl(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function bae(t){return hl(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function FDe(t){return hl(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="optional":!1}function UDe(t){return hl(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="nullable":!1}function c2(t,e=!1){if($De(t))return t.strict();if(AT(t)){let n=t._zod.def.shape;if(e)for(let[i,s]of Object.entries(t._zod.def.shape)){if(AT(s))n[i]=c2(s,e);else if(bae(s)){let l=s._zod.def.element;AT(l)&&(l=c2(l,e)),n[i]=xs(s,{...s._zod.def,element:l})}else n[i]=s;let a=Oa.get(s);a&&Oa.add(n[i],a)}let r=xs(t,{...t._zod.def,shape:n,catchall:GF(zF)}),o=Oa.get(t);return o&&Oa.add(r,o),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function eIt(t){return Zf(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function tIt(t){return hl(t)&&t._zod.def.type==="pipe"}function ET(t,e,n){let r=n.get(t);if(r!==void 0)return r;if(Zf(t))return eIt(t)?ET(t._def.schema,e,n):t;if(hl(t)){let o=t;if(tIt(t)&&(o=ET(t._zod.def.in,e,n)),e){if(AT(o)){let s={};for(let[a,l]of Object.entries(o._zod.def.shape))s[a]=ET(l,e,n);o=xs(o,{...o._zod.def,shape:s})}else if(bae(o)){let s=ET(o._zod.def.element,e,n);o=xs(o,{...o._zod.def,element:s})}else if(FDe(o)){let s=ET(o._zod.def.innerType,e,n);o=xs(o,{...o._zod.def,innerType:s})}else if(UDe(o)){let s=ET(o._zod.def.innerType,e,n);o=xs(o,{...o._zod.def,innerType:s})}}let i=Oa.get(t);return i&&Oa.add(o,i),n.set(t,o),o}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Cae(t,e=!1){return ET(t,e,new WeakMap)}function _ae(t){return t instanceof Error&&(t.constructor.name==="ZodError"||t.constructor.name==="$ZodError")}var vg=C(()=>{Ql()});var Bd=C(()=>{$n();vg()});var zDe,BDe,jDe,l3=C(()=>{zDe=Symbol("Let zodToJsonSchema decide on which parser to use"),BDe={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},jDe=t=>typeof t=="string"?{...BDe,name:t}:{...BDe,...t}});var VDe,Sae=C(()=>{l3();VDe=t=>{let e=jDe(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});var c3,u3=C(()=>{c3=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function ci(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?c3(e,t.currentPath):e.join("/")}}var Jf=C(()=>{u3()});function Tae(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function Er(t,e,n,r,o){t[e]=n,Tae(t,e,r,o)}var Eb=C(()=>{});var yr,Iae,Ct,xg,d2=C(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},t.find=(o,i)=>{for(let s of o)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(yr||(yr={}));(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Iae||(Iae={}));Ct=yr.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xg=t=>{switch(typeof t){case"undefined":return Ct.undefined;case"string":return Ct.string;case"number":return Number.isNaN(t)?Ct.nan:Ct.number;case"boolean":return Ct.boolean;case"function":return Ct.function;case"bigint":return Ct.bigint;case"symbol":return Ct.symbol;case"object":return Array.isArray(t)?Ct.array:t===null?Ct.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?Ct.promise:typeof Map<"u"&&t instanceof Map?Ct.map:typeof Set<"u"&&t instanceof Set?Ct.set:typeof Date<"u"&&t instanceof Date?Ct.date:Ct.object;default:return Ct.unknown}}});var $e,nIt,$u,d3=C(()=>{d2();$e=yr.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),nIt=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),$u=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,yr.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];n[i]=n[i]||[],n[i].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};$u.create=t=>new $u(t)});var rIt,_w,Pae=C(()=>{d3();d2();rIt=(t,e)=>{let n;switch(t.code){case $e.invalid_type:t.received===Ct.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case $e.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,yr.jsonStringifyReplacer)}`;break;case $e.unrecognized_keys:n=`Unrecognized key(s) in object: ${yr.joinValues(t.keys,", ")}`;break;case $e.invalid_union:n="Invalid input";break;case $e.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${yr.joinValues(t.options)}`;break;case $e.invalid_enum_value:n=`Invalid enum value. Expected ${yr.joinValues(t.options)}, received '${t.received}'`;break;case $e.invalid_arguments:n="Invalid function arguments";break;case $e.invalid_return_type:n="Invalid function return type";break;case $e.invalid_date:n="Invalid date";break;case $e.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:yr.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case $e.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case $e.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case $e.custom:n="Invalid input";break;case $e.invalid_intersection_types:n="Intersection results could not be merged";break;case $e.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case $e.not_finite:n="Number must be finite";break;default:n=e.defaultError,yr.assertNever(t)}return{message:n}},_w=rIt});function oIt(t){WDe=t}function Nk(){return WDe}var WDe,f3=C(()=>{Pae();WDe=_w});function ut(t,e){let n=Nk(),r=f2({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===_w?void 0:_w].filter(o=>!!o)});t.common.issues.push(r)}var f2,iIt,gl,wn,OT,ec,p3,m3,Ab,Ok,Eae=C(()=>{f3();Pae();f2=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,i=[...n,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...o,path:i,message:a}},iIt=[];gl=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return wn;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let i=await o.key,s=await o.value;r.push({key:i,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return wn;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:e.value,value:r}}},wn=Object.freeze({status:"aborted"}),OT=t=>({status:"dirty",value:t}),ec=t=>({status:"valid",value:t}),p3=t=>t.status==="aborted",m3=t=>t.status==="dirty",Ab=t=>t.status==="valid",Ok=t=>typeof Promise<"u"&&t instanceof Promise});var HDe=C(()=>{});var Vt,KDe=C(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(Vt||(Vt={}))});function Jn(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(s,a)=>{let{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}function ZDe(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function CIt(t){return new RegExp(`^${ZDe(t)}$`)}function JDe(t){let e=`${YDe}T${ZDe(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function _It(t,e){return!!((e==="v4"||!e)&&hIt.test(t)||(e==="v6"||!e)&&yIt.test(t))}function SIt(t,e){if(!dIt.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function TIt(t,e){return!!((e==="v4"||!e)&&gIt.test(t)||(e==="v6"||!e)&&wIt.test(t))}function IIt(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}function Rk(t){if(t instanceof Fu){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Xf.create(Rk(r))}return new Fu({...t._def,shape:()=>e})}else return t instanceof Iw?new Iw({...t._def,type:Rk(t.element)}):t instanceof Xf?Xf.create(Rk(t.unwrap())):t instanceof Cg?Cg.create(Rk(t.unwrap())):t instanceof bg?bg.create(t.items.map(e=>Rk(e))):t}function kae(t,e){let n=xg(t),r=xg(e);if(t===e)return{valid:!0,data:t};if(n===Ct.object&&r===Ct.object){let o=yr.objectKeys(e),i=yr.objectKeys(t).filter(a=>o.indexOf(a)!==-1),s={...t,...e};for(let a of i){let l=kae(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===Ct.array&&r===Ct.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],l=kae(s,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===Ct.date&&r===Ct.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function XDe(t,e){return new WT({values:t,typeName:he.ZodEnum,...Jn(e)})}function GDe(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function QDe(t,e={},n){return t?Mb.create().superRefine((r,o)=>{let i=t(r);if(i instanceof Promise)return i.then(s=>{if(!s){let a=GDe(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!i){let s=GDe(e,r),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):Mb.create()}var Qf,qDe,ar,sIt,aIt,lIt,cIt,uIt,dIt,fIt,pIt,mIt,Aae,hIt,gIt,yIt,wIt,vIt,xIt,YDe,bIt,kb,RT,LT,DT,$T,Lk,FT,UT,Mb,Tw,Nm,Dk,Iw,Fu,BT,Sw,h3,zT,bg,g3,$k,Fk,y3,jT,VT,WT,HT,Nb,ep,Xf,Cg,KT,qT,Uk,PIt,p2,m2,GT,EIt,he,AIt,e$e,t$e,kIt,MIt,n$e,NIt,OIt,RIt,LIt,DIt,$It,FIt,UIt,BIt,zIt,jIt,VIt,WIt,HIt,KIt,qIt,GIt,YIt,ZIt,JIt,XIt,QIt,e0t,t0t,n0t,r0t,o0t,i0t,s0t,a0t,l0t,c0t,u0t,d0t,r$e=C(()=>{d3();f3();KDe();Eae();d2();Qf=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},qDe=(t,e)=>{if(Ab(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new $u(t.common.issues);return this._error=n,this._error}}};ar=class{get description(){return this._def.description}_getType(e){return xg(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:xg(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new gl,ctx:{common:e.parent.common,data:e.data,parsedType:xg(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Ok(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xg(e)},o=this._parseSync({data:e,path:r.path,parent:r});return qDe(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xg(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Ab(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Ab(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xg(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(Ok(o)?o:Promise.resolve(o));return qDe(r,i)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:$e.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new ep({schema:this,typeName:he.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Xf.create(this,this._def)}nullable(){return Cg.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Iw.create(this)}promise(){return Nb.create(this,this._def)}or(e){return BT.create([this,e],this._def)}and(e){return zT.create(this,e,this._def)}transform(e){return new ep({...Jn(this._def),schema:this,typeName:he.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new KT({...Jn(this._def),innerType:this,defaultValue:n,typeName:he.ZodDefault})}brand(){return new p2({typeName:he.ZodBranded,type:this,...Jn(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new qT({...Jn(this._def),innerType:this,catchValue:n,typeName:he.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return m2.create(this,e)}readonly(){return GT.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},sIt=/^c[^\s-]{8,}$/i,aIt=/^[0-9a-z]+$/,lIt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cIt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,uIt=/^[a-z0-9_-]{21}$/i,dIt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fIt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,pIt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,mIt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",hIt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,gIt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,yIt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,wIt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,vIt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xIt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,YDe="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",bIt=new RegExp(`^${YDe}$`);kb=class t extends ar{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==Ct.string){let i=this._getOrReturnCtx(e);return ut(i,{code:$e.invalid_type,expected:Ct.string,received:i.parsedType}),wn}let r=new gl,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(e,o),s?ut(o,{code:$e.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&ut(o,{code:$e.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")pIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"email",code:$e.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Aae||(Aae=new RegExp(mIt,"u")),Aae.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"emoji",code:$e.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")cIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"uuid",code:$e.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")uIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"nanoid",code:$e.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")sIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"cuid",code:$e.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")aIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"cuid2",code:$e.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")lIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"ulid",code:$e.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),ut(o,{validation:"url",code:$e.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"regex",code:$e.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?JDe(i).test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?bIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?CIt(i).test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?fIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"duration",code:$e.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?_It(e.data,i.version)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"ip",code:$e.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?SIt(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"jwt",code:$e.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?TIt(e.data,i.version)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"cidr",code:$e.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?vIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"base64",code:$e.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?xIt.test(e.data)||(o=this._getOrReturnCtx(e,o),ut(o,{validation:"base64url",code:$e.invalid_string,message:i.message}),r.dirty()):yr.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:$e.invalid_string,...Vt.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Vt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Vt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Vt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Vt.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Vt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Vt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Vt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Vt.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Vt.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Vt.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Vt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Vt.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Vt.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...Vt.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...Vt.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...Vt.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Vt.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...Vt.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Vt.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Vt.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Vt.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Vt.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Vt.errToObj(n)})}nonempty(e){return this.min(1,Vt.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};kb.create=t=>new kb({checks:[],typeName:he.ZodString,coerce:t?.coerce??!1,...Jn(t)});RT=class t extends ar{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==Ct.number){let i=this._getOrReturnCtx(e);return ut(i,{code:$e.invalid_type,expected:Ct.number,received:i.parsedType}),wn}let r,o=new gl;for(let i of this._def.checks)i.kind==="int"?yr.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),ut(r,{code:$e.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),ut(r,{code:$e.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ut(r,{code:$e.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?IIt(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),ut(r,{code:$e.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),ut(r,{code:$e.not_finite,message:i.message}),o.dirty()):yr.assertNever(i);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Vt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Vt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Vt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Vt.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Vt.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Vt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Vt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Vt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Vt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Vt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Vt.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Vt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Vt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Vt.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&yr.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};RT.create=t=>new RT({checks:[],typeName:he.ZodNumber,coerce:t?.coerce||!1,...Jn(t)});LT=class t extends ar{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==Ct.bigint)return this._getInvalidInput(e);let r,o=new gl;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),ut(r,{code:$e.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ut(r,{code:$e.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),ut(r,{code:$e.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):yr.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return ut(n,{code:$e.invalid_type,expected:Ct.bigint,received:n.parsedType}),wn}gte(e,n){return this.setLimit("min",e,!0,Vt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Vt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Vt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Vt.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Vt.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Vt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Vt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Vt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Vt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Vt.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};LT.create=t=>new LT({checks:[],typeName:he.ZodBigInt,coerce:t?.coerce??!1,...Jn(t)});DT=class extends ar{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==Ct.boolean){let r=this._getOrReturnCtx(e);return ut(r,{code:$e.invalid_type,expected:Ct.boolean,received:r.parsedType}),wn}return ec(e.data)}};DT.create=t=>new DT({typeName:he.ZodBoolean,coerce:t?.coerce||!1,...Jn(t)});$T=class t extends ar{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==Ct.date){let i=this._getOrReturnCtx(e);return ut(i,{code:$e.invalid_type,expected:Ct.date,received:i.parsedType}),wn}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return ut(i,{code:$e.invalid_date}),wn}let r=new gl,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),ut(o,{code:$e.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):yr.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Vt.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Vt.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};$T.create=t=>new $T({checks:[],coerce:t?.coerce||!1,typeName:he.ZodDate,...Jn(t)});Lk=class extends ar{_parse(e){if(this._getType(e)!==Ct.symbol){let r=this._getOrReturnCtx(e);return ut(r,{code:$e.invalid_type,expected:Ct.symbol,received:r.parsedType}),wn}return ec(e.data)}};Lk.create=t=>new Lk({typeName:he.ZodSymbol,...Jn(t)});FT=class extends ar{_parse(e){if(this._getType(e)!==Ct.undefined){let r=this._getOrReturnCtx(e);return ut(r,{code:$e.invalid_type,expected:Ct.undefined,received:r.parsedType}),wn}return ec(e.data)}};FT.create=t=>new FT({typeName:he.ZodUndefined,...Jn(t)});UT=class extends ar{_parse(e){if(this._getType(e)!==Ct.null){let r=this._getOrReturnCtx(e);return ut(r,{code:$e.invalid_type,expected:Ct.null,received:r.parsedType}),wn}return ec(e.data)}};UT.create=t=>new UT({typeName:he.ZodNull,...Jn(t)});Mb=class extends ar{constructor(){super(...arguments),this._any=!0}_parse(e){return ec(e.data)}};Mb.create=t=>new Mb({typeName:he.ZodAny,...Jn(t)});Tw=class extends ar{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ec(e.data)}};Tw.create=t=>new Tw({typeName:he.ZodUnknown,...Jn(t)});Nm=class extends ar{_parse(e){let n=this._getOrReturnCtx(e);return ut(n,{code:$e.invalid_type,expected:Ct.never,received:n.parsedType}),wn}};Nm.create=t=>new Nm({typeName:he.ZodNever,...Jn(t)});Dk=class extends ar{_parse(e){if(this._getType(e)!==Ct.undefined){let r=this._getOrReturnCtx(e);return ut(r,{code:$e.invalid_type,expected:Ct.void,received:r.parsedType}),wn}return ec(e.data)}};Dk.create=t=>new Dk({typeName:he.ZodVoid,...Jn(t)});Iw=class t extends ar{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==Ct.array)return ut(n,{code:$e.invalid_type,expected:Ct.array,received:n.parsedType}),wn;if(o.exactLength!==null){let s=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(s||a)&&(ut(n,{code:s?$e.too_big:$e.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(ut(n,{code:$e.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(ut(n,{code:$e.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new Qf(n,s,n.path,a)))).then(s=>gl.mergeArray(r,s));let i=[...n.data].map((s,a)=>o.type._parseSync(new Qf(n,s,n.path,a)));return gl.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:Vt.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:Vt.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:Vt.toString(n)}})}nonempty(e){return this.min(1,e)}};Iw.create=(t,e)=>new Iw({type:t,minLength:null,maxLength:null,exactLength:null,typeName:he.ZodArray,...Jn(e)});Fu=class t extends ar{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=yr.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==Ct.object){let c=this._getOrReturnCtx(e);return ut(c,{code:$e.invalid_type,expected:Ct.object,received:c.parsedType}),wn}let{status:r,ctx:o}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Nm&&this._def.unknownKeys==="strip"))for(let c in o.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let u=i[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Qf(o,d,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Nm){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(ut(o,{code:$e.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let d=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Qf(o,d,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,f=await u.value;c.push({key:d,value:f,alwaysSet:u.alwaysSet})}return c}).then(c=>gl.mergeObjectSync(r,c)):gl.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return Vt.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:Vt.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:he.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of yr.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of yr.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Rk(this)}partial(e){let n={};for(let r of yr.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of yr.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Xf;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return XDe(yr.objectKeys(this.shape))}};Fu.create=(t,e)=>new Fu({shape:()=>t,unknownKeys:"strip",catchall:Nm.create(),typeName:he.ZodObject,...Jn(e)});Fu.strictCreate=(t,e)=>new Fu({shape:()=>t,unknownKeys:"strict",catchall:Nm.create(),typeName:he.ZodObject,...Jn(e)});Fu.lazycreate=(t,e)=>new Fu({shape:t,unknownKeys:"strip",catchall:Nm.create(),typeName:he.ZodObject,...Jn(e)});BT=class extends ar{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new $u(a.ctx.common.issues));return ut(n,{code:$e.invalid_union,unionErrors:s}),wn}if(n.common.async)return Promise.all(r.map(async i=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i,s=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=l._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(l=>new $u(l));return ut(n,{code:$e.invalid_union,unionErrors:a}),wn}}get options(){return this._def.options}};BT.create=(t,e)=>new BT({options:t,typeName:he.ZodUnion,...Jn(e)});Sw=t=>t instanceof jT?Sw(t.schema):t instanceof ep?Sw(t.innerType()):t instanceof VT?[t.value]:t instanceof WT?t.options:t instanceof HT?yr.objectValues(t.enum):t instanceof KT?Sw(t._def.innerType):t instanceof FT?[void 0]:t instanceof UT?[null]:t instanceof Xf?[void 0,...Sw(t.unwrap())]:t instanceof Cg?[null,...Sw(t.unwrap())]:t instanceof p2||t instanceof GT?Sw(t.unwrap()):t instanceof qT?Sw(t._def.innerType):[],h3=class t extends ar{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ct.object)return ut(n,{code:$e.invalid_type,expected:Ct.object,received:n.parsedType}),wn;let r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(ut(n,{code:$e.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),wn)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let i of n){let s=Sw(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,i)}}return new t({typeName:he.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...Jn(r)})}};zT=class extends ar{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(i,s)=>{if(p3(i)||p3(s))return wn;let a=kae(i.value,s.value);return a.valid?((m3(i)||m3(s))&&n.dirty(),{status:n.value,value:a.data}):(ut(r,{code:$e.invalid_intersection_types}),wn)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};zT.create=(t,e,n)=>new zT({left:t,right:e,typeName:he.ZodIntersection,...Jn(n)});bg=class t extends ar{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ct.array)return ut(r,{code:$e.invalid_type,expected:Ct.array,received:r.parsedType}),wn;if(r.data.length<this._def.items.length)return ut(r,{code:$e.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),wn;!this._def.rest&&r.data.length>this._def.items.length&&(ut(r,{code:$e.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Qf(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>gl.mergeArray(n,s)):gl.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};bg.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new bg({items:t,typeName:he.ZodTuple,rest:null,...Jn(e)})};g3=class t extends ar{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ct.object)return ut(r,{code:$e.invalid_type,expected:Ct.object,received:r.parsedType}),wn;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in r.data)o.push({key:i._parse(new Qf(r,a,r.path,a)),value:s._parse(new Qf(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?gl.mergeObjectAsync(n,o):gl.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof ar?new t({keyType:e,valueType:n,typeName:he.ZodRecord,...Jn(r)}):new t({keyType:kb.create(),valueType:e,typeName:he.ZodRecord,...Jn(n)})}},$k=class extends ar{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ct.map)return ut(r,{code:$e.invalid_type,expected:Ct.map,received:r.parsedType}),wn;let o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Qf(r,a,r.path,[c,"key"])),value:i._parse(new Qf(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return wn;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return wn;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};$k.create=(t,e,n)=>new $k({valueType:e,keyType:t,typeName:he.ZodMap,...Jn(n)});Fk=class t extends ar{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==Ct.set)return ut(r,{code:$e.invalid_type,expected:Ct.set,received:r.parsedType}),wn;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(ut(r,{code:$e.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(ut(r,{code:$e.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function s(l){let c=new Set;for(let u of l){if(u.status==="aborted")return wn;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>i._parse(new Qf(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:Vt.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:Vt.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Fk.create=(t,e)=>new Fk({valueType:t,minSize:null,maxSize:null,typeName:he.ZodSet,...Jn(e)});y3=class t extends ar{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ct.function)return ut(n,{code:$e.invalid_type,expected:Ct.function,received:n.parsedType}),wn;function r(a,l){return f2({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Nk(),_w].filter(c=>!!c),issueData:{code:$e.invalid_arguments,argumentsError:l}})}function o(a,l){return f2({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Nk(),_w].filter(c=>!!c),issueData:{code:$e.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Nb){let a=this;return ec(async function(...l){let c=new $u([]),u=await a._def.args.parseAsync(l,i).catch(p=>{throw c.addIssue(r(l,p)),c}),d=await Reflect.apply(s,this,u);return await a._def.returns._def.type.parseAsync(d,i).catch(p=>{throw c.addIssue(o(d,p)),c})})}else{let a=this;return ec(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new $u([r(l,c.error)]);let u=Reflect.apply(s,this,c.data),d=a._def.returns.safeParse(u,i);if(!d.success)throw new $u([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:bg.create(e).rest(Tw.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||bg.create([]).rest(Tw.create()),returns:n||Tw.create(),typeName:he.ZodFunction,...Jn(r)})}},jT=class extends ar{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};jT.create=(t,e)=>new jT({getter:t,typeName:he.ZodLazy,...Jn(e)});VT=class extends ar{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return ut(n,{received:n.data,code:$e.invalid_literal,expected:this._def.value}),wn}return{status:"valid",value:e.data}}get value(){return this._def.value}};VT.create=(t,e)=>new VT({value:t,typeName:he.ZodLiteral,...Jn(e)});WT=class t extends ar{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return ut(n,{expected:yr.joinValues(r),received:n.parsedType,code:$e.invalid_type}),wn}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return ut(n,{received:n.data,code:$e.invalid_enum_value,options:r}),wn}return ec(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};WT.create=XDe;HT=class extends ar{_parse(e){let n=yr.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==Ct.string&&r.parsedType!==Ct.number){let o=yr.objectValues(n);return ut(r,{expected:yr.joinValues(o),received:r.parsedType,code:$e.invalid_type}),wn}if(this._cache||(this._cache=new Set(yr.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=yr.objectValues(n);return ut(r,{received:r.data,code:$e.invalid_enum_value,options:o}),wn}return ec(e.data)}get enum(){return this._def.values}};HT.create=(t,e)=>new HT({values:t,typeName:he.ZodNativeEnum,...Jn(e)});Nb=class extends ar{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==Ct.promise&&n.common.async===!1)return ut(n,{code:$e.invalid_type,expected:Ct.promise,received:n.parsedType}),wn;let r=n.parsedType===Ct.promise?n.data:Promise.resolve(n.data);return ec(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Nb.create=(t,e)=>new Nb({type:t,typeName:he.ZodPromise,...Jn(e)});ep=class extends ar{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===he.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s=>{ut(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return wn;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?wn:l.status==="dirty"?OT(l.value):n.value==="dirty"?OT(l.value):l});{if(n.value==="aborted")return wn;let a=this._def.schema._parseSync({data:s,path:r.path,parent:r});return a.status==="aborted"?wn:a.status==="dirty"?OT(a.value):n.value==="dirty"?OT(a.value):a}}if(o.type==="refinement"){let s=a=>{let l=o.refinement(a,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?wn:(a.status==="dirty"&&n.dirty(),s(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?wn:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Ab(s))return wn;let a=o.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Ab(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:n.value,value:a})):wn);yr.assertNever(o)}};ep.create=(t,e,n)=>new ep({schema:t,typeName:he.ZodEffects,effect:e,...Jn(n)});ep.createWithPreprocess=(t,e,n)=>new ep({schema:e,effect:{type:"preprocess",transform:t},typeName:he.ZodEffects,...Jn(n)});Xf=class extends ar{_parse(e){return this._getType(e)===Ct.undefined?ec(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Xf.create=(t,e)=>new Xf({innerType:t,typeName:he.ZodOptional,...Jn(e)});Cg=class extends ar{_parse(e){return this._getType(e)===Ct.null?ec(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Cg.create=(t,e)=>new Cg({innerType:t,typeName:he.ZodNullable,...Jn(e)});KT=class extends ar{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===Ct.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};KT.create=(t,e)=>new KT({innerType:t,typeName:he.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Jn(e)});qT=class extends ar{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ok(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new $u(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new $u(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};qT.create=(t,e)=>new qT({innerType:t,typeName:he.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Jn(e)});Uk=class extends ar{_parse(e){if(this._getType(e)!==Ct.nan){let r=this._getOrReturnCtx(e);return ut(r,{code:$e.invalid_type,expected:Ct.nan,received:r.parsedType}),wn}return{status:"valid",value:e.data}}};Uk.create=t=>new Uk({typeName:he.ZodNaN,...Jn(t)});PIt=Symbol("zod_brand"),p2=class extends ar{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},m2=class t extends ar{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?wn:i.status==="dirty"?(n.dirty(),OT(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?wn:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:he.ZodPipeline})}},GT=class extends ar{_parse(e){let n=this._def.innerType._parse(e),r=o=>(Ab(o)&&(o.value=Object.freeze(o.value)),o);return Ok(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};GT.create=(t,e)=>new GT({innerType:t,typeName:he.ZodReadonly,...Jn(e)});EIt={object:Fu.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(he||(he={}));AIt=(t,e={message:`Input not instance of ${t.name}`})=>QDe(n=>n instanceof t,e),e$e=kb.create,t$e=RT.create,kIt=Uk.create,MIt=LT.create,n$e=DT.create,NIt=$T.create,OIt=Lk.create,RIt=FT.create,LIt=UT.create,DIt=Mb.create,$It=Tw.create,FIt=Nm.create,UIt=Dk.create,BIt=Iw.create,zIt=Fu.create,jIt=Fu.strictCreate,VIt=BT.create,WIt=h3.create,HIt=zT.create,KIt=bg.create,qIt=g3.create,GIt=$k.create,YIt=Fk.create,ZIt=y3.create,JIt=jT.create,XIt=VT.create,QIt=WT.create,e0t=HT.create,t0t=Nb.create,n0t=ep.create,r0t=Xf.create,o0t=Cg.create,i0t=ep.createWithPreprocess,s0t=m2.create,a0t=()=>e$e().optional(),l0t=()=>t$e().optional(),c0t=()=>n$e().optional(),u0t={string:t=>kb.create({...t,coerce:!0}),number:t=>RT.create({...t,coerce:!0}),boolean:t=>DT.create({...t,coerce:!0}),bigint:t=>LT.create({...t,coerce:!0}),date:t=>$T.create({...t,coerce:!0})},d0t=wn});var we={};zn(we,{BRAND:()=>PIt,DIRTY:()=>OT,EMPTY_PATH:()=>iIt,INVALID:()=>wn,NEVER:()=>d0t,OK:()=>ec,ParseStatus:()=>gl,Schema:()=>ar,ZodAny:()=>Mb,ZodArray:()=>Iw,ZodBigInt:()=>LT,ZodBoolean:()=>DT,ZodBranded:()=>p2,ZodCatch:()=>qT,ZodDate:()=>$T,ZodDefault:()=>KT,ZodDiscriminatedUnion:()=>h3,ZodEffects:()=>ep,ZodEnum:()=>WT,ZodError:()=>$u,ZodFirstPartyTypeKind:()=>he,ZodFunction:()=>y3,ZodIntersection:()=>zT,ZodIssueCode:()=>$e,ZodLazy:()=>jT,ZodLiteral:()=>VT,ZodMap:()=>$k,ZodNaN:()=>Uk,ZodNativeEnum:()=>HT,ZodNever:()=>Nm,ZodNull:()=>UT,ZodNullable:()=>Cg,ZodNumber:()=>RT,ZodObject:()=>Fu,ZodOptional:()=>Xf,ZodParsedType:()=>Ct,ZodPipeline:()=>m2,ZodPromise:()=>Nb,ZodReadonly:()=>GT,ZodRecord:()=>g3,ZodSchema:()=>ar,ZodSet:()=>Fk,ZodString:()=>kb,ZodSymbol:()=>Lk,ZodTransformer:()=>ep,ZodTuple:()=>bg,ZodType:()=>ar,ZodUndefined:()=>FT,ZodUnion:()=>BT,ZodUnknown:()=>Tw,ZodVoid:()=>Dk,addIssueToContext:()=>ut,any:()=>DIt,array:()=>BIt,bigint:()=>MIt,boolean:()=>n$e,coerce:()=>u0t,custom:()=>QDe,date:()=>NIt,datetimeRegex:()=>JDe,defaultErrorMap:()=>_w,discriminatedUnion:()=>WIt,effect:()=>n0t,enum:()=>QIt,function:()=>ZIt,getErrorMap:()=>Nk,getParsedType:()=>xg,instanceof:()=>AIt,intersection:()=>HIt,isAborted:()=>p3,isAsync:()=>Ok,isDirty:()=>m3,isValid:()=>Ab,late:()=>EIt,lazy:()=>JIt,literal:()=>XIt,makeIssue:()=>f2,map:()=>GIt,nan:()=>kIt,nativeEnum:()=>e0t,never:()=>FIt,null:()=>LIt,nullable:()=>o0t,number:()=>t$e,object:()=>zIt,objectUtil:()=>Iae,oboolean:()=>c0t,onumber:()=>l0t,optional:()=>r0t,ostring:()=>a0t,pipeline:()=>s0t,preprocess:()=>i0t,promise:()=>t0t,quotelessJson:()=>nIt,record:()=>qIt,set:()=>YIt,setErrorMap:()=>oIt,strictObject:()=>jIt,string:()=>e$e,symbol:()=>OIt,transformer:()=>n0t,tuple:()=>KIt,undefined:()=>RIt,union:()=>VIt,unknown:()=>$It,util:()=>yr,void:()=>UIt});var h2=C(()=>{f3();Eae();HDe();d2();r$e();d3()});var _g=C(()=>{h2();h2()});function o$e(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==he.ZodAny&&(n.items=Tn(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Er(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Er(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Er(n,"minItems",t.exactLength.value,t.exactLength.message,e),Er(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var Mae=C(()=>{Eb();bs();_g()});function i$e(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?Er(n,"minimum",r.value,r.message,e):Er(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Er(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Er(n,"maximum",r.value,r.message,e):Er(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Er(n,"maximum",r.value,r.message,e));break;case"multipleOf":Er(n,"multipleOf",r.value,r.message,e);break}return n}var Nae=C(()=>{Eb()});function s$e(){return{type:"boolean"}}var Oae=C(()=>{});function w3(t,e){return Tn(t.type._def,e)}var v3=C(()=>{bs()});var a$e,Rae=C(()=>{bs();a$e=(t,e)=>Tn(t.innerType._def,e)});function Lae(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(o=>Lae(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return f0t(t,e)}}var f0t,Dae=C(()=>{Eb();f0t=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":Er(n,"minimum",r.value,r.message,e);break;case"max":Er(n,"maximum",r.value,r.message,e);break}return n}});function l$e(t,e){return{...Tn(t.innerType._def,e),default:t.defaultValue()}}var $ae=C(()=>{bs()});function c$e(t,e){return e.effectStrategy==="input"?Tn(t.schema._def,e):ci(e)}var Fae=C(()=>{Jf();bs()});function u$e(t){return{type:"string",enum:Array.from(t.values)}}var Uae=C(()=>{});function d$e(t,e){let n=[Tn(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Tn(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(i=>{if(p0t(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(r=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...l}=i;s=l}else r=void 0;o.push(s)}}),o.length?{allOf:o,...r}:void 0}var p0t,Bae=C(()=>{bs();p0t=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function f$e(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var zae=C(()=>{});function x3(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":Er(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":Er(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Rm(n,"email",r.message,e);break;case"format:idn-email":Rm(n,"idn-email",r.message,e);break;case"pattern:zod":Uc(n,Om.email,r.message,e);break}break;case"url":Rm(n,"uri",r.message,e);break;case"uuid":Rm(n,"uuid",r.message,e);break;case"regex":Uc(n,r.regex,r.message,e);break;case"cuid":Uc(n,Om.cuid,r.message,e);break;case"cuid2":Uc(n,Om.cuid2,r.message,e);break;case"startsWith":Uc(n,RegExp(`^${Vae(r.value,e)}`),r.message,e);break;case"endsWith":Uc(n,RegExp(`${Vae(r.value,e)}$`),r.message,e);break;case"datetime":Rm(n,"date-time",r.message,e);break;case"date":Rm(n,"date",r.message,e);break;case"time":Rm(n,"time",r.message,e);break;case"duration":Rm(n,"duration",r.message,e);break;case"length":Er(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),Er(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":Uc(n,RegExp(Vae(r.value,e)),r.message,e);break;case"ip":r.version!=="v6"&&Rm(n,"ipv4",r.message,e),r.version!=="v4"&&Rm(n,"ipv6",r.message,e);break;case"base64url":Uc(n,Om.base64url,r.message,e);break;case"jwt":Uc(n,Om.jwt,r.message,e);break;case"cidr":r.version!=="v6"&&Uc(n,Om.ipv4Cidr,r.message,e),r.version!=="v4"&&Uc(n,Om.ipv6Cidr,r.message,e);break;case"emoji":Uc(n,Om.emoji(),r.message,e);break;case"ulid":Uc(n,Om.ulid,r.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":Rm(n,"binary",r.message,e);break;case"contentEncoding:base64":Er(n,"contentEncoding","base64",r.message,e);break;case"pattern:zod":Uc(n,Om.base64,r.message,e);break}break;case"nanoid":Uc(n,Om.nanoid,r.message,e);break;case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Vae(t,e){return e.patternStrategy==="escape"?h0t(t):t}function h0t(t){let e="";for(let n=0;n<t.length;n++)m0t.has(t[n])||(e+="\\"),e+=t[n];return e}function Rm(t,e,n,r){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Er(t,"format",e,n,r)}function Uc(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:p$e(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Er(t,"pattern",p$e(e,r),n,r)}function p$e(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",i=!1,s=!1,a=!1;for(let l=0;l<r.length;l++){if(i){o+=r[l],i=!1;continue}if(n.i){if(s){if(r[l].match(/[a-z]/)){a?(o+=r[l],o+=`${r[l-2]}-${r[l]}`.toUpperCase(),a=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(o+=r[l],a=!0):o+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){o+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(n.m){if(r[l]==="^"){o+=`(^|(?<=[\r
]))`;continue}else if(r[l]==="$"){o+=`($|(?=[\r
]))`;continue}}if(n.s&&r[l]==="."){o+=s?`${r[l]}\r
`:`[${r[l]}\r
]`;continue}o+=r[l],r[l]==="\\"?i=!0:s&&r[l]==="]"?s=!1:!s&&r[l]==="["&&(s=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var jae,Om,m0t,b3=C(()=>{Eb();Om={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(jae===void 0&&(jae=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),jae),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};m0t=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function C3(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===he.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??ci(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===he.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=x3(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===he.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===he.ZodBranded&&t.keyType._def.type._def.typeName===he.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=w3(t.keyType._def,e);return{...n,propertyNames:o}}}return n}var _3=C(()=>{Jf();v3();b3();bs();_g()});function m$e(t,e){return e.mapStrategy==="record"?C3(t,e):{type:"array",maxItems:125,items:{type:"array",items:[Tn(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ci(e),Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ci(e)],minItems:2,maxItems:2}}}var Wae=C(()=>{Jf();_3();bs()});function h$e(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),r=Array.from(new Set(n.map(o=>typeof o)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}var Hae=C(()=>{});function g$e(t){return t.target==="openAi"?void 0:{not:ci({...t,currentPath:[...t.currentPath,"not"]})}}var Kae=C(()=>{Jf()});function y$e(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var qae=C(()=>{});function v$e(t,e){if(e.target==="openApi3")return w$e(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in g2&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,i)=>{let s=g2[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":return i._def.value===null?[...o,"null"]:o;default:return o}},[]);if(r.length===n.length){let o=r.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(i=>!r.includes(i))],[])};return w$e(t,e)}var g2,w$e,S3=C(()=>{bs();g2={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};w$e=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>Tn(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function x$e(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:g2[t.innerType._def.typeName],nullable:!0}:{type:[g2[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=Tn(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=Tn(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Gae=C(()=>{S3();bs()});function b$e(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",Tae(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?Er(n,"minimum",r.value,r.message,e):Er(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Er(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Er(n,"maximum",r.value,r.message,e):Er(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Er(n,"maximum",r.value,r.message,e));break;case"multipleOf":Er(n,"multipleOf",r.value,r.message,e);break}return n}var Yae=C(()=>{Eb()});function C$e(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},o=[],i=t.shape();for(let a in i){let l=i[a];if(l===void 0||l._def===void 0)continue;let c=y0t(l);c&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),c=!1);let u=Tn(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(r.properties[a]=u,c||o.push(a))}o.length&&(r.required=o);let s=g0t(t,e);return s!==void 0&&(r.additionalProperties=s),r}function g0t(t,e){if(t.catchall._def.typeName!=="ZodNever")return Tn(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function y0t(t){try{return t.isOptional()}catch{return!0}}var Zae=C(()=>{bs()});var _$e,Jae=C(()=>{Jf();bs();_$e=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Tn(t.innerType._def,e);let n=Tn(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ci(e)},n]}:ci(e)}});var S$e,Xae=C(()=>{bs();S$e=(t,e)=>{if(e.pipeStrategy==="input")return Tn(t.in._def,e);if(e.pipeStrategy==="output")return Tn(t.out._def,e);let n=Tn(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});return{allOf:[n,Tn(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]})].filter(r=>r!==void 0)}}});function T$e(t,e){return Tn(t.type._def,e)}var Qae=C(()=>{bs()});function I$e(t,e){let n={type:"array",uniqueItems:!0,items:Tn(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Er(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Er(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var ele=C(()=>{Eb();bs()});function P$e(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>Tn(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:Tn(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>Tn(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var tle=C(()=>{bs()});function E$e(t){return{not:ci(t)}}var nle=C(()=>{Jf()});function A$e(t){return ci(t)}var rle=C(()=>{Jf()});var k$e,ole=C(()=>{bs();k$e=(t,e)=>Tn(t.innerType._def,e)});var M$e,ile=C(()=>{Jf();Mae();Nae();Oae();v3();Rae();Dae();$ae();Fae();Uae();Bae();zae();b3();_3();Wae();Hae();Kae();qae();S3();Gae();Yae();Zae();Jae();Xae();Qae();ele();tle();nle();rle();ole();_g();M$e=(t,e,n)=>{switch(e){case he.ZodString:return x3(t,n);case he.ZodNumber:return b$e(t,n);case he.ZodObject:return C$e(t,n);case he.ZodBigInt:return i$e(t,n);case he.ZodBoolean:return s$e();case he.ZodDate:return Lae(t,n);case he.ZodUndefined:return E$e(n);case he.ZodNull:return y$e(n);case he.ZodArray:return o$e(t,n);case he.ZodUnion:case he.ZodDiscriminatedUnion:return v$e(t,n);case he.ZodIntersection:return d$e(t,n);case he.ZodTuple:return P$e(t,n);case he.ZodRecord:return C3(t,n);case he.ZodLiteral:return f$e(t,n);case he.ZodEnum:return u$e(t);case he.ZodNativeEnum:return h$e(t);case he.ZodNullable:return x$e(t,n);case he.ZodOptional:return _$e(t,n);case he.ZodMap:return m$e(t,n);case he.ZodSet:return I$e(t,n);case he.ZodLazy:return()=>t.getter()._def;case he.ZodPromise:return T$e(t,n);case he.ZodNaN:case he.ZodNever:return g$e(n);case he.ZodEffects:return c$e(t,n);case he.ZodAny:return ci(n);case he.ZodUnknown:return A$e(n);case he.ZodDefault:return l$e(t,n);case he.ZodBranded:return w3(t,n);case he.ZodReadonly:return k$e(t,n);case he.ZodCatch:return a$e(t,n);case he.ZodPipeline:return S$e(t,n);case he.ZodFunction:case he.ZodVoid:case he.ZodSymbol:return;default:return(r=>{})(e)}}});function Tn(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==zDe)return a}if(r&&!n){let a=w0t(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=M$e(t,t.typeName,e),s=typeof i=="function"?Tn(i(),e):i;if(s&&v0t(t,e,s),e.postProcess){let a=e.postProcess(s,t,e);return o.jsonSchema=s,a}return o.jsonSchema=s,s}var w0t,v0t,bs=C(()=>{l3();u3();Jf();ile();w0t=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:c3(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ci(e)):e.$refStrategy==="seen"?ci(e):void 0}},v0t=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var N$e,sle=C(()=>{Sae();Jf();bs();N$e=(t,e)=>{let n=VDe(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[c,u])=>({...l,[c]:Tn(u._def,{...n,currentPath:[...n.basePath,n.definitionPath,c]},!0)??ci(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,i=Tn(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??ci(n),s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...i,[n.definitionPath]:r}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:i}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var O$e=C(()=>{l3();Sae();Eb();u3();Jf();Mae();Nae();Oae();v3();Rae();Dae();$ae();Fae();Uae();Bae();zae();b3();_3();Wae();Hae();Kae();qae();S3();Gae();Yae();Zae();Jae();Xae();Qae();ele();tle();nle();rle();ole();ile();bs();sle()});function x0t(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function ale(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function Ob(t){return x0t(t)&&ale(t)}var y2=C(()=>{$n()});function Pw(t,e){let n=typeof t;if(n!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;let r=t.length;if(r!==e.length)return!1;for(let o=0;o<r;o++)if(!Pw(t[o],e[o]))return!1;return!0}if(n==="object"){if(!t||!e)return t===e;let r=Object.keys(t),o=Object.keys(e);if(r.length!==o.length)return!1;for(let s of r)if(!Pw(t[s],e[s]))return!1;return!0}return t===e}var lle=C(()=>{});function zd(t){return encodeURI(b0t(t))}function b0t(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var T3=C(()=>{});function Ew(t,e=Object.create(null),n=T0t,r=""){if(t&&typeof t=="object"&&!Array.isArray(t)){let i=t.$id||t.id;if(i){let s=new URL(i,n.href);s.hash.length>1?e[s.href]=t:(s.hash="",r===""?n=s:Ew(t,e,n))}}else if(t!==!0&&t!==!1)return e;let o=n.href+(r?"#"+r:"");if(e[o]!==void 0)throw new Error(`Duplicate schema URI "${o}".`);if(e[o]=t,t===!0||t===!1)return e;if(t.__absolute_uri__===void 0&&Object.defineProperty(t,"__absolute_uri__",{enumerable:!1,value:o}),t.$ref&&t.__absolute_ref__===void 0){let i=new URL(t.$ref,n.href);i.hash=i.hash,Object.defineProperty(t,"__absolute_ref__",{enumerable:!1,value:i.href})}if(t.$recursiveRef&&t.__absolute_recursive_ref__===void 0){let i=new URL(t.$recursiveRef,n.href);i.hash=i.hash,Object.defineProperty(t,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(t.$anchor){let i=new URL("#"+t.$anchor,n.href);e[i.href]=t}for(let i in t){if(S0t[i])continue;let s=`${r}/${zd(i)}`,a=t[i];if(Array.isArray(a)){if(C0t[i]){let l=a.length;for(let c=0;c<l;c++)Ew(a[c],e,n,`${s}/${c}`)}}else if(_0t[i])for(let l in a)Ew(a[l],e,n,`${s}/${zd(l)}`);else Ew(a,e,n,s)}return e}var C0t,_0t,S0t,T0t,I3=C(()=>{T3();C0t={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},_0t={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},S0t={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},T0t=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker")});function Uu(t){return t.test.bind(t)}function K0t(t){return t%4===0&&(t%100!==0||t%400===0)}function R$e(t){let e=t.match(I0t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r==2&&K0t(n)?29:P0t[r])}function L$e(t,e){let n=e.match(E0t);if(!n)return!1;let r=+n[1],o=+n[2],i=+n[3],s=!!n[5];return(r<=23&&o<=59&&i<=59||r==23&&o==59&&i==60)&&(!t||s)}function G0t(t){let e=t.split(q0t);return e.length==2&&R$e(e[0])&&L$e(!0,e[1])}function J0t(t){return Y0t.test(t)&&Z0t.test(t)}function Q0t(t){if(X0t.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}var I0t,P0t,E0t,A0t,k0t,M0t,N0t,O0t,R0t,L0t,D0t,$0t,F0t,U0t,B0t,z0t,j0t,V0t,W0t,H0t,cle,q0t,Y0t,Z0t,X0t,ule=C(()=>{I0t=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,P0t=[0,31,28,31,30,31,30,31,31,30,31,30,31],E0t=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,A0t=/^(?=.{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,k0t=/^(?:[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,M0t=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,N0t=/^(?:(?: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,O0t=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,R0t=/^(?:\/(?:[^~/]|~0|~1)*)*$/,L0t=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,D0t=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,$0t=/^\d\d\d\d-[0-1]\d-[0-3]\d$/,F0t=/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,U0t=/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B0t=/^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,z0t=t=>{if(t[0]==='"')return!1;let[e,n,...r]=t.split("@");return!e||!n||r.length!==0||e.length>64||n.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:n.split(".").every(o=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(o))},j0t=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,V0t=/^((([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,W0t=t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t));H0t={date:R$e,time:L$e.bind(void 0,!1),"date-time":G0t,duration:W0t,uri:J0t,"uri-reference":Uu(k0t),"uri-template":Uu(M0t),url:Uu(N0t),email:z0t,hostname:Uu(A0t),ipv4:Uu(j0t),ipv6:Uu(V0t),regex:Q0t,uuid:Uu(O0t),"json-pointer":Uu(R0t),"json-pointer-uri-fragment":Uu(L0t),"relative-json-pointer":Uu(D0t)},cle={...H0t,date:Uu($0t),time:Uu(F0t),"date-time":Uu(U0t),"uri-reference":Uu(B0t)};q0t=/t|\s/i;Y0t=/\/|:/,Z0t=/^(?:[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;X0t=/[^\\]\\Z/});var D$e,$$e=C(()=>{(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(D$e||(D$e={}))});function F$e(t){let e=0,n=t.length,r=0,o;for(;r<n;)e++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<n&&(o=t.charCodeAt(r),(o&64512)==56320&&r++);return e}var dle=C(()=>{});function Yo(t,e,n="2019-09",r=Ew(e),o=!0,i=null,s="#",a="#",l=Object.create(null)){if(e===!0)return{valid:!0,errors:[]};if(e===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let c=typeof t,u;switch(c){case"boolean":case"number":case"string":u=c;break;case"object":t===null?u="null":Array.isArray(t)?u="array":u="object";break;default:throw new Error(`Instances of "${c}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:y,not:w,anyOf:v,allOf:x,oneOf:b,if:_,then:T,else:S,format:P,properties:A,patternProperties:O,additionalProperties:D,unevaluatedProperties:$,minProperties:B,maxProperties:W,propertyNames:F,dependentRequired:Z,dependentSchemas:V,dependencies:H,prefixItems:te,items:fe,additionalItems:me,unevaluatedItems:j,contains:G,minContains:J,maxContains:M,minItems:E,maxItems:R,uniqueItems:L,minimum:K,maximum:Y,exclusiveMinimum:re,exclusiveMaximum:ae,multipleOf:ve,minLength:Te,maxLength:Ee,pattern:nt,__absolute_ref__:rt,__absolute_recursive_ref__:Jt}=e,ke=[];if(p===!0&&i===null&&(i=e),f==="#"){let He=i===null?r[Jt]:i,Ie=`${a}/$recursiveRef`,dt=Yo(t,i===null?e:i,n,r,o,He,s,Ie,l);dt.valid||ke.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:Ie,error:"A subschema had errors."},...dt.errors)}if(d!==void 0){let Ie=r[rt||d];if(Ie===void 0){let Ue=`Unresolved $ref "${d}".`;throw rt&&rt!==d&&(Ue+=`  Absolute URI "${rt}".`),Ue+=`
Known schemas:
- ${Object.keys(r).join(`
- `)}`,new Error(Ue)}let dt=`${a}/$ref`,Me=Yo(t,Ie,n,r,o,i,s,dt,l);if(Me.valid||ke.push({instanceLocation:s,keyword:"$ref",keywordLocation:dt,error:"A subschema had errors."},...Me.errors),n==="4"||n==="7")return{valid:ke.length===0,errors:ke}}if(Array.isArray(m)){let He=m.length,Ie=!1;for(let dt=0;dt<He;dt++)if(u===m[dt]||m[dt]==="integer"&&u==="number"&&t%1===0&&t===t){Ie=!0;break}Ie||ke.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join('", "')}".`})}else m==="integer"?(u!=="number"||t%1||t!==t)&&ke.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&ke.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u==="object"||u==="array"?Pw(t,h)||ke.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):t!==h&&ke.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u==="object"||u==="array"?g.some(He=>Pw(t,He))||ke.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(He=>t===He)||ke.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),w!==void 0){let He=`${a}/not`;Yo(t,w,n,r,o,i,s,He).valid&&ke.push({instanceLocation:s,keyword:"not",keywordLocation:He,error:'Instance matched "not" schema.'})}let Ln=[];if(v!==void 0){let He=`${a}/anyOf`,Ie=ke.length,dt=!1;for(let Me=0;Me<v.length;Me++){let Ue=v[Me],it=Object.create(l),St=Yo(t,Ue,n,r,o,p===!0?i:null,s,`${He}/${Me}`,it);ke.push(...St.errors),dt=dt||St.valid,St.valid&&Ln.push(it)}dt?ke.length=Ie:ke.splice(Ie,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:He,error:"Instance does not match any subschemas."})}if(x!==void 0){let He=`${a}/allOf`,Ie=ke.length,dt=!0;for(let Me=0;Me<x.length;Me++){let Ue=x[Me],it=Object.create(l),St=Yo(t,Ue,n,r,o,p===!0?i:null,s,`${He}/${Me}`,it);ke.push(...St.errors),dt=dt&&St.valid,St.valid&&Ln.push(it)}dt?ke.length=Ie:ke.splice(Ie,0,{instanceLocation:s,keyword:"allOf",keywordLocation:He,error:"Instance does not match every subschema."})}if(b!==void 0){let He=`${a}/oneOf`,Ie=ke.length,dt=b.filter((Me,Ue)=>{let it=Object.create(l),St=Yo(t,Me,n,r,o,p===!0?i:null,s,`${He}/${Ue}`,it);return ke.push(...St.errors),St.valid&&Ln.push(it),St.valid}).length;dt===1?ke.length=Ie:ke.splice(Ie,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:He,error:`Instance does not match exactly one subschema (${dt} matches).`})}if((u==="object"||u==="array")&&Object.assign(l,...Ln),_!==void 0){let He=`${a}/if`;if(Yo(t,_,n,r,o,i,s,He,l).valid){if(T!==void 0){let dt=Yo(t,T,n,r,o,i,s,`${a}/then`,l);dt.valid||ke.push({instanceLocation:s,keyword:"if",keywordLocation:He,error:'Instance does not match "then" schema.'},...dt.errors)}}else if(S!==void 0){let dt=Yo(t,S,n,r,o,i,s,`${a}/else`,l);dt.valid||ke.push({instanceLocation:s,keyword:"if",keywordLocation:He,error:'Instance does not match "else" schema.'},...dt.errors)}}if(u==="object"){if(y!==void 0)for(let Me of y)Me in t||ke.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${Me}".`});let He=Object.keys(t);if(B!==void 0&&He.length<B&&ke.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${B} properties.`}),W!==void 0&&He.length>W&&ke.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${W} properties.`}),F!==void 0){let Me=`${a}/propertyNames`;for(let Ue in t){let it=`${s}/${zd(Ue)}`,St=Yo(Ue,F,n,r,o,i,it,Me);St.valid||ke.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:Me,error:`Property name "${Ue}" does not match schema.`},...St.errors)}}if(Z!==void 0){let Me=`${a}/dependantRequired`;for(let Ue in Z)if(Ue in t){let it=Z[Ue];for(let St of it)St in t||ke.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:Me,error:`Instance has "${Ue}" but does not have "${St}".`})}}if(V!==void 0)for(let Me in V){let Ue=`${a}/dependentSchemas`;if(Me in t){let it=Yo(t,V[Me],n,r,o,i,s,`${Ue}/${zd(Me)}`,l);it.valid||ke.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:Ue,error:`Instance has "${Me}" but does not match dependant schema.`},...it.errors)}}if(H!==void 0){let Me=`${a}/dependencies`;for(let Ue in H)if(Ue in t){let it=H[Ue];if(Array.isArray(it))for(let St of it)St in t||ke.push({instanceLocation:s,keyword:"dependencies",keywordLocation:Me,error:`Instance has "${Ue}" but does not have "${St}".`});else{let St=Yo(t,it,n,r,o,i,s,`${Me}/${zd(Ue)}`);St.valid||ke.push({instanceLocation:s,keyword:"dependencies",keywordLocation:Me,error:`Instance has "${Ue}" but does not match dependant schema.`},...St.errors)}}}let Ie=Object.create(null),dt=!1;if(A!==void 0){let Me=`${a}/properties`;for(let Ue in A){if(!(Ue in t))continue;let it=`${s}/${zd(Ue)}`,St=Yo(t[Ue],A[Ue],n,r,o,i,it,`${Me}/${zd(Ue)}`);if(St.valid)l[Ue]=Ie[Ue]=!0;else if(dt=o,ke.push({instanceLocation:s,keyword:"properties",keywordLocation:Me,error:`Property "${Ue}" does not match schema.`},...St.errors),dt)break}}if(!dt&&O!==void 0){let Me=`${a}/patternProperties`;for(let Ue in O){let it=new RegExp(Ue,"u"),St=O[Ue];for(let $r in t){if(!it.test($r))continue;let oo=`${s}/${zd($r)}`,Bn=Yo(t[$r],St,n,r,o,i,oo,`${Me}/${zd(Ue)}`);Bn.valid?l[$r]=Ie[$r]=!0:(dt=o,ke.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:Me,error:`Property "${$r}" matches pattern "${Ue}" but does not match associated schema.`},...Bn.errors))}}}if(!dt&&D!==void 0){let Me=`${a}/additionalProperties`;for(let Ue in t){if(Ie[Ue])continue;let it=`${s}/${zd(Ue)}`,St=Yo(t[Ue],D,n,r,o,i,it,Me);St.valid?l[Ue]=!0:(dt=o,ke.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:Me,error:`Property "${Ue}" does not match additional properties schema.`},...St.errors))}}else if(!dt&&$!==void 0){let Me=`${a}/unevaluatedProperties`;for(let Ue in t)if(!l[Ue]){let it=`${s}/${zd(Ue)}`,St=Yo(t[Ue],$,n,r,o,i,it,Me);St.valid?l[Ue]=!0:ke.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:Me,error:`Property "${Ue}" does not match unevaluated properties schema.`},...St.errors)}}}else if(u==="array"){R!==void 0&&t.length>R&&ke.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${t.length} > ${R}).`}),E!==void 0&&t.length<E&&ke.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${t.length} < ${E}).`});let He=t.length,Ie=0,dt=!1;if(te!==void 0){let Me=`${a}/prefixItems`,Ue=Math.min(te.length,He);for(;Ie<Ue;Ie++){let it=Yo(t[Ie],te[Ie],n,r,o,i,`${s}/${Ie}`,`${Me}/${Ie}`);if(l[Ie]=!0,!it.valid&&(dt=o,ke.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:Me,error:"Items did not match schema."},...it.errors),dt))break}}if(fe!==void 0){let Me=`${a}/items`;if(Array.isArray(fe)){let Ue=Math.min(fe.length,He);for(;Ie<Ue;Ie++){let it=Yo(t[Ie],fe[Ie],n,r,o,i,`${s}/${Ie}`,`${Me}/${Ie}`);if(l[Ie]=!0,!it.valid&&(dt=o,ke.push({instanceLocation:s,keyword:"items",keywordLocation:Me,error:"Items did not match schema."},...it.errors),dt))break}}else for(;Ie<He;Ie++){let Ue=Yo(t[Ie],fe,n,r,o,i,`${s}/${Ie}`,Me);if(l[Ie]=!0,!Ue.valid&&(dt=o,ke.push({instanceLocation:s,keyword:"items",keywordLocation:Me,error:"Items did not match schema."},...Ue.errors),dt))break}if(!dt&&me!==void 0){let Ue=`${a}/additionalItems`;for(;Ie<He;Ie++){let it=Yo(t[Ie],me,n,r,o,i,`${s}/${Ie}`,Ue);l[Ie]=!0,it.valid||(dt=o,ke.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:Ue,error:"Items did not match additional items schema."},...it.errors))}}}if(G!==void 0)if(He===0&&J===void 0)ke.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(J!==void 0&&He<J)ke.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${He}) than minContains (${J}).`});else{let Me=`${a}/contains`,Ue=ke.length,it=0;for(let St=0;St<He;St++){let $r=Yo(t[St],G,n,r,o,i,`${s}/${St}`,Me);$r.valid?(l[St]=!0,it++):ke.push(...$r.errors)}it>=(J||0)&&(ke.length=Ue),J===void 0&&M===void 0&&it===0?ke.splice(Ue,0,{instanceLocation:s,keyword:"contains",keywordLocation:Me,error:"Array does not contain item matching schema."}):J!==void 0&&it<J?ke.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${J} items matching schema. Only ${it} items were found.`}):M!==void 0&&it>M&&ke.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${M} items matching schema. ${it} items were found.`})}if(!dt&&j!==void 0){let Me=`${a}/unevaluatedItems`;for(Ie;Ie<He;Ie++){if(l[Ie])continue;let Ue=Yo(t[Ie],j,n,r,o,i,`${s}/${Ie}`,Me);l[Ie]=!0,Ue.valid||ke.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:Me,error:"Items did not match unevaluated items schema."},...Ue.errors)}}if(L)for(let Me=0;Me<He;Me++){let Ue=t[Me],it=typeof Ue=="object"&&Ue!==null;for(let St=0;St<He;St++){if(Me===St)continue;let $r=t[St];(Ue===$r||it&&(typeof $r=="object"&&$r!==null)&&Pw(Ue,$r))&&(ke.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${Me} and ${St}.`}),Me=Number.MAX_SAFE_INTEGER,St=Number.MAX_SAFE_INTEGER)}}}else if(u==="number"){if(n==="4"?(K!==void 0&&(re===!0&&t<=K||t<K)&&ke.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${re?"or equal to ":""} ${K}.`}),Y!==void 0&&(ae===!0&&t>=Y||t>Y)&&ke.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${ae?"or equal to ":""} ${Y}.`})):(K!==void 0&&t<K&&ke.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${t} is less than ${K}.`}),Y!==void 0&&t>Y&&ke.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${t} is greater than ${Y}.`}),re!==void 0&&t<=re&&ke.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${t} is less than ${re}.`}),ae!==void 0&&t>=ae&&ke.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${t} is greater than or equal to ${ae}.`})),ve!==void 0){let He=t%ve;Math.abs(0-He)>=11920929e-14&&Math.abs(ve-He)>=11920929e-14&&ke.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${t} is not a multiple of ${ve}.`})}}else if(u==="string"){let He=Te===void 0&&Ee===void 0?0:F$e(t);Te!==void 0&&He<Te&&ke.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${He} < ${Te}).`}),Ee!==void 0&&He>Ee&&ke.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${He} > ${Ee}).`}),nt!==void 0&&!new RegExp(nt,"u").test(t)&&ke.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),P!==void 0&&cle[P]&&!cle[P](t)&&ke.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${P}".`})}return{valid:ke.length===0,errors:ke}}var fle=C(()=>{lle();I3();ule();T3();dle()});var U$e=C(()=>{I3();fle()});var P3=C(()=>{lle();I3();ule();T3();$$e();dle();fle();U$e()});function Hr(t,e){let n=!e&&t!=null&&typeof t=="object";if(n){let o=B$e.get(t);if(o)return o}let r;if(ale(t)&&!hl(t))r=t["~standard"].jsonSchema.input({target:"draft-07"});else if(hl(t)){let o=Cae(t,!0);AT(o)?r=Pb(c2(o,!0),e):r=Pb(t,e)}else Zf(t)?r=N$e(t):r=t;return n&&r!=null&&typeof r=="object"&&B$e.set(t,r),r}function w2(t){if(!t||typeof t!="object"||Object.keys(t).length===0||Array.isArray(t))return!1;if("type"in t)return typeof t.type=="string"?t.type==="string":Array.isArray(t.type)?t.type.every(e=>e==="string"):!1;if("enum"in t)return Array.isArray(t.enum)&&t.enum.length>0&&t.enum.every(e=>typeof e=="string");if("const"in t)return typeof t.const=="string";if("allOf"in t&&Array.isArray(t.allOf))return t.allOf.some(e=>w2(e));if("anyOf"in t&&Array.isArray(t.anyOf)||"oneOf"in t&&Array.isArray(t.oneOf)){let e="anyOf"in t?t.anyOf:t.oneOf;return e.length>0&&e.every(n=>w2(n))}if("not"in t)return!1;if("$ref"in t&&typeof t.$ref=="string"){let e=t.$ref,n=Ew(t);return n[e]?w2(n[e]):!1}return!1}var B$e,Bu=C(()=>{$n();vg();sle();O$e();y2();Ql();P3();B$e=new WeakMap});function Aw(t){if(typeof t=="object"&&t!==null){let e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(let n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(Aw):typeof e[n]=="object"&&e[n]!==null&&(e[n]=Aw(e[n])));return e}return t}function v2(t){let{$schema:e,...n}=Aw(jr(t)?Hr(t):t);return n}function z$e(t){let{$schema:e,...n}=Aw(t);return n}var E3=C(()=>{Bd();Bu()});function YT(t,e,n=[]){if(t==null||typeof t!="object")return;let r=t;if(Array.isArray(r.enum)&&r.enum.some(o=>o==="")){let o=n.length?` at path "${n.join(".")}"`:"",i=e?` in tool "${e}"`:"";throw new Error(`Invalid enum: empty string not allowed${i}${o}. Gemini API rejects empty strings in enums.`)}if(r.type==="object"&&r.properties&&typeof r.properties=="object")for(let[o,i]of Object.entries(r.properties))YT(i,e,[...n,o]);r.items&&YT(r.items,e,[...n,"[]"]);for(let o of["anyOf","oneOf","allOf"]){let i=r[o];Array.isArray(i)&&i.forEach((s,a)=>YT(s,e,[...n,`${o}[${a}]`]))}r.additionalProperties&&typeof r.additionalProperties=="object"&&YT(r.additionalProperties,e,[...n,"additionalProperties"])}var j$e=C(()=>{});function tc(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function x2(t){return tc(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function b2(t){return tc(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function ple(t){return tc(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function mle(t){if(tc(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function A3(t){let e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);let n=e[0].trim(),r=e[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);let o={};for(let i of t.split(";").slice(1)){let s=i.split("=");if(s.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);let a=s[0].trim(),l=s[1].trim();if(a==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);o[a]=l}return{type:n,subtype:r,parameters:o}}function Bc({dataUrl:t,asTypedArray:e=!1}){let n=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),r;if(n){r=n[1].toLowerCase();let o=e?Uint8Array.from(atob(n[2]),i=>i.charCodeAt(0)):n[2];return{mime_type:r,data:o}}}function kw(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}var C2=C(()=>{});function hle(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}var gle=C(()=>{});function rPt(t){return t.replace(ePt,"$1_$2").replace(tPt,"$1_$2").replace(nPt,"_").toLowerCase()}function V$e(t,e){return e?.[t]||rPt(t)}function W$e(t,e,n){let r={};for(let o in t)Object.hasOwn(t,o)&&(r[e(o,n)]=t[o]);return r}var ePt,tPt,nPt,H$e=C(()=>{ePt=/([A-Z]+)([A-Z][a-z0-9]+)/g,tPt=/([a-z0-9])([A-Z])/g,nPt=/[-_\s]+/g});function iPt(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}function sPt(t){return{[oPt]:t}}function aPt(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function lPt(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function k3(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return lPt(t);if(aPt(t))return t;e.add(t);let n=t;if(iPt(n))return e.delete(t),sPt(n);let r={};for(let[o,i]of Object.entries(n))r[o]=k3(i,e);return e.delete(t),r}return Array.isArray(t)?t.map(n=>k3(n,e)):t}var oPt,K$e=C(()=>{oPt="__lc_escaped__"});function q$e(t){return Array.isArray(t)?[...t]:{...t}}function cPt(t,e){let n=q$e(t);for(let[r,o]of Object.entries(e)){let[i,...s]=r.split(".").reverse(),a=n;for(let l of s.reverse()){if(a[l]===void 0)break;a[l]=q$e(a[l]),a=a[l]}a[i]!==void 0&&(a[i]={lc:1,type:"secret",id:[o]})}return n}function yle(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var zu,Rb=C(()=>{$n();H$e();K$e();zu=class G$e{constructor(e,...n){I(this,"lc_serializable",!1);I(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=e??{}}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,yle(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof G$e||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},n={},r=Object.keys(this.lc_kwargs).reduce((a,l)=>(a[l]=l in this?this[l]:this.lc_kwargs[l],a),{});for(let a=Object.getPrototypeOf(this);a;a=Object.getPrototypeOf(a))Object.assign(e,Reflect.get(a,"lc_aliases",this)),Object.assign(n,Reflect.get(a,"lc_secrets",this)),Object.assign(r,Reflect.get(a,"lc_attributes",this));Object.keys(n).forEach(a=>{let l=this,c=r,[u,...d]=a.split(".").reverse();for(let f of d.reverse()){if(!(f in l)||l[f]===void 0)return;(!(f in c)||c[f]===void 0)&&(typeof l[f]=="object"&&l[f]!=null?c[f]={}:Array.isArray(l[f])&&(c[f]=[])),l=l[f],c=c[f]}u in l&&l[u]!==void 0&&(c[u]=c[u]||l[u])});let o={},i=new WeakSet;i.add(this);for(let[a,l]of Object.entries(r))o[a]=k3(l,i);let s=W$e(Object.keys(n).length?cPt(o,n):o,V$e,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:s}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}});function yt(t,e){return Wt(t)&&t.type===e}function Wt(t){return typeof t=="object"&&t!==null}function js(t){return Array.isArray(t)}function Oe(t){return typeof t=="string"}function jd(t){return typeof t=="number"}function M3(t){return t instanceof Uint8Array}function wle(t){try{return JSON.parse(t)}catch{return}}var Vd,tp=C(()=>{Vd=t=>t()});function uPt(t){if(t.type==="char_location"&&Oe(t.document_title)&&jd(t.start_char_index)&&jd(t.end_char_index)&&Oe(t.cited_text)){let{document_title:e,start_char_index:n,end_char_index:r,cited_text:o,...i}=t;return{...i,type:"citation",source:"char",title:e??void 0,startIndex:n,endIndex:r,citedText:o}}if(t.type==="page_location"&&Oe(t.document_title)&&jd(t.start_page_number)&&jd(t.end_page_number)&&Oe(t.cited_text)){let{document_title:e,start_page_number:n,end_page_number:r,cited_text:o,...i}=t;return{...i,type:"citation",source:"page",title:e??void 0,startIndex:n,endIndex:r,citedText:o}}if(t.type==="content_block_location"&&Oe(t.document_title)&&jd(t.start_block_index)&&jd(t.end_block_index)&&Oe(t.cited_text)){let{document_title:e,start_block_index:n,end_block_index:r,cited_text:o,...i}=t;return{...i,type:"citation",source:"block",title:e??void 0,startIndex:n,endIndex:r,citedText:o}}if(t.type==="web_search_result_location"&&Oe(t.url)&&Oe(t.title)&&Oe(t.encrypted_index)&&Oe(t.cited_text)){let{url:e,title:n,encrypted_index:r,cited_text:o,...i}=t;return{...i,type:"citation",source:"url",url:e,title:n,startIndex:Number(r),endIndex:Number(r),citedText:o}}if(t.type==="search_result_location"&&Oe(t.source)&&Oe(t.title)&&jd(t.start_block_index)&&jd(t.end_block_index)&&Oe(t.cited_text)){let{source:e,title:n,start_block_index:r,end_block_index:o,cited_text:i,...s}=t;return{...s,type:"citation",source:"search",url:e,title:n??void 0,startIndex:r,endIndex:o,citedText:i}}}function Z$e(t){if(yt(t,"document")&&Wt(t.source)&&"type"in t.source){if(t.source.type==="base64"&&Oe(t.source.media_type)&&Oe(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&Oe(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&Oe(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&Oe(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(yt(t,"image")&&Wt(t.source)&&"type"in t.source){if(t.source.type==="base64"&&Oe(t.source.media_type)&&Oe(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&Oe(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&Oe(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function J$e(t){function*e(){for(let n of t){let r=Z$e(n);r?yield r:yield n}}return Array.from(e())}function Y$e(t){function*e(){let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n){if(yt(r,"text")&&Oe(r.text)){let{text:o,citations:i,...s}=r;if(js(i)&&i.length){let a=i.reduce((l,c)=>{let u=uPt(c);return u?[...l,u]:l},[]);yield{...s,type:"text",text:o,annotations:a};continue}else{yield{...s,type:"text",text:o};continue}}else if(yt(r,"thinking")&&Oe(r.thinking)){let{thinking:o,signature:i,...s}=r;yield{...s,type:"reasoning",reasoning:o,signature:i};continue}else if(yt(r,"redacted_thinking")){yield{type:"non_standard",value:r};continue}else if(yt(r,"tool_use")&&Oe(r.name)&&Oe(r.id)){yield{type:"tool_call",id:r.id,name:r.name,args:r.input};continue}else if(yt(r,"input_json_delta")){if(dPt(t)&&t.tool_call_chunks?.length){let o=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:o.id,name:o.name,args:o.args,index:o.index};continue}}else if(yt(r,"server_tool_use")&&Oe(r.name)&&Oe(r.id)){let{name:o,id:i}=r;if(o==="web_search"){yield{id:i,type:"server_tool_call",name:"web_search",args:{query:Vd(()=>{if(typeof r.input=="string")return r.input;if(Wt(r.input)&&Oe(r.input.query))return r.input.query;if(Oe(r.partial_json)){let s=wle(r.partial_json);if(s?.query)return s.query}return""})}};continue}else if(r.name==="code_execution"){yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:Vd(()=>{if(typeof r.input=="string")return r.input;if(Wt(r.input)&&Oe(r.input.code))return r.input.code;if(Oe(r.partial_json)){let s=wle(r.partial_json);if(s?.code)return s.code}return""})}};continue}}else if(yt(r,"web_search_tool_result")&&Oe(r.tool_use_id)&&js(r.content)){let{content:o,tool_use_id:i}=r;yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:o.reduce((s,a)=>yt(a,"web_search_result")?[...s,a.url]:s,[])}};continue}else if(yt(r,"code_execution_tool_result")&&Oe(r.tool_use_id)&&Wt(r.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(yt(r,"mcp_tool_use")){yield{id:r.id,type:"server_tool_call",name:"mcp_tool_use",args:r.input};continue}else if(yt(r,"mcp_tool_result")&&Oe(r.tool_use_id)&&Wt(r.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:r.tool_use_id,status:"success",output:r.content};continue}else if(yt(r,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:r.input};continue}else if(yt(r,"search_result")){yield{id:r.id,type:"non_standard",value:r};continue}else if(yt(r,"tool_result")){yield{id:r.id,type:"non_standard",value:r};continue}else{let o=Z$e(r);if(o){yield o;continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}function dPt(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}var X$e,vle=C(()=>{tp();X$e={translateContent:Y$e,translateContentChunk:Y$e}});function fPt(t){return x2(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:b2(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:ple(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function Q$e(t){return t.map(fPt)}function eFe(t){return!!(yt(t,"image_url")&&Wt(t.image_url)||yt(t,"input_audio")&&Wt(t.input_audio)||yt(t,"file")&&Wt(t.file))}function tFe(t){if(yt(t,"image_url")&&Wt(t.image_url)&&Oe(t.image_url.url)){let e=Bc({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(yt(t,"input_audio")&&Wt(t.input_audio)&&Oe(t.input_audio.data)&&Oe(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(yt(t,"file")&&Wt(t.file)&&Oe(t.file.data)){let e=Bc({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(Oe(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}var xle=C(()=>{C2();tp()});function pPt(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...N3(t.content));for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function mPt(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...N3(t.content));for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function N3(t){let e=[];for(let n of t)eFe(n)?e.push(tFe(n)):e.push(n);return e}function hPt(t){if(t.type==="url_citation"){let{url:e,title:n,start_index:r,end_index:o}=t;return{type:"citation",url:e,title:n,startIndex:r,endIndex:o}}if(t.type==="file_citation"){let{file_id:e,filename:n,index:r}=t;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:e}}return t}function nFe(t){function*e(){Wt(t.additional_kwargs?.reasoning)&&js(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((r,o)=>Wt(o)&&Oe(o.text)?`${r}${o.text}`:r,"")});let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n)if(yt(r,"text")){let{text:o,annotations:i,phase:s,extras:a,...l}=r,c=Wt(a)?{...a}:{};Oe(s)&&(c.phase=s);let u=Object.keys(c).length>0?{extras:c}:{};Array.isArray(i)?yield{...l,...u,type:"text",text:String(o),annotations:i.map(hPt)}:yield{...l,...u,type:"text",text:String(o)}}for(let r of t.tool_calls??[])yield{type:"tool_call",id:r.id,name:r.name,args:r.args};if(Wt(t.additional_kwargs)&&js(t.additional_kwargs.tool_outputs))for(let r of t.additional_kwargs.tool_outputs){if(yt(r,"web_search_call")){let o={};if(Wt(r.action)&&Oe(r.action.query)&&(o.query=r.action.query),yield{id:r.id,type:"server_tool_call",name:"web_search",args:o},r.status==="completed"||r.status==="failed"){let i={};Wt(r.action)&&(i.action=r.action),yield{type:"server_tool_call_result",toolCallId:Oe(r.id)?r.id:"",status:r.status==="completed"?"success":"error",output:i}}continue}else if(yt(r,"file_search_call")){yield{id:r.id,type:"server_tool_call",name:"file_search",args:{queries:js(r.queries)?r.queries:[]}},(r.status==="completed"||r.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:Oe(r.id)?r.id:"",status:r.status==="completed"?"success":"error",output:js(r.results)?{results:r.results}:{}});continue}else if(yt(r,"computer_call")){yield{type:"non_standard",value:r};continue}else if(yt(r,"code_interpreter_call")){if(Oe(r.code)&&(yield{id:r.id,type:"server_tool_call",name:"code_interpreter",args:{code:r.code}}),js(r.outputs)){let o=Vd(()=>{if(r.status!=="in_progress"){if(r.status==="completed")return 0;if(r.status==="incomplete")return 127;if(r.status!=="interpreting"&&r.status==="failed")return 1}});for(let i of r.outputs)if(yt(i,"logs")){yield{type:"server_tool_call_result",toolCallId:r.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:o??0,stderr:[0,void 0].includes(o)?void 0:String(i.logs),stdout:[0,void 0].includes(o)?String(i.logs):void 0}};continue}}continue}else if(yt(r,"mcp_call")){yield{id:r.id,type:"server_tool_call",name:"mcp_call",args:r.input};continue}else if(yt(r,"mcp_list_tools")){yield{id:r.id,type:"server_tool_call",name:"mcp_list_tools",args:r.input};continue}else if(yt(r,"mcp_approval_request")){yield{type:"non_standard",value:r};continue}else if(yt(r,"tool_search_call")){let o={};Wt(r.arguments)&&Object.assign(o,r.arguments);let i={};Oe(r.execution)&&(i.execution=r.execution),Oe(r.status)&&(i.status=r.status),Oe(r.call_id)&&(i.call_id=r.call_id),yield{id:Oe(r.id)?r.id:"",type:"server_tool_call",name:"tool_search",args:o,...Object.keys(i).length>0?{extras:i}:{}};continue}else if(yt(r,"tool_search_output")){let o={name:"tool_search"};Oe(r.execution)&&(o.execution=r.execution),yield{type:"server_tool_call_result",toolCallId:Oe(r.id)?r.id:"",status:r.status==="completed"?"success":r.status==="failed"?"error":"success",output:{tools:js(r.tools)?r.tools:[]},extras:o};continue}else if(yt(r,"image_generation_call")){Oe(r.result)&&(yield{type:"image",mimeType:"image/png",data:r.result,id:Oe(r.id)?r.id:void 0,metadata:{status:Oe(r.status)?r.status:void 0}}),yield{type:"non_standard",value:r};continue}Wt(r)&&(yield{type:"non_standard",value:r})}}return Array.from(e())}function gPt(t){function*e(){yield*nFe(t);for(let n of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(e())}var rFe,ble=C(()=>{tp();xle();rFe={translateContent:t=>typeof t.content=="string"?pPt(t):nFe(t),translateContentChunk:t=>typeof t.content=="string"?mPt(t):gPt(t)}});function oFe(t,e="pretty"){return e==="pretty"?yPt(t):JSON.stringify(t)}function yPt(t){let e=[],n=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),o="=".repeat(r),i=n.length%2===0?o:`${o}=`;if(e.push(`${o}${n}${i}`),t.type==="ai"){let s=t;if(s.tool_calls&&s.tool_calls.length>0){e.push("Tool Calls:");for(let a of s.tool_calls){e.push(`  ${a.name} (${a.id})`),e.push(` Call ID: ${a.id}`),e.push("  Args:");for(let[l,c]of Object.entries(a.args))e.push(`    ${l}: ${typeof c=="object"?JSON.stringify(c):c}`)}}}if(t.type==="tool"){let s=t;s.name&&e.push(`Name: ${s.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
`)}var iFe=C(()=>{});function sFe(t){return Array.isArray(t)?t:typeof t=="string"?t===""?[]:[{type:"text",text:t}]:t==null?[]:[t]}function zc(t,e){if(typeof t=="string")return t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(n=>tc(n))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e];if(Array.isArray(e)){let n=sFe(t);return ZT(n,e)??[...n,...e]}else return e===""?t:Array.isArray(t)&&t.some(n=>tc(n))?[...t,{type:"file",source_type:"text",text:e}]:[...sFe(t),{type:"text",text:e}]}function _le(t,e){return t==="error"||e==="error"?"error":"success"}function wPt(t,e){function n(r,o){if(typeof r!="object"||r===null||r===void 0)return r;if(o>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(s=>n(s,o+1));let i={};for(let s of Object.keys(r))i[s]=n(r[s],o+1);return i}return JSON.stringify(n(t,0),null,2)}function Ii(t,e,n){let r=n?.ignoreKeys??dFe;if(t==null&&e==null)return;if(t==null||e==null)return t??e;let o={...t};for(let[i,s]of Object.entries(e))if(o[i]==null)o[i]=s;else{if(s==null)continue;if(typeof o[i]!=typeof s||Array.isArray(o[i])!==Array.isArray(s))throw new Error(`field[${i}] already exists in the message chunk, but with a different type.`);if(typeof o[i]=="string"){if(i==="type")continue;if(["id","name","output_version","model_provider"].includes(i))s&&(o[i]=s);else{if(r.includes(i))continue;o[i]+=s}}else if(typeof o[i]=="number"){if(r.includes(i))continue;o[i]=o[i]+s}else if(typeof o[i]=="object"&&!Array.isArray(o[i]))o[i]=Ii(o[i],s,n);else if(Array.isArray(o[i]))o[i]=ZT(o[i],s,n);else{if(o[i]===s)continue;console.warn(`field[${i}] already exists in this message chunk and value has unsupported type.`)}}return o}function vPt(t){return typeof t=="number"||typeof t=="string"}function aFe(t){return typeof t!="object"||t===null||!("index"in t)?!1:vPt(t.index)}function lFe(t){if(typeof t!="object"||t===null||!("id"in t))return!1;let e=t.id;return e!=null&&e!==""}function cFe(t){return t.endsWith("_delta")?t.slice(0,-6):t}function xPt(t,e){return typeof t!="object"||t===null||typeof e!="object"||e===null||!("type"in t)||!("type"in e)?!1:typeof t.type=="string"&&typeof e.type=="string"&&cFe(t.type)!==cFe(e.type)}function bPt(t,e){let n=aFe(e),r=lFe(e);return!n&&!r?-1:t.findIndex(o=>{let i=aFe(o),s=lFe(o);return n&&i?o.index!==e.index||xPt(o,e)?!1:s&&r?o.id===e.id:!0:!n&&!i&&r&&s?o.id===e.id:!1})}function ZT(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{let r=[...t];for(let o of e){let i=bPt(r,o);if(i!==-1)r[i]=Ii(r[i],o,n);else{if(typeof o=="object"&&o!==null&&"text"in o&&o.text==="")continue;r.push(o)}}return r}}}function Sle(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types.
Left ${typeof t}
Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return ZT(t,e,n);if(typeof t=="object"&&typeof e=="object")return Ii(t,e,n);if(t===e)return t;throw new Error(`Can not merge objects of different types.
Left ${t}
Right ${e}`)}}function Tle(t){return typeof t.role=="string"}function np(t){return typeof t?._getType=="function"}function O3(t){return ju.isInstance(t)}var Cle,uFe,Vs,dFe,ju,nc=C(()=>{Rb();C2();vle();xle();ble();gle();iFe();Cle=Symbol.for("langchain.message");Vs=class extends zu{constructor(e){let n=typeof e=="string"||Array.isArray(e)?{content:e}:e;n.additional_kwargs||(n.additional_kwargs={}),n.response_metadata||(n.response_metadata={});super(n);I(this,"lc_namespace",["langchain_core","messages"]);I(this,"lc_serializable",!0);I(this,uFe,!0);I(this,"id");I(this,"name");I(this,"content");I(this,"additional_kwargs");I(this,"response_metadata");this.name=n.name,n.content===void 0&&n.contentBlocks!==void 0?(this.content=n.contentBlocks,this.response_metadata={output_version:"v1",...n.response_metadata}):n.content!==void 0?(this.content=n.content??[],this.response_metadata=n.response_metadata):(this.content=[],this.response_metadata=n.response_metadata),this.additional_kwargs=n.additional_kwargs,this.id=n.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){let e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[Q$e,N3,J$e].reduce((n,r)=>r(n),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&Cle in e&&e[Cle]===!0&&hle(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(uFe=Cle,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;let n=wPt(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${n}`}toFormattedString(e="pretty"){return oFe(this,e)}},dFe=["index","created","timestamp"];ju=class fFe extends Vs{static isInstance(e){if(!super.isInstance(e))return!1;let n=Object.getPrototypeOf(e);for(;n!==null;){if(n===fFe.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}}});function Ile(t,e){return Ii(t,e)??{}}function pFe(t,e){let n={};return(t?.audio!==void 0||e?.audio!==void 0)&&(n.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(n.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(n.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(n.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(n.text=(t?.text??0)+(e?.text??0)),n}function CPt(t,e){let n={...pFe(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(n.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(n.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),n}function _Pt(t,e){let n={...pFe(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(n.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),n}function _2(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:CPt(t?.input_token_details,e?.input_token_details),output_token_details:_Pt(t?.output_token_details,e?.output_token_details)}}var R3=C(()=>{nc()});function Ple(t){return t!=null&&typeof t=="object"&&"lc_direct_tool_output"in t&&t.lc_direct_tool_output===!0}function Ele(t){let e=[],n=[];for(let r of t)if(r.function){let o=r.function.name;try{let i=JSON.parse(r.function.arguments);e.push({name:o||"",args:i||{},id:r.id})}catch{n.push({name:o,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,n]}function Ale(t){return typeof t=="object"&&t!==null&&"getType"in t&&typeof t.getType=="function"&&t.getType()==="tool"}var Wd,Bk,zk=C(()=>{$n();nc();Wd=class extends Vs{constructor(e,n,r){let o=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:n}:e;super(o);I(this,"lc_direct_tool_output",!0);I(this,"type","tool");I(this,"status");I(this,"tool_call_id");I(this,"metadata");I(this,"artifact");this.tool_call_id=o.tool_call_id,this.artifact=o.artifact,this.status=o.status,this.metadata=o.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},Bk=class extends ju{constructor(e){super(e);I(this,"type","tool");I(this,"tool_call_id");I(this,"status");I(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){let n=this.constructor;return new n({content:zc(this.content,e.content),additional_kwargs:Ii(this.additional_kwargs,e.additional_kwargs),response_metadata:Ii(this.response_metadata,e.response_metadata),artifact:Sle(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:_le(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}});function kle(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function SPt(t){if(Wt(t.document)&&Wt(t.document.source)){let e=kle(Wt(t.document)&&Oe(t.document.format)?t.document.format:"");if(Wt(t.document.source)){if(Wt(t.document.source.s3Location)&&Oe(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(M3(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(Oe(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(js(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((n,r)=>Wt(r)&&Oe(r.text)?n+r.text:n,"")}}}return{type:"non_standard",value:t}}function TPt(t){if(yt(t,"image")&&Wt(t.image)){let e=kle(Wt(t.image)&&Oe(t.image.format)?t.image.format:"");if(Wt(t.image.source)){if(Wt(t.image.source.s3Location)&&Oe(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(M3(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function IPt(t){if(yt(t,"video")&&Wt(t.video)){let e=kle(Wt(t.video)&&Oe(t.video.format)?t.video.format:"");if(Wt(t.video.source)){if(Wt(t.video.source.s3Location)&&Oe(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(M3(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function mFe(t){function*e(){let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n){if(yt(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(yt(r,"citations_content")&&Wt(r.citationsContent)){yield{type:"text",text:js(r.citationsContent.content)?r.citationsContent.content.reduce((o,i)=>Wt(i)&&Oe(i.text)?o+i.text:o,""):"",annotations:js(r.citationsContent.citations)?r.citationsContent.citations.reduce((o,i)=>{if(Wt(i)){let s=js(i.sourceContent)?i.sourceContent.reduce((l,c)=>Wt(c)&&Oe(c.text)?l+c.text:l,""):"",a=Vd(()=>{if(Wt(i.location)){let l=i.location.documentChar||i.location.documentPage||i.location.documentChunk;if(Wt(l))return{source:jd(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:jd(l.start)?l.start:void 0,endIndex:jd(l.end)?l.end:void 0}}return{}});o.push({type:"citation",citedText:s,...a})}return o},[]):[]};continue}else if(yt(r,"document")&&Wt(r.document)){yield SPt(r);continue}else if(yt(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(yt(r,"image")&&Wt(r.image)){yield TPt(r);continue}else if(yt(r,"reasoning_content")&&Oe(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(yt(r,"text")&&Oe(r.text)){yield{type:"text",text:r.text};continue}else if(yt(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(yt(r,"tool_call"))continue;if(yt(r,"video")&&Wt(r.video)){yield IPt(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}var hFe,gFe=C(()=>{tp();hFe={translateContent:mFe,translateContentChunk:mFe}});function yFe(t){let e=[],n=t.additional_kwargs?.reasoning_content;if(Oe(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let r of t.content)typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&Oe(r.text)&&e.push({type:"text",text:r.text});for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}var wFe,vFe=C(()=>{tp();wFe={translateContent:yFe,translateContentChunk:yFe}});function xFe(t){function*e(){let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n){if(yt(r,"text")&&Oe(r.text)){yield{type:"text",text:r.text};continue}else if(yt(r,"thinking")&&Oe(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(yt(r,"inlineData")&&Wt(r.inlineData)&&Oe(r.inlineData.mimeType)&&Oe(r.inlineData.data)){yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data};continue}else if(yt(r,"functionCall")&&Wt(r.functionCall)&&Oe(r.functionCall.name)&&Wt(r.functionCall.args)){yield{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args};continue}else if(yt(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(yt(r,"fileData")&&Wt(r.fileData)&&Oe(r.fileData.mimeType)&&Oe(r.fileData.fileUri)){yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri};continue}else if(yt(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(yt(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}var bFe,CFe=C(()=>{tp();bFe={translateContent:xFe,translateContentChunk:xFe}});function _Fe(t){function*e(){let n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let r of n){if(yt(r,"reasoning")&&Oe(r.reasoning)){let o=Vd(()=>{let i=n.indexOf(r);if(js(t.additional_kwargs?.signatures)&&i>=0)return t.additional_kwargs.signatures.at(i)});Oe(o)?yield{type:"reasoning",reasoning:r.reasoning,signature:o}:yield{type:"reasoning",reasoning:r.reasoning};continue}else if(yt(r,"thinking")&&Oe(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(yt(r,"text")&&Oe(r.text)){yield{type:"text",text:r.text};continue}else if(yt(r,"image_url")){if(Oe(r.image_url))if(r.image_url.startsWith("data:")){let o=r.image_url.match(/^data:([^;]+);base64,(.+)$/);o?yield{type:"image",data:o[2],mimeType:o[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if(yt(r,"media")&&Oe(r.mimeType)&&Oe(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}var SFe,TFe=C(()=>{tp();SFe={translateContent:_Fe,translateContentChunk:_Fe}});function IFe(t){let e=[],n=t.additional_kwargs?.reasoning;if(Oe(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string"){let r=t.content,o=r.match(/<think>([\s\S]*?)<\/think>/);if(o){let i=o[1].trim();i.length>0&&e.push({type:"reasoning",reasoning:i}),r=r.replace(/<think>[\s\S]*?<\/think>/,"").trim()}r.length>0&&e.push({type:"text",text:r})}else for(let r of t.content)if(typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&Oe(r.text)){let o=r.text,i=o.match(/<think>([\s\S]*?)<\/think>/);if(i){let s=i[1].trim();s.length>0&&e.push({type:"reasoning",reasoning:s}),o=o.replace(/<think>[\s\S]*?<\/think>/,"").trim()}o.length>0&&e.push({type:"text",text:o})}for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}var PFe,EFe=C(()=>{tp();PFe={translateContent:IFe,translateContentChunk:IFe}});function AFe(t){let e=[],n=t.additional_kwargs?.reasoning_content;if(Oe(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let r of t.content)typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&Oe(r.text)&&e.push({type:"text",text:r.text});for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}var kFe,MFe=C(()=>{tp();kFe={translateContent:AFe,translateContentChunk:AFe}});function NFe(t){let e=[];if(Wt(t.additional_kwargs?.reasoning)){let r=t.additional_kwargs.reasoning;if(js(r.summary)){let o=r.summary.reduce((i,s)=>Wt(s)&&Oe(s.text)?`${i}${s.text}`:i,"");o.length>0&&e.push({type:"reasoning",reasoning:o})}}let n=t.additional_kwargs?.reasoning_content;if(Oe(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let r of t.content)typeof r=="object"&&"type"in r&&r.type==="text"&&"text"in r&&Oe(r.text)&&e.push({type:"text",text:r.text});for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}var OFe,RFe=C(()=>{tp();OFe={translateContent:NFe,translateContentChunk:NFe}});function LFe(t){function*e(){let n=Vd(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let r=t.additional_kwargs?.originalTextContentBlock;if(r?.thoughtSignature&&!t.content.some(o=>"thoughtSignature"in o)){let o=[...t.content];for(let i=o.length-1;i>=0;i--){let s=o[i];if(s.type==="text"&&!s.thought)return s.thoughtSignature=r.thoughtSignature,o}}return t.content}});for(let r of n){let o=Vd(()=>yt(r,"text")&&Oe(r.text)?{type:"text",text:r.text}:yt(r,"inlineData")&&Wt(r.inlineData)&&Oe(r.inlineData.mimeType)&&Oe(r.inlineData.data)?{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data}:yt(r,"functionCall")&&Wt(r.functionCall)&&Oe(r.functionCall.name)&&Wt(r.functionCall.args)?{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args}:yt(r,"functionResponse")?{type:"non_standard",value:r}:yt(r,"fileData")&&Wt(r.fileData)&&Oe(r.fileData.mimeType)&&Oe(r.fileData.fileUri)?{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri}:yt(r,"executableCode")?{type:"non_standard",value:r}:yt(r,"codeExecutionResult")?{type:"non_standard",value:r}:{type:"non_standard",value:r}),i=Vd(()=>"thought"in r&&r.thought?{type:"reasoning",reasoning:o.type==="text"?o.text:"",reasoningContentBlock:o}:o),s={thought:r.thought,thoughtSignature:r.thoughtSignature,partMetadata:r.partMetadata,...i};for(let a in s)s[a]===void 0&&delete s[a];yield s}}return Array.from(e())}var DFe,$Fe=C(()=>{tp();DFe={translateContent:LFe,translateContentChunk:LFe}});function Mle(t){return globalThis.lc_block_translators_registry.get(t)}var FFe=C(()=>{vle();ble();gFe();vFe();CFe();TFe();EFe();MFe();RFe();$Fe();globalThis.lc_block_translators_registry??(globalThis.lc_block_translators_registry=new Map([["anthropic",X$e],["bedrock-converse",hFe],["deepseek",wFe],["google",DFe],["google-genai",bFe],["google-vertexai",SFe],["groq",PFe],["ollama",kFe],["openai",rFe],["xai",OFe]]))});function UFe(t){let e=Symbol.for(t);return{brand(n,r){var s,a;let o=r?Symbol.for(`${t}.${r}`):e;class i extends(a=n,s=o,a){constructor(...u){super(...u);I(this,s,!0)}static isInstance(u){return typeof u=="object"&&u!==null&&o in u&&u[o]===!0}}return Object.defineProperty(i,"name",{value:n.name}),i},sub(n){return UFe(`${t}.${n}`)},isInstance(n){return typeof n=="object"&&n!==null&&e in n&&n[e]===!0}}}var BFe,zFe=C(()=>{BFe=UFe("langchain")});function Lb(t,e){return t.lc_error_code=e,t.message=`${t.message}

Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}var Nle,jFe,Ole,VFe,JT=C(()=>{$n();zFe();Nle=BFe.sub("error"),jFe=class extends Nle.brand(Error){constructor(e){super(e);I(this,"name","LangChainError");Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Ole=class extends Nle.brand(jFe,"model-abort"){constructor(e,n){super(e);I(this,"name","ModelAbortError");I(this,"partialOutput");this.partialOutput=n}},VFe=class WFe extends Nle.brand(jFe,"context-overflow"){constructor(n){super(n??"Input exceeded the model's context window.");I(this,"name","ContextOverflowError");I(this,"cause")}static fromError(n){let r=new WFe(n.message);return r.cause=n,r}}});function Db(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}function HFe(t){return!!(t&&typeof t=="object"&&"toolCall"in t&&t.toolCall!=null&&typeof t.toolCall=="object"&&"id"in t.toolCall&&typeof t.toolCall.id=="string")}var S2,L3=C(()=>{S2=class extends Error{constructor(e,n){super(e);I(this,"output");this.output=n}}});function jk(t,e=Vk){t=t.trim();let n=t.indexOf("```");if(n===-1)return e(t);let r=t.substring(n+3);r.startsWith(`json
`)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
`)&&(r=r.substring(1));let o=r.indexOf("```"),i=r;return o!==-1&&(i=r.substring(0,o)),e(i.trim())}function PPt(t){try{return JSON.parse(t)}catch{}let e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let n=0;function r(){for(;n<e.length&&/\s/.test(e[n]);)n+=1}function o(){if(e[n]!=='"')throw new Error(`Expected '"' at position ${n}, got '${e[n]}'`);n+=1;let u="",d=!1;for(;n<e.length;){let f=e[n];if(d){if(f==="n")u+=`
`;else if(f==="t")u+="	";else if(f==="r")u+="\r";else if(f==="\\")u+="\\";else if(f==='"')u+='"';else if(f==="b")u+="\b";else if(f==="f")u+="\f";else if(f==="/")u+="/";else if(f==="u"){let p=e.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(p))p.length===4?u+=String.fromCharCode(Number.parseInt(p,16)):u+=`u${p}`,n+=p.length;else throw new Error(`Invalid unicode escape sequence '\\u${p}' at position ${n}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${n}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return n+=1,u;u+=f}n+=1}return d&&(u+="\\"),u}function i(){let u=n,d="";if(e[n]==="-"&&(d+="-",n+=1),n<e.length&&e[n]==="0"&&(d+="0",n+=1,e[n]>="0"&&e[n]<="9"))throw new Error(`Invalid number at position ${u}`);if(n<e.length&&e[n]>="1"&&e[n]<="9")for(;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&e[n]===".")for(d+=".",n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&(e[n]==="e"||e[n]==="E"))for(d+=e[n],n+=1,n<e.length&&(e[n]==="+"||e[n]==="-")&&(d+=e[n],n+=1);n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(d==="-")return-0;let f=Number.parseFloat(d);if(Number.isNaN(f))throw n=u,new Error(`Invalid number '${d}' at position ${u}`);return f}function s(){if(r(),n>=e.length)throw new Error(`Unexpected end of input at position ${n}`);let u=e[n];if(u==="{")return l();if(u==="[")return a();if(u==='"')return o();if("null".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),null;if("true".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),!0;if("false".startsWith(e.substring(n,n+5)))return n+=Math.min(5,e.length-n),!1;if(u==="-"||u>="0"&&u<="9")return i();throw new Error(`Unexpected character '${u}' at position ${n}`)}function a(){if(e[n]!=="[")throw new Error(`Expected '[' at position ${n}, got '${e[n]}'`);let u=[];if(n+=1,r(),n>=e.length)return u;if(e[n]==="]")return n+=1,u;for(;n<e.length;){if(r(),n>=e.length||(u.push(s()),r(),n>=e.length))return u;if(e[n]==="]")return n+=1,u;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or ']' at position ${n}, got '${e[n]}'`)}return u}function l(){if(e[n]!=="{")throw new Error(`Expected '{' at position ${n}, got '${e[n]}'`);let u={};if(n+=1,r(),n>=e.length)return u;if(e[n]==="}")return n+=1,u;for(;n<e.length;){if(r(),n>=e.length)return u;let d=o();if(r(),n>=e.length)return u;if(e[n]!==":")throw new Error(`Expected ':' at position ${n}, got '${e[n]}'`);if(n+=1,r(),n>=e.length||(u[d]=s(),r(),n>=e.length))return u;if(e[n]==="}")return n+=1,u;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or '}' at position ${n}, got '${e[n]}'`)}return u}let c=s();if(r(),n<e.length)throw new Error(`Unexpected character '${e[n]}' at position ${n}`);return c}function Vk(t){try{return typeof t>"u"?null:PPt(t)}catch{return null}}var Wk=C(()=>{});var rc,$b,T2=C(()=>{nc();rc=class KFe extends Vs{constructor(n,r){(typeof n=="string"||Array.isArray(n))&&(n={content:n,role:r});super(n);I(this,"type","generic");I(this,"role");this.role=n.role}static lc_name(){return"ChatMessage"}static _chatMessageClass(){return KFe}static isInstance(n){return super.isInstance(n)&&n.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},$b=class extends ju{constructor(e,n){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:n});super(e);I(this,"type","generic");I(this,"role");this.role=e.role}static lc_name(){return"ChatMessageChunk"}concat(e){let n=this.constructor;return new n({content:zc(this.content,e.content),additional_kwargs:Ii(this.additional_kwargs,e.additional_kwargs),response_metadata:Ii(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}}});var Fb,D3=C(()=>{nc();Fb=class extends ju{constructor(){super(...arguments);I(this,"type","function")}static lc_name(){return"FunctionMessageChunk"}concat(e){let n=this.constructor;return new n({content:zc(this.content,e.content),additional_kwargs:Ii(this.additional_kwargs,e.additional_kwargs),response_metadata:Ii(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}});var Zo,Ub,Bb=C(()=>{nc();Zo=class extends Vs{constructor(e){super(e);I(this,"type","human")}static lc_name(){return"HumanMessage"}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},Ub=class extends ju{constructor(e){super(e);I(this,"type","human")}static lc_name(){return"HumanMessageChunk"}concat(e){let n=this.constructor;return new n({content:zc(this.content,e.content),additional_kwargs:Ii(this.additional_kwargs,e.additional_kwargs),response_metadata:Ii(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}}});var $3,F3=C(()=>{nc();$3=class extends Vs{constructor(e){super({...e,content:[]});I(this,"type","remove");I(this,"id");this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}}});var Vu,Sg,I2=C(()=>{nc();Vu=class U3 extends Vs{constructor(n){super(n);I(this,"type","system")}static lc_name(){return"SystemMessage"}concat(n){if(typeof n=="string")return new U3({content:zc(this.content,n),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(U3.isInstance(n))return new U3({content:zc(this.content,n.content),additional_kwargs:{...this.additional_kwargs,...n.additional_kwargs},response_metadata:{...this.response_metadata,...n.response_metadata},id:this.id??n.id,name:this.name??n.name});throw new Error("Unexpected chunk type for system message")}static isInstance(n){return super.isInstance(n)&&n.type==="system"}},Sg=class extends ju{constructor(e){super(e);I(this,"type","system")}static lc_name(){return"SystemMessageChunk"}concat(e){let n=this.constructor;return new n({content:zc(this.content,e.content),additional_kwargs:Ii(this.additional_kwargs,e.additional_kwargs),response_metadata:Ii(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}}});function EPt(t){return Db(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function APt(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function Rle(t){let e,n;if(APt(t)){let r=t.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?e="user":r==="AIMessage"||r==="AIMessageChunk"?e="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?e="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?e="function":r==="ToolMessage"||r==="ToolMessageChunk"?e="tool":e="unknown",n=t.kwargs}else{let{type:r,...o}=t;e=r,n=o}if(e==="human"||e==="user")return new Zo(n);if(e==="ai"||e==="assistant"){let{tool_calls:r,...o}=n;if(!Array.isArray(r))return new kn(n);let i=r.map(EPt);return new kn({...o,tool_calls:i})}else{if(e==="system")return new Vu(n);if(e==="developer")return new Vu({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in n)return new Wd({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if(e==="remove"&&"id"in n&&typeof n.id=="string")return new $3({...n,id:n.id});throw Lb(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.

Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Lm(t){if(typeof t=="string")return new Zo(t);if(np(t))return t;if(Array.isArray(t)){let[e,n]=t;return Rle({type:e,content:n})}else if(Tle(t)){let{role:e,...n}=t;return Rle({...n,type:e})}else return Rle(t)}function kPt(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}function ui(t,e="Human",n="AI"){let r=[];for(let o of t){let i;if(o.type==="human")i=e;else if(o.type==="ai")i=n;else if(o.type==="system")i="System";else if(o.type==="tool")i="Tool";else if(o.type==="generic")i=o.role;else throw new Error(`Got unsupported message type: ${o.type}`);let s=o.name?`${o.name}, `:"",a=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(kPt).filter(Boolean).join(""):"",l=`${i}: ${s}${a}`;if(o.type==="ai"){let c=o;c.tool_calls&&c.tool_calls.length>0?l+=JSON.stringify(c.tool_calls):c.additional_kwargs&&"function_call"in c.additional_kwargs&&(l+=JSON.stringify(c.additional_kwargs.function_call))}r.push(l)}return r.join(`
`)}function B3(t){let e=t._getType();if(e==="human")return new Ub({...t});if(e==="ai"){let n={...t};return"tool_calls"in n&&(n={...n,tool_call_chunks:n.tool_calls?.map(r=>({...r,type:"tool_call_chunk",index:void 0,args:JSON.stringify(r.args)}))}),new Yt({...n})}else{if(e==="system")return new Sg({...t});if(e==="function")return new Fb({...t});if(rc.isInstance(t))return new $b({...t});throw new Error("Unknown message type.")}}function Dle(t){let e=t.reduce((o,i)=>{let s=o.findIndex(([a])=>"id"in i&&i.id&&"index"in i&&i.index!==void 0?i.id===a.id&&i.index===a.index:"id"in i&&i.id?i.id===a.id:"index"in i&&i.index!==void 0?i.index===a.index:!1);return s!==-1?o[s].push(i):o.push([i]),o},[]),n=[],r=[];for(let o of e){let i=null,s=o[0]?.name??"",a=o.map(u=>u.args||"").join("").trim(),l=a.length?a:"{}",c=o[0]?.id;try{if(i=Vk(l),!c||i===null||typeof i!="object"||Array.isArray(i))throw new Error("Malformed tool call chunk args.");n.push({name:s,args:i,id:c,type:"tool_call"})}catch{r.push({name:s,args:l,id:c,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:n,invalid_tool_calls:r}}var Lle,Dm=C(()=>{JT();L3();Wk();nc();zk();Wu();T2();D3();Bb();F3();I2();Lle=t=>t()});function rp(t){return t._getType()==="ai"}function z3(t){return t._getType()==="ai"}var kn,Yt,Wu=C(()=>{nc();FFe();R3();zk();Dm();kn=class extends Vs{constructor(e){let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{n=e;let r=n.additional_kwargs?.tool_calls,o=n.tool_calls;r!=null&&r.length>0&&(o===void 0||o.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.

Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&o===void 0){let[i,s]=Ele(r);n.tool_calls=i??[],n.invalid_tool_calls=s??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}if(n.response_metadata!==void 0&&"output_version"in n.response_metadata&&n.response_metadata.output_version==="v1"&&(n.contentBlocks=n.content,n.content=void 0),n.contentBlocks!==void 0){if(n.tool_calls){let s=n.tool_calls.filter(a=>!n.contentBlocks?.some(l=>l.type==="tool_call"&&l.id===a.id&&l.name===a.name));n.contentBlocks.push(...s.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}let i=n.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!n.tool_calls?.some(a=>a.id===s.id&&a.name===s.name));i.length>0&&(n.tool_calls=[...n.tool_calls??[],...i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args}))])}}super(n);I(this,"type","ai");I(this,"tool_calls",[]);I(this,"invalid_tool_calls",[]);I(this,"usage_metadata");typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let n=Mle(this.response_metadata.model_provider);if(n)return n.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls){let n=this.tool_calls.filter(r=>!e.some(o=>o.id===r.id&&o.name===r.name));e.push(...n.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};Yt=class extends ju{constructor(e){let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)n={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{let r=Dle(e.tool_call_chunks??[]);n={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(n);I(this,"type","ai");I(this,"tool_calls",[]);I(this,"invalid_tool_calls",[]);I(this,"tool_call_chunks",[]);I(this,"usage_metadata");this.tool_call_chunks=n.tool_call_chunks??this.tool_call_chunks,this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let n=Mle(this.response_metadata.model_provider);if(n)return n.translateContent(this)}let e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){let n=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(let r of this.tool_calls)r.id&&!n.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){let n={content:zc(this.content,e.content),additional_kwargs:Ii(this.additional_kwargs,e.additional_kwargs),response_metadata:Ile(this.response_metadata,e.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){let o=ZT(this.tool_call_chunks,e.tool_call_chunks);o!==void 0&&o.length>0&&(n.tool_call_chunks=o)}if(this.tool_calls!==void 0||e.tool_calls!==void 0){let o=ZT(this.tool_calls,e.tool_calls);o!==void 0&&o.length>0&&(n.tool_calls=o)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(n.usage_metadata=_2(this.usage_metadata,e.usage_metadata));let r=this.constructor;return new r(n)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}}});var GFe,YFe=C(()=>{GFe=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function Tg(t){return typeof t=="string"&&GFe.test(t)}var Hk=C(()=>{YFe()});function XT(t,e=0){return(yl[t[e+0]]+yl[t[e+1]]+yl[t[e+2]]+yl[t[e+3]]+"-"+yl[t[e+4]]+yl[t[e+5]]+"-"+yl[t[e+6]]+yl[t[e+7]]+"-"+yl[t[e+8]]+yl[t[e+9]]+"-"+yl[t[e+10]]+yl[t[e+11]]+yl[t[e+12]]+yl[t[e+13]]+yl[t[e+14]]+yl[t[e+15]]).toLowerCase()}var yl,Kk=C(()=>{Hk();yl=[];for(let t=0;t<256;++t)yl.push((t+256).toString(16).slice(1))});function qk(){return crypto.getRandomValues(MPt)}var MPt,j3=C(()=>{MPt=new Uint8Array(16)});function op(t,e,n){let r;if(t)r=ZFe(t.random??t.rng?.()??qk(),t.msecs,t.seq,e,n);else{let o=Date.now(),i=qk();NPt($le,o,i),r=ZFe(i,$le.msecs,$le.seq,e,n)}return e??XT(r)}function NPt(t,e,n){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function ZFe(t,e,n,r,o=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),o=0;else if(o<0||o+16>r.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`);return e??(e=Date.now()),n??(n=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),r[o++]=e/1099511627776&255,r[o++]=e/4294967296&255,r[o++]=e/16777216&255,r[o++]=e/65536&255,r[o++]=e/256&255,r[o++]=e&255,r[o++]=112|n>>>28&15,r[o++]=n>>>20&255,r[o++]=128|n>>>14&63,r[o++]=n>>>6&255,r[o++]=n<<2&255|t[10]&3,r[o++]=t[11],r[o++]=t[12],r[o++]=t[13],r[o++]=t[14],r[o++]=t[15],r}var $le,P2=C(()=>{Kk();j3();$le={}});var JFe=C(()=>{});var XFe=C(()=>{});function V3(t){if(!Tg(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}var Fle=C(()=>{Hk()});var QFe=C(()=>{Kk();j3()});function Ule(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():OPt(t,e,n)}function OPt(t,e,n){t=t||{};let r=t.random??t.rng?.()??qk();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return XT(r)}var Ble=C(()=>{Kk();j3()});function RPt(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function zle(t,e){return t<<e|t>>>32-e}function e2e(t){let e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(t.length+1);r.set(t),r[t.length]=128,t=r;let o=t.length/4+2,i=Math.ceil(o/16),s=new Array(i);for(let a=0;a<i;++a){let l=new Uint32Array(16);for(let c=0;c<16;++c)l[c]=t[a*64+c*4]<<24|t[a*64+c*4+1]<<16|t[a*64+c*4+2]<<8|t[a*64+c*4+3];s[a]=l}s[i-1][14]=(t.length-1)*8/2**32,s[i-1][14]=Math.floor(s[i-1][14]),s[i-1][15]=(t.length-1)*8&4294967295;for(let a=0;a<i;++a){let l=new Uint32Array(80);for(let m=0;m<16;++m)l[m]=s[a][m];for(let m=16;m<80;++m)l[m]=zle(l[m-3]^l[m-8]^l[m-14]^l[m-16],1);let c=n[0],u=n[1],d=n[2],f=n[3],p=n[4];for(let m=0;m<80;++m){let h=Math.floor(m/20),g=zle(c,5)+RPt(h,u,d,f)+p+e[h]+l[m]>>>0;p=f,f=d,d=zle(u,30)>>>0,u=c,c=g}n[0]=n[0]+c>>>0,n[1]=n[1]+u>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+f>>>0,n[4]=n[4]+p>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}var t2e=C(()=>{});function LPt(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e[n]=t.charCodeAt(n);return e}function o2e(t,e,n,r,o,i){let s=typeof n=="string"?LPt(n):n,a=typeof r=="string"?V3(r):r;if(typeof r=="string"&&(r=V3(r)),r?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+s.length);if(l.set(a),l.set(s,a.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,o){if(i??(i=0),i<0||i+16>o.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let c=0;c<16;++c)o[i+c]=l[c];return o}return XT(l)}var n2e,r2e,i2e=C(()=>{Fle();Kk();n2e="6ba7b810-9dad-11d1-80b4-00c04fd430c8",r2e="6ba7b811-9dad-11d1-80b4-00c04fd430c8"});function jle(t,e,n,r){return o2e(80,e2e,t,e,n,r)}var s2e=C(()=>{t2e();i2e();jle.DNS=n2e;jle.URL=r2e});var a2e=C(()=>{Hk()});var E2=C(()=>{$n();JFe();XFe();Hk();Fle();Kk();QFe();Ble();s2e();P2();a2e()});var l2e,QT,c2e,zb,A2=C(()=>{l2e=Symbol.for("ls:tracing_async_local_storage"),QT=Symbol.for("lc:context_variables"),c2e=t=>{globalThis[l2e]=t},zb=()=>globalThis[l2e]});function u2e(){return Vle===void 0&&(Vle={library:"langchain-js",runtime:Hle()}),Vle}function In(t){try{return typeof process<"u"?process.env?.[t]:Wle()?Deno?.env.get(t):void 0}catch{return}}var DPt,$Pt,FPt,Wle,UPt,Hle,Vle,Jo=C(()=>{$n();DPt=()=>typeof window<"u"&&typeof window.document<"u",$Pt=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",FPt=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Wle=()=>typeof Deno<"u",UPt=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Wle(),Hle=()=>{let t;return DPt()?t="browser":UPt()?t="node":$Pt()?t="webworker":FPt()?t="jsdom":Wle()?t="deno":t="other",t}});function Kle(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}function d2e(t){return"lc_prefer_chat_model_stream_events"in t&&t.lc_prefer_chat_model_stream_events}var BPt,Gk,f2e,k2=C(()=>{$n();Rb();P2();E2();Jo();BPt=class{};Gk=class extends BPt{constructor(e){super();I(this,"lc_serializable",!1);I(this,"lc_kwargs");I(this,"ignoreLLM",!1);I(this,"ignoreChain",!1);I(this,"ignoreAgent",!1);I(this,"ignoreRetriever",!1);I(this,"ignoreCustomEvent",!1);I(this,"raiseError",!1);I(this,"awaitHandlers",In("LANGCHAIN_CALLBACKS_BACKGROUND")==="false");this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,yle(this.constructor)]}copy(){return new this.constructor(this)}toJSON(){return zu.prototype.toJSON.call(this)}toJSONNotImplemented(){return zu.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class n extends Gk{constructor(){super();I(this,"name",op());Object.assign(this,e)}}return new n}},f2e=t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"}});var p2e,m2e=C(()=>{p2e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i});function zPt(t){return typeof t=="string"&&p2e.test(t)}var h2e,g2e=C(()=>{m2e();h2e=zPt});function jPt(t){if(!h2e(t))throw TypeError("Invalid UUID");var e,n=new Uint8Array(16);return n[0]=(e=parseInt(t.slice(0,8),16))>>>24,n[1]=e>>>16&255,n[2]=e>>>8&255,n[3]=e&255,n[4]=(e=parseInt(t.slice(9,13),16))>>>8,n[5]=e&255,n[6]=(e=parseInt(t.slice(14,18),16))>>>8,n[7]=e&255,n[8]=(e=parseInt(t.slice(19,23),16))>>>8,n[9]=e&255,n[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,n[11]=e/4294967296&255,n[12]=e>>>24&255,n[13]=e>>>16&255,n[14]=e>>>8&255,n[15]=e&255,n}var y2e,w2e=C(()=>{g2e();y2e=jPt});function Yk(t,e=0){return(wl[t[e+0]]+wl[t[e+1]]+wl[t[e+2]]+wl[t[e+3]]+"-"+wl[t[e+4]]+wl[t[e+5]]+"-"+wl[t[e+6]]+wl[t[e+7]]+"-"+wl[t[e+8]]+wl[t[e+9]]+"-"+wl[t[e+10]]+wl[t[e+11]]+wl[t[e+12]]+wl[t[e+13]]+wl[t[e+14]]+wl[t[e+15]]).toLowerCase()}var wl,W3,H3=C(()=>{wl=[];for(W3=0;W3<256;++W3)wl.push((W3+256).toString(16).slice(1))});function M2(){if(!K3&&(K3=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!K3))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return K3(VPt)}var K3,VPt,qle=C(()=>{VPt=new Uint8Array(16)});function WPt(t){t=unescape(encodeURIComponent(t));for(var e=[],n=0;n<t.length;++n)e.push(t.charCodeAt(n));return e}function Gle(t,e,n){function r(o,i,s,a){var l;if(typeof o=="string"&&(o=WPt(o)),typeof i=="string"&&(i=y2e(i)),((l=i)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var c=new Uint8Array(16+o.length);if(c.set(i),c.set(o,i.length),c=n(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,s){a=a||0;for(var u=0;u<16;++u)s[a+u]=c[u];return s}return Yk(c)}try{r.name=t}catch{}return r.DNS=HPt,r.URL=KPt,r}var HPt,KPt,v2e=C(()=>{H3();w2e();HPt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",KPt="6ba7b811-9dad-11d1-80b4-00c04fd430c8"});var qPt,Yle,x2e=C(()=>{qPt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Yle={randomUUID:qPt}});function GPt(t,e,n){if(Yle.randomUUID&&!e&&!t)return Yle.randomUUID();t=t||{};var r=t.random||(t.rng||M2)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){n=n||0;for(var o=0;o<16;++o)e[n+o]=r[o];return e}return Yk(r)}var eI,b2e=C(()=>{x2e();qle();H3();eI=GPt});function YPt(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function Zle(t,e){return t<<e|t>>>32-e}function ZPt(t){var e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof t=="string"){var r=unescape(encodeURIComponent(t));t=[];for(var o=0;o<r.length;++o)t.push(r.charCodeAt(o))}else Array.isArray(t)||(t=Array.prototype.slice.call(t));t.push(128);for(var i=t.length/4+2,s=Math.ceil(i/16),a=new Array(s),l=0;l<s;++l){for(var c=new Uint32Array(16),u=0;u<16;++u)c[u]=t[l*64+u*4]<<24|t[l*64+u*4+1]<<16|t[l*64+u*4+2]<<8|t[l*64+u*4+3];a[l]=c}a[s-1][14]=(t.length-1)*8/Math.pow(2,32),a[s-1][14]=Math.floor(a[s-1][14]),a[s-1][15]=(t.length-1)*8&4294967295;for(var d=0;d<s;++d){for(var f=new Uint32Array(80),p=0;p<16;++p)f[p]=a[d][p];for(var m=16;m<80;++m)f[m]=Zle(f[m-3]^f[m-8]^f[m-14]^f[m-16],1);for(var h=n[0],g=n[1],y=n[2],w=n[3],v=n[4],x=0;x<80;++x){var b=Math.floor(x/20),_=Zle(h,5)+YPt(b,g,y,w)+v+e[b]+f[x]>>>0;v=w,w=y,y=Zle(g,30)>>>0,g=h,h=_}n[0]=n[0]+h>>>0,n[1]=n[1]+g>>>0,n[2]=n[2]+y>>>0,n[3]=n[3]+w>>>0,n[4]=n[4]+v>>>0}return[n[0]>>24&255,n[0]>>16&255,n[0]>>8&255,n[0]&255,n[1]>>24&255,n[1]>>16&255,n[1]>>8&255,n[1]&255,n[2]>>24&255,n[2]>>16&255,n[2]>>8&255,n[2]&255,n[3]>>24&255,n[3]>>16&255,n[3]>>8&255,n[3]&255,n[4]>>24&255,n[4]>>16&255,n[4]>>8&255,n[4]&255]}var C2e,_2e=C(()=>{C2e=ZPt});var JPt,Jle,S2e=C(()=>{v2e();_2e();JPt=Gle("v5",80,C2e),Jle=JPt});function XPt(t,e,n){t=t||{};var r=e&&n||0,o=e||new Uint8Array(16),i=t.random||(t.rng||M2)(),s=t.msecs!==void 0?t.msecs:Date.now(),a=t.seq!==void 0?t.seq:null,l=I2e,c=T2e;return s>$m&&t.msecs===void 0&&($m=s,a!==null&&(l=null,c=null)),a!==null&&(a>2147483647&&(a=2147483647),l=a>>>19&4095,c=a&524287),(l===null||c===null)&&(l=i[6]&127,l=l<<8|i[7],c=i[8]&63,c=c<<8|i[9],c=c<<5|i[10]>>>3),s+1e4>$m&&a===null?++c>524287&&(c=0,++l>4095&&(l=0,$m++)):$m=s,I2e=l,T2e=c,o[r++]=$m/1099511627776&255,o[r++]=$m/4294967296&255,o[r++]=$m/16777216&255,o[r++]=$m/65536&255,o[r++]=$m/256&255,o[r++]=$m&255,o[r++]=l>>>4&15|112,o[r++]=l&255,o[r++]=c>>>13&63|128,o[r++]=c>>>5&255,o[r++]=c<<3&255|i[10]&7,o[r++]=i[11],o[r++]=i[12],o[r++]=i[13],o[r++]=i[14],o[r++]=i[15],e||Yk(o)}var T2e,I2e,$m,Xle,P2e=C(()=>{qle();H3();T2e=null,I2e=null,$m=0;Xle=XPt});var q3=C(()=>{b2e();S2e();P2e()});var E2e,A2e,Qle,k2e,ece,tce,nce,M2e,N2e,O2e,R2e,L2e,D2e,$2e,F2e,U2e,B2e,z2e,j2e,V2e,W2e,H2e,K2e,q2e,G2e,Y2e,Z2e,J2e,X2e,Q2e,rce,eUe,tUe,nUe=C(()=>{E2e="gen_ai.operation.name",A2e="gen_ai.system",Qle="gen_ai.request.model",k2e="gen_ai.response.model",ece="gen_ai.usage.input_tokens",tce="gen_ai.usage.output_tokens",nce="gen_ai.usage.total_tokens",M2e="gen_ai.request.max_tokens",N2e="gen_ai.request.temperature",O2e="gen_ai.request.top_p",R2e="gen_ai.request.frequency_penalty",L2e="gen_ai.request.presence_penalty",D2e="gen_ai.response.finish_reasons",$2e="gen_ai.prompt",F2e="gen_ai.completion",U2e="gen_ai.request.extra_query",B2e="gen_ai.request.extra_body",z2e="gen_ai.serialized.name",j2e="gen_ai.serialized.signature",V2e="gen_ai.serialized.doc",W2e="gen_ai.response.id",H2e="gen_ai.response.service_tier",K2e="gen_ai.response.system_fingerprint",q2e="gen_ai.usage.input_token_details",G2e="gen_ai.usage.output_token_details",Y2e="langsmith.trace.session_id",Z2e="langsmith.trace.session_name",J2e="langsmith.span.kind",X2e="langsmith.trace.name",Q2e="langsmith.metadata",rce="langsmith.span.tags",eUe="langsmith.request.streaming",tUe="langsmith.request.headers"});var tEt,nEt,rUe,oUe,iUe,oce=C(()=>{Mw();tEt=(...t)=>fetch(...t),rUe=Symbol.for("ls:fetch_implementation"),oUe=()=>globalThis[rUe]===void 0?!0:nEt??!1,iUe=t=>async(...e)=>{if(t||rs("DEBUG")==="true"){let[r,o]=e;console.log(`\u2192 ${o?.method||"GET"} ${r}`)}let n=await(globalThis[rUe]??tEt)(...e);return(t||rs("DEBUG")==="true")&&console.log(`\u2190 ${n.status} ${n.statusText} ${n.url}`),n}});var N2,ice=C(()=>{Mw();N2=()=>rs("PROJECT")??Hd("LANGCHAIN_SESSION")??"default"});function tI(t){sUe[t]||(console.warn(t),sUe[t]=!0)}var sUe,G3=C(()=>{sUe={}});function aEt(t){let e=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)e[n/2]=parseInt(t.substring(n,n+2),16);return e}function $o(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}function Xo(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}function Zk(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}function sce(t,e=0){return t[e]}function fEt(t,e){return(t<<e|t>>Re(32)-e)&X3}function mUe(t,e,n){for(let r=0;r<pUe;r++){let o=Xo(e,r*8),i=o^Xo(n,r*8);t[r^1]+=o,t[r]+=dEt(i,i>>Re(32))}return t}function aUe(t,e,n,r){for(let o=0;o<r;o++)mUe(t,$o(e,o*Nw),$o(n,o*8));return t}function pEt(t,e){for(let n=0;n<pUe;n++){let r=Xo(e,n*8),o=t[n];o=ace(o,Re(47)),o^=r,o*=uUe,t[n]=o&nr}return t}function Z3(t,e){return hUe(t[0]^Xo(e,0),t[1]^Xo(e,lEt))}function lUe(t,e,n){let r=n;return r+=Z3(t.slice(0),$o(e,0*Y3)),r+=Z3(t.slice(2),$o(e,4*Y3)),r+=Z3(t.slice(4),$o(e,8*Y3)),r+=Z3(t.slice(6),$o(e,12*Y3)),Pg(r&nr)}function mEt(t,e,n,r,o){let i=Math.floor((n.byteLength-Nw)/8),s=Nw*i,a=Math.floor((e.byteLength-1)/s);for(let l=0;l<a;l++)t=aUe(t,$o(e,l*s),n,i),t=o(t,$o(n,n.byteLength-Nw));{let l=Math.floor((e.byteLength-1-s*a)/Nw);t=aUe(t,$o(e,a*s),n,l),t=r(t,$o(e,e.byteLength-Nw),$o(n,n.byteLength-Nw-7))}return t}function hEt(t,e,n){let r=new BigUint64Array([rEt,jb,nI,fUe,cce,dUe,oEt,uUe]);Xk(t.length>128),r=mEt(r,t,e,mUe,pEt),Xk(r.length*8==64);{let o=lUe(r,$o(e,11),Re(t.byteLength)*jb&nr);return lUe(r,$o(e,e.byteLength-Nw-11),~(Re(t.byteLength)*nI)&nr)<<Re(64)|o}}function hUe(t,e){let n=t*e&Jk;return n&nr^n>>Re(64)}function cUe(t,e,n){return hUe((Xo(t,0)^Xo(e,0)+n)&nr,(Xo(t,8)^Xo(e,8)-n)&nr)}function J3(t,e,n,r,o){let i=t&nr,s=t>>Re(64)&nr;return i+=cUe(e,r,o),i^=Xo(n,0)+Xo(n,8),i&=nr,s+=cUe(n,$o(r,16),o),s^=Xo(e,0)+Xo(e,8),s&=nr,s<<Re(64)|i}function Pg(t){return t^=t>>Re(37),t*=iEt,t&=nr,t^=t>>Re(32),t}function Q3(t){return t^=t>>Re(33),t*=nI,t&=nr,t^=t>>Re(29),t*=fUe,t&=nr,t^=t>>Re(32),t}function gEt(t,e,n){let r=t.byteLength;Xk(r>0&&r<=3);let o=Re(sce(t,r-1))|Re(r<<8)|Re(sce(t,0)<<16)|Re(sce(t,r>>1)<<24),i=(Re(Zk(e,0))^Re(Zk(e,4)))+n,s=(o^i)&nr,a=(Re(Zk(e,8))^Re(Zk(e,12)))-n,l=(fEt(uEt(o),Re(13))^a)&nr;return(Q3(l)&nr)<<Re(64)|Q3(s)}function ace(t,e){return t^t>>e}function yEt(t,e,n){let r=t.byteLength;Xk(r>=4&&r<=8);{let o=Zk(t,0),i=Zk(t,r-4),s=Re(o)|Re(i)<<Re(32),a=(Xo(e,16)^Xo(e,24))+n&nr,c=(s^a)*(jb+(Re(r)<<Re(2)))&Jk;return c+=(c&nr)<<Re(65),c&=Jk,c^=c>>Re(67),ace(ace(c&nr,Re(35))*sEt&nr,Re(28))|Pg(c>>Re(64))<<Re(64)}}function wEt(t,e,n){let r=t.byteLength;Xk(r>=9&&r<=16);{let o=(Xo(e,32)^Xo(e,40))+n&nr,i=(Xo(e,48)^Xo(e,56))-n&nr,s=Xo(t),a=Xo(t,r-8),l=(s^a^o)*jb,c=(l&nr)+(Re(r-1)<<Re(54));l=l&(Jk^nr)|c,a^=i,l+=a+(a&X3)*(dUe-Re(1))<<Re(64),l&=Jk,l^=cEt(l>>Re(64));let u=(l&nr)*nI;return u+=(l>>Re(64))*nI<<Re(64),u&=Jk,Pg(u&nr)|Pg(u>>Re(64))<<Re(64)}}function vEt(t,e){let n=t.byteLength;return Xk(n<=16),n>8?wEt(t,Ig,e):n>=4?yEt(t,Ig,e):n>0?gEt(t,Ig,e):Q3(e^Xo(Ig,64)^Xo(Ig,72))|Q3(e^Xo(Ig,80)^Xo(Ig,88))<<Re(64)}function lce(t){return~t+Re(1)&nr}function xEt(t,e,n){let r=Re(t.byteLength)*jb&nr,o=Re(t.byteLength-1)/Re(32);for(;o>=0;){let a=Number(o);r=J3(r,$o(t,16*a),$o(t,t.byteLength-16*(a+1)),$o(e,32*a),n),o--}let i=r+(r>>Re(64))&nr;i=Pg(i);let s=(r&nr)*jb+(r>>Re(64))*cce+(Re(t.byteLength)-n&nr)*nI;return s&=nr,s=lce(Pg(s)),i|s<<Re(64)}function bEt(t,e,n){let r=Re(t.byteLength)*jb&nr;for(let s=32;s<160;s+=32)r=J3(r,$o(t,s-32),$o(t,s-16),$o(e,s-32),n);r=Pg(r&nr)|Pg(r>>Re(64))<<Re(64);for(let s=160;s<=t.byteLength;s+=32)r=J3(r,$o(t,s-32),$o(t,s-16),$o(e,3+s-160),n);r=J3(r,$o(t,t.byteLength-16),$o(t,t.byteLength-32),$o(e,103),lce(n));let o=r+(r>>Re(64))&nr;o=Pg(o);let i=(r&nr)*jb+(r>>Re(64))*cce+(Re(t.byteLength)-n&nr)*nI;return i&=nr,i=lce(Pg(i)),o|i<<Re(64)}function gUe(t,e=Re(0)){let n=t.byteLength;return n<=16?vEt(t,e):n<=128?xEt(t,Ig,e):n<=240?bEt(t,Ig,e):hEt(t,Ig,e)}function yUe(t){let e=new Uint8Array(16),n=new DataView(e.buffer),r=t&nr,o=t>>Re(64);return n.setBigUint64(0,o,!1),n.setBigUint64(8,r,!1),e}var Re,uUe,dUe,rEt,jb,nI,fUe,cce,oEt,iEt,sEt,Ig,Jk,nr,X3,Nw,pUe,lEt,Y3,cEt,uEt,dEt,Xk,wUe=C(()=>{Re=t=>BigInt(t),uUe=Re("0x9E3779B1"),dUe=Re("0x85EBCA77"),rEt=Re("0xC2B2AE3D"),jb=Re("0x9E3779B185EBCA87"),nI=Re("0xC2B2AE3D27D4EB4F"),fUe=Re("0x165667B19E3779F9"),cce=Re("0x85EBCA77C2B2AE63"),oEt=Re("0x27D4EB2F165667C5"),iEt=Re("0x165667919E3779F9"),sEt=Re("0x9FB21C651E98DF25");Ig=aEt("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Jk=(Re(1)<<Re(128))-Re(1),nr=(Re(1)<<Re(64))-Re(1),X3=(Re(1)<<Re(32))-Re(1),Nw=64,pUe=Nw/8,lEt=8,Y3=4;cEt=t=>(t&Re(255))<<Re(56)|(t&Re(65280))<<Re(40)|(t&Re(16711680))<<Re(24)|(t&Re(4278190080))<<Re(8)|(t&Re(0xff00000000))>>Re(8)|(t&Re(0xff0000000000))>>Re(24)|(t&Re(0xff000000000000))>>Re(40)|(t&Re(0xff00000000000000))>>Re(56),uEt=t=>(t=(t&Re(65535))<<Re(16)|(t&Re(4294901760))>>Re(16),t=(t&Re(16711935))<<Re(8)|(t&Re(4278255360))>>Re(8),t),dEt=(t,e)=>(t&X3)*(e&X3)&nr,Xk=t=>{if(!t)throw new Error("Assert failed")}});function qn(t,e){if(!vUe.test(t)){let n=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(n)}return t}function eK(t){let e=typeof t=="string"?Date.parse(t):t;return Xle({msecs:e,seq:0})}function CEt(t){if(!vUe.test(t))return null;let e=t[14];return parseInt(e,16)}function _Et(t){let e=t.replace(/-/g,""),n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(e.slice(r*2,r*2+2),16);return n}function SEt(t){let e=Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function IEt(t){let e=TEt.encode(t),n=gUe(e);return yUe(n)}function O2(t,e){let n=`${t}:${e}`,r=IEt(n),o=new Uint8Array(16);if(CEt(t)===7){let s=_Et(t);o.set(s.slice(0,6),0)}else{let s=Date.now();o[0]=s/1099511627776&255,o[1]=s/4294967296&255,o[2]=s/16777216&255,o[3]=s/65536&255,o[4]=s/256&255,o[5]=s&255}return o[6]=112|r[0]&15,o[7]=r[1],o[8]=128|r[2]&63,o.set(r.slice(3,10),9),SEt(o)}var vUe,TEt,tK=C(()=>{q3();G3();wUe();vUe=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;TEt=new TextEncoder});var xUe=C(()=>{tK()});function bUe(t,e){throw new Error("dump() is not supported in browser environments.")}function CUe(t){throw new Error("load() is not supported in browser environments.")}var _Ue=C(()=>{});function PEt(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}var nK,rK,uce=C(()=>{_Ue();nK=class{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,n){if(this.maxSize===0)return;let r=this.cache.get(e);if(!r){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...r,refreshFunc:n}),this._metrics.hits+=1,r.value}set(e,n,r){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}let o={value:n,createdAt:Date.now(),refreshFunc:r};this.cache.delete(e),this.cache.set(e,o)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let n={};for(let[r,o]of this.cache.entries())n[r]=o.value;bUe(e,n)}load(e){let n=CUe(e);if(!n)return 0;let r=0,o=Date.now();for(let[i,s]of Object.entries(n)){if(this.cache.size>=this.maxSize)break;let a={value:s,createdAt:o};this.cache.set(i,a),r+=1}return r}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[n,r]of this.cache.entries())PEt(r,this.ttlSeconds)&&e.push([n,r]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[n,r]of e)if(r.refreshFunc!==void 0)try{let o=await r.refreshFunc();this.set(n,o,r.refreshFunc),this._metrics.refreshes+=1}catch(o){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${n}:`,o)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??5*60}},rK=new nK});var oK,iK=C(()=>{dce();fce();oce();ice();xUe();uce();oK="0.5.4"});function sK(){if(pce===void 0){let t=hce(),e=OEt();pce={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:oK,...e}}return pce}function gce(){let t=NEt(),e={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[r,o]of Object.entries(t))typeof o=="string"&&!n.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=o:e[r]=o);return e}function NEt(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,n]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&n!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof n=="string"?t[e]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):t[e]=n)}catch{}return t}function Hd(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}function rs(t){return Hd(`LANGSMITH_${t}`)||Hd(`LANGCHAIN_${t}`)}function OEt(){if(mce!==void 0)return mce;let t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(let n of t){let r=Hd(n);r!==void 0&&(e[n]=r)}return mce=e,e}function aK(){return Hd("OTEL_ENABLED")==="true"||rs("OTEL_ENABLED")==="true"}var Eg,EEt,AEt,kEt,SUe,MEt,hce,pce,mce,Mw=C(()=>{iK();EEt=()=>typeof window<"u"&&typeof window.document<"u",AEt=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",kEt=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),SUe=()=>typeof Deno<"u",MEt=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!SUe(),hce=()=>Eg||(typeof Bun<"u"?Eg="bun":EEt()?Eg="browser":MEt()?Eg="node":AEt()?Eg="webworker":kEt()?Eg="jsdom":SUe()?Eg="deno":Eg="other",Eg)});function lK(){return _ce.getTraceInstance()}function IUe(){return _ce.getContextInstance()}function PUe(){return _ce.getDefaultOTLPTracerComponents()}var vce,xce,bce,yce,wce,TUe,REt,LEt,Cce,_ce,Sce=C(()=>{Mw();vce=class{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...n){!this.hasWarned&&aK()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(n.length===1&&typeof n[0]=="function"?r=n[0]:n.length===2&&typeof n[1]=="function"?r=n[1]:n.length===3&&typeof n[2]=="function"&&(r=n[2]),typeof r=="function")return r()}},xce=class{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new vce})}getTracer(e,n){return this.mockTracer}getActiveSpan(){}setSpan(e,n){return e}getSpan(e){}setSpanContext(e,n){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},bce=class{active(){return{}}with(e,n){return n()}},yce=Symbol.for("ls:otel_trace"),wce=Symbol.for("ls:otel_context"),TUe=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),REt=new xce,LEt=new bce,Cce=class{getTraceInstance(){return globalThis[yce]??REt}getContextInstance(){return globalThis[wce]??LEt}initializeGlobalInstances(e){globalThis[yce]===void 0&&(globalThis[yce]=e.trace),globalThis[wce]===void 0&&(globalThis[wce]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[TUe]=e}getDefaultOTLPTracerComponents(){return globalThis[TUe]??void 0}},_ce=new Cce});function $Et(t){return DEt[t]||t}var DEt,cK,EUe=C(()=>{nUe();Sce();DEt={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};cK=class{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,n){for(let r of e)try{if(!r.run)continue;if(r.operation==="post"){let o=this.createSpanForRun(r,r.run,n.get(r.id));o&&!r.run.end_time&&this.spans.set(r.id,o)}else this.updateSpanForRun(r,r.run)}catch(o){console.error(`Error processing operation ${r.id}:`,o)}}createSpanForRun(e,n,r){let o=r&&lK().getSpan(r);if(o)try{return this.finishSpanSetup(o,n,e)}catch(i){console.error(`Failed to create span for run ${e.id}:`,i);return}}finishSpanSetup(e,n,r){return this.setSpanAttributes(e,n,r),n.error?(e.setStatus({code:2}),e.recordException(new Error(n.error))):e.setStatus({code:1}),n.end_time&&e.end(new Date(n.end_time)),e}updateSpanForRun(e,n){try{let r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,n,e),n.error?(r.setStatus({code:2}),r.recordException(new Error(n.error))):r.setStatus({code:1});let o=n.end_time;o&&(r.end(new Date(o)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){if(e.extra?.metadata){let n=e.extra.metadata;if(n.ls_model_name)return n.ls_model_name;if(n.invocation_params){let r=n.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(e,n,r){if("run_type"in n&&n.run_type){e.setAttribute(J2e,n.run_type);let a=$Et(n.run_type||"chain");e.setAttribute(E2e,a)}"name"in n&&n.name&&e.setAttribute(X2e,n.name),"session_id"in n&&n.session_id&&e.setAttribute(Y2e,n.session_id),"session_name"in n&&n.session_name&&e.setAttribute(Z2e,n.session_name),this.setGenAiSystem(e,n);let o=this.extractModelName(n);o&&e.setAttribute(Qle,o),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&e.setAttribute(ece,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&e.setAttribute(tce,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&e.setAttribute(nce,n.total_tokens),this.setInvocationParameters(e,n);let i=n.extra?.metadata||{};for(let[a,l]of Object.entries(i))l!=null&&e.setAttribute(`${Q2e}.${a}`,String(l));let s=n.tags;if(s&&Array.isArray(s)?e.setAttribute(rce,s.join(", ")):s&&e.setAttribute(rce,String(s)),"serialized"in n&&typeof n.serialized=="object"){let a=n.serialized;a.name&&e.setAttribute(z2e,String(a.name)),a.signature&&e.setAttribute(j2e,String(a.signature)),a.doc&&e.setAttribute(V2e,String(a.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,n){let r="langchain",o=this.extractModelName(n);if(o){let i=o.toLowerCase();i.includes("anthropic")||i.startsWith("claude")?r="anthropic":i.includes("bedrock")?r="aws.bedrock":i.includes("azure")&&i.includes("openai")?r="az.ai.openai":i.includes("azure")&&i.includes("inference")?r="az.ai.inference":i.includes("cohere")?r="cohere":i.includes("deepseek")?r="deepseek":i.includes("gemini")?r="gemini":i.includes("groq")?r="groq":i.includes("watson")||i.includes("ibm")?r="ibm.watsonx.ai":i.includes("mistral")?r="mistral_ai":i.includes("gpt")||i.includes("openai")?r="openai":i.includes("perplexity")||i.includes("sonar")?r="perplexity":i.includes("vertex")?r="vertex_ai":(i.includes("xai")||i.includes("grok"))&&(r="xai")}e.setAttribute(A2e,r)}setInvocationParameters(e,n){if(!n.extra?.metadata?.invocation_params)return;let r=n.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(M2e,r.max_tokens),r.temperature!==void 0&&e.setAttribute(N2e,r.temperature),r.top_p!==void 0&&e.setAttribute(O2e,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(R2e,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(L2e,r.presence_penalty)}setIOAttributes(e,n){if(n.run.inputs)try{let r=n.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(Qle,r.model),r.stream!==void 0&&e.setAttribute(eUe,r.stream),r.extra_headers&&e.setAttribute(tUe,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(U2e,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(B2e,JSON.stringify(r.extra_body))),e.setAttribute($2e,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${n.id}`,r)}if(n.run.outputs)try{let r=n.run.outputs,o=this.getUnifiedRunTokens(r);if(o&&(e.setAttribute(ece,o[0]),e.setAttribute(tce,o[1]),e.setAttribute(nce,o[0]+o[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(k2e,String(r.model)),r.id&&e.setAttribute(W2e,r.id),r.choices&&Array.isArray(r.choices)){let i=r.choices.map(s=>s.finish_reason).filter(s=>s).map(String);i.length>0&&e.setAttribute(D2e,i.join(", "))}if(r.service_tier&&e.setAttribute(H2e,r.service_tier),r.system_fingerprint&&e.setAttribute(K2e,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){let i=r.usage_metadata;i.input_token_details&&e.setAttribute(q2e,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(G2e,JSON.stringify(i.output_token_details))}}e.setAttribute(F2e,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${n.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let n=this.extractUnifiedRunTokens(e.usage_metadata);if(n)return n;let r=Object.keys(e);for(let s of r){let a=e[s];if(!(!a||typeof a!="object")&&(n=this.extractUnifiedRunTokens(a.usage_metadata),n||a.lc===1&&a.kwargs&&typeof a.kwargs=="object"&&(n=this.extractUnifiedRunTokens(a.kwargs.usage_metadata),n)))return n}let o=e.generations||[];if(!Array.isArray(o))return null;let i=Array.isArray(o[0])?o.flat():o;for(let s of i)if(typeof s=="object"&&s.message&&typeof s.message=="object"&&s.message.kwargs&&typeof s.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(s.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}});function Tce(t){if(!(t&&UEt(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:n,stack:r}=t;return n==="Load failed"?r===void 0||"__sentry_captured__"in t:n.startsWith("error sending request for url")?!0:BEt.has(n)}var FEt,UEt,BEt,AUe=C(()=>{FEt=Object.prototype.toString,UEt=t=>FEt.call(t)==="[object Error]",BEt=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"])});function zEt(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function uK(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be \u2265 ${n}.`)}}function jEt(t,e){let n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1,o=Math.round(r*e.minTimeout*e.factor**(n-1));return o=Math.min(o,e.maxTimeout),o}function kUe(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function VEt({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:o}){let i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof Ice)throw i.originalError;let s=Number.isFinite(o.retries)?Math.max(0,o.retries-n):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:i,attemptNumber:e,retriesLeft:s,retriesConsumed:n});if(await o.onFailedAttempt(l),kUe(r,a)<=0)throw i;let c=await o.shouldConsumeRetry(l),u=kUe(r,a);if(u<=0||s<=0)throw i;if(i instanceof TypeError&&!Tce(i)){if(c)throw i;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(l))throw i;if(!c)return o.signal?.throwIfAborted(),!1;let d=jEt(n,o),f=Math.min(d,u);return f>0&&await new Promise((p,m)=>{let h=()=>{clearTimeout(g),o.signal?.removeEventListener("abort",h),m(o.signal.reason)},g=setTimeout(()=>{o.signal?.removeEventListener("abort",h),p()},f);o.unref&&g.unref?.(),o.signal?.addEventListener("abort",h,{once:!0})}),o.signal?.throwIfAborted(),!0}async function Pce(t,e={}){if(e={...e},zEt(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),uK("factor",e.factor,{min:0,allowInfinity:!1}),uK("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),uK("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),uK("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let n=0,r=0,o=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{e.signal?.throwIfAborted();let i=await t(n);return e.signal?.throwIfAborted(),i}catch(i){await VEt({error:i,attemptNumber:n,retriesConsumed:r,startTime:o,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var Ice,MUe=C(()=>{AUe();Ice=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}});var Ace=Tt((uSn,Ece)=>{"use strict";var WEt=Object.prototype.hasOwnProperty,jc="~";function R2(){}Object.create&&(R2.prototype=Object.create(null),new R2().__proto__||(jc=!1));function HEt(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function NUe(t,e,n,r,o){if(typeof n!="function")throw new TypeError("The listener must be a function");var i=new HEt(n,r||t,o),s=jc?jc+e:e;return t._events[s]?t._events[s].fn?t._events[s]=[t._events[s],i]:t._events[s].push(i):(t._events[s]=i,t._eventsCount++),t}function dK(t,e){--t._eventsCount===0?t._events=new R2:delete t._events[e]}function oc(){this._events=new R2,this._eventsCount=0}oc.prototype.eventNames=function(){var e=[],n,r;if(this._eventsCount===0)return e;for(r in n=this._events)WEt.call(n,r)&&e.push(jc?r.slice(1):r);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(n)):e};oc.prototype.listeners=function(e){var n=jc?jc+e:e,r=this._events[n];if(!r)return[];if(r.fn)return[r.fn];for(var o=0,i=r.length,s=new Array(i);o<i;o++)s[o]=r[o].fn;return s};oc.prototype.listenerCount=function(e){var n=jc?jc+e:e,r=this._events[n];return r?r.fn?1:r.length:0};oc.prototype.emit=function(e,n,r,o,i,s){var a=jc?jc+e:e;if(!this._events[a])return!1;var l=this._events[a],c=arguments.length,u,d;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),c){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,n),!0;case 3:return l.fn.call(l.context,n,r),!0;case 4:return l.fn.call(l.context,n,r,o),!0;case 5:return l.fn.call(l.context,n,r,o,i),!0;case 6:return l.fn.call(l.context,n,r,o,i,s),!0}for(d=1,u=new Array(c-1);d<c;d++)u[d-1]=arguments[d];l.fn.apply(l.context,u)}else{var f=l.length,p;for(d=0;d<f;d++)switch(l[d].once&&this.removeListener(e,l[d].fn,void 0,!0),c){case 1:l[d].fn.call(l[d].context);break;case 2:l[d].fn.call(l[d].context,n);break;case 3:l[d].fn.call(l[d].context,n,r);break;case 4:l[d].fn.call(l[d].context,n,r,o);break;default:if(!u)for(p=1,u=new Array(c-1);p<c;p++)u[p-1]=arguments[p];l[d].fn.apply(l[d].context,u)}}return!0};oc.prototype.on=function(e,n,r){return NUe(this,e,n,r,!1)};oc.prototype.once=function(e,n,r){return NUe(this,e,n,r,!0)};oc.prototype.removeListener=function(e,n,r,o){var i=jc?jc+e:e;if(!this._events[i])return this;if(!n)return dK(this,i),this;var s=this._events[i];if(s.fn)s.fn===n&&(!o||s.once)&&(!r||s.context===r)&&dK(this,i);else{for(var a=0,l=[],c=s.length;a<c;a++)(s[a].fn!==n||o&&!s[a].once||r&&s[a].context!==r)&&l.push(s[a]);l.length?this._events[i]=l.length===1?l[0]:l:dK(this,i)}return this};oc.prototype.removeAllListeners=function(e){var n;return e?(n=jc?jc+e:e,this._events[n]&&dK(this,n)):(this._events=new R2,this._eventsCount=0),this};oc.prototype.off=oc.prototype.removeListener;oc.prototype.addListener=oc.prototype.on;oc.prefixed=jc;oc.EventEmitter=oc;typeof Ece<"u"&&(Ece.exports=oc)});var kce=Tt((dSn,OUe)=>{"use strict";OUe.exports=(t,e)=>(e=e||(()=>{}),t.then(n=>new Promise(r=>{r(e())}).then(()=>n),n=>new Promise(r=>{r(e())}).then(()=>{throw n})))});var LUe=Tt((fSn,pK)=>{"use strict";var KEt=kce(),fK=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},RUe=(t,e,n)=>new Promise((r,o)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){r(t);return}let i=setTimeout(()=>{if(typeof n=="function"){try{r(n())}catch(l){o(l)}return}let s=typeof n=="string"?n:`Promise timed out after ${e} milliseconds`,a=n instanceof Error?n:new fK(s);typeof t.cancel=="function"&&t.cancel(),o(a)},e);KEt(t.then(r,o),()=>{clearTimeout(i)})});pK.exports=RUe;pK.exports.default=RUe;pK.exports.TimeoutError=fK});var DUe=Tt(Mce=>{"use strict";Object.defineProperty(Mce,"__esModule",{value:!0});function qEt(t,e,n){let r=0,o=t.length;for(;o>0;){let i=o/2|0,s=r+i;n(t[s],e)<=0?(r=++s,o-=i+1):o=i}return r}Mce.default=qEt});var $Ue=Tt(Oce=>{"use strict";Object.defineProperty(Oce,"__esModule",{value:!0});var GEt=DUe(),Nce=class{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);let r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}let o=GEt.default(this._queue,r,(i,s)=>s.priority-i.priority);this._queue.splice(o,0,r)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this._queue.length}};Oce.default=Nce});var UUe=Tt(Lce=>{"use strict";Object.defineProperty(Lce,"__esModule",{value:!0});var YEt=Ace(),FUe=LUe(),ZEt=$Ue(),mK=()=>{},JEt=new FUe.TimeoutError,Rce=class extends YEt{constructor(e){var n,r,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=mK,this._resolveIdle=mK,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:ZEt.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(n=e.intervalCap)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(o=e.interval)===null||o===void 0?void 0:o.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=mK,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=mK,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let n=this._intervalEnd-e;if(n<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},n)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let n=this._queue.dequeue();return n?(this.emit("active"),n(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,n={}){return new Promise((r,o)=>{let i=async()=>{this._pendingCount++,this._intervalCount++;try{let s=this._timeout===void 0&&n.timeout===void 0?e():FUe.default(Promise.resolve(e()),n.timeout===void 0?this._timeout:n.timeout,()=>{(n.throwOnTimeout===void 0?this._throwOnTimeout:n.throwOnTimeout)&&o(JEt)});r(await s)}catch(s){o(s)}this._next()};this._queue.enqueue(i,n),this._tryToStartAnother(),this.emit("add")})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let n=this._resolveEmpty;this._resolveEmpty=()=>{n(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let n=this._resolveIdle;this._resolveIdle=()=>{n(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Lce.default=Rce});var hK,BUe,zUe=C(()=>{hK=N(UUe(),1),BUe="default"in hK.default?hK.default.default:hK.default});var XEt,L2,jUe=C(()=>{MUe();zUe();XEt=[408,425,429,500,502,503,504],L2=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new BUe({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...n){return this.callWithOptions({},e,...n)}callWithOptions(e,n,...r){let o=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&o>0&&this.queueSizeBytes+o>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${o} bytes.`));o>0&&(this.queueSizeBytes+=o);let i=this.onFailedResponseHook,s=this.queue.add(()=>Pce(()=>n(...r).catch(a=>{throw a instanceof Error?a:new Error(a)}),{async onFailedAttempt({error:a}){if(typeof a!="object"||a==null)throw a;let l="message"in a&&typeof a.message=="string"?a.message:void 0;if(l?.startsWith("Cancel")||l?.startsWith("TimeoutError")||l?.startsWith("AbortError")||"name"in a&&a.name==="TimeoutError"||"code"in a&&a.code==="ECONNABORTED")throw a;let c="response"in a?a.response:void 0;if(i&&await i(c))return;let u=c?.status??("status"in a?a.status:void 0);if(u!=null&&(typeof u=="number"||typeof u=="string")&&!XEt.includes(+u))throw a},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return o>0&&(s=s.finally(()=>{this.queueSizeBytes-=o})),e.signal?Promise.race([s,new Promise((a,l)=>{e.signal?.addEventListener("abort",()=>{l(new Error("AbortError"))})})]):s}}});function Dce(t){return typeof t?._getType=="function"}function $ce(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}var VUe=C(()=>{});var D2=Tt((bSn,WUe)=>{"use strict";var QEt="2.0.0",eAt=Number.MAX_SAFE_INTEGER||9007199254740991,tAt=16,nAt=250,rAt=["major","premajor","minor","preminor","patch","prepatch","prerelease"];WUe.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:tAt,MAX_SAFE_BUILD_LENGTH:nAt,MAX_SAFE_INTEGER:eAt,RELEASE_TYPES:rAt,SEMVER_SPEC_VERSION:QEt,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var $2=Tt((CSn,HUe)=>{"use strict";var oAt=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};HUe.exports=oAt});var Qk=Tt((Ag,KUe)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Fce,MAX_SAFE_BUILD_LENGTH:iAt,MAX_LENGTH:sAt}=D2(),aAt=$2();Ag=KUe.exports={};var lAt=Ag.re=[],cAt=Ag.safeRe=[],At=Ag.src=[],uAt=Ag.safeSrc=[],kt=Ag.t={},dAt=0,Uce="[a-zA-Z0-9-]",fAt=[["\\s",1],["\\d",sAt],[Uce,iAt]],pAt=t=>{for(let[e,n]of fAt)t=t.split(`${e}*`).join(`${e}{0,${n}}`).split(`${e}+`).join(`${e}{1,${n}}`);return t},Yn=(t,e,n)=>{let r=pAt(e),o=dAt++;aAt(t,o,e),kt[t]=o,At[o]=e,uAt[o]=r,lAt[o]=new RegExp(e,n?"g":void 0),cAt[o]=new RegExp(r,n?"g":void 0)};Yn("NUMERICIDENTIFIER","0|[1-9]\\d*");Yn("NUMERICIDENTIFIERLOOSE","\\d+");Yn("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Uce}*`);Yn("MAINVERSION",`(${At[kt.NUMERICIDENTIFIER]})\\.(${At[kt.NUMERICIDENTIFIER]})\\.(${At[kt.NUMERICIDENTIFIER]})`);Yn("MAINVERSIONLOOSE",`(${At[kt.NUMERICIDENTIFIERLOOSE]})\\.(${At[kt.NUMERICIDENTIFIERLOOSE]})\\.(${At[kt.NUMERICIDENTIFIERLOOSE]})`);Yn("PRERELEASEIDENTIFIER",`(?:${At[kt.NONNUMERICIDENTIFIER]}|${At[kt.NUMERICIDENTIFIER]})`);Yn("PRERELEASEIDENTIFIERLOOSE",`(?:${At[kt.NONNUMERICIDENTIFIER]}|${At[kt.NUMERICIDENTIFIERLOOSE]})`);Yn("PRERELEASE",`(?:-(${At[kt.PRERELEASEIDENTIFIER]}(?:\\.${At[kt.PRERELEASEIDENTIFIER]})*))`);Yn("PRERELEASELOOSE",`(?:-?(${At[kt.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${At[kt.PRERELEASEIDENTIFIERLOOSE]})*))`);Yn("BUILDIDENTIFIER",`${Uce}+`);Yn("BUILD",`(?:\\+(${At[kt.BUILDIDENTIFIER]}(?:\\.${At[kt.BUILDIDENTIFIER]})*))`);Yn("FULLPLAIN",`v?${At[kt.MAINVERSION]}${At[kt.PRERELEASE]}?${At[kt.BUILD]}?`);Yn("FULL",`^${At[kt.FULLPLAIN]}$`);Yn("LOOSEPLAIN",`[v=\\s]*${At[kt.MAINVERSIONLOOSE]}${At[kt.PRERELEASELOOSE]}?${At[kt.BUILD]}?`);Yn("LOOSE",`^${At[kt.LOOSEPLAIN]}$`);Yn("GTLT","((?:<|>)?=?)");Yn("XRANGEIDENTIFIERLOOSE",`${At[kt.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);Yn("XRANGEIDENTIFIER",`${At[kt.NUMERICIDENTIFIER]}|x|X|\\*`);Yn("XRANGEPLAIN",`[v=\\s]*(${At[kt.XRANGEIDENTIFIER]})(?:\\.(${At[kt.XRANGEIDENTIFIER]})(?:\\.(${At[kt.XRANGEIDENTIFIER]})(?:${At[kt.PRERELEASE]})?${At[kt.BUILD]}?)?)?`);Yn("XRANGEPLAINLOOSE",`[v=\\s]*(${At[kt.XRANGEIDENTIFIERLOOSE]})(?:\\.(${At[kt.XRANGEIDENTIFIERLOOSE]})(?:\\.(${At[kt.XRANGEIDENTIFIERLOOSE]})(?:${At[kt.PRERELEASELOOSE]})?${At[kt.BUILD]}?)?)?`);Yn("XRANGE",`^${At[kt.GTLT]}\\s*${At[kt.XRANGEPLAIN]}$`);Yn("XRANGELOOSE",`^${At[kt.GTLT]}\\s*${At[kt.XRANGEPLAINLOOSE]}$`);Yn("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Fce}})(?:\\.(\\d{1,${Fce}}))?(?:\\.(\\d{1,${Fce}}))?`);Yn("COERCE",`${At[kt.COERCEPLAIN]}(?:$|[^\\d])`);Yn("COERCEFULL",At[kt.COERCEPLAIN]+`(?:${At[kt.PRERELEASE]})?(?:${At[kt.BUILD]})?(?:$|[^\\d])`);Yn("COERCERTL",At[kt.COERCE],!0);Yn("COERCERTLFULL",At[kt.COERCEFULL],!0);Yn("LONETILDE","(?:~>?)");Yn("TILDETRIM",`(\\s*)${At[kt.LONETILDE]}\\s+`,!0);Ag.tildeTrimReplace="$1~";Yn("TILDE",`^${At[kt.LONETILDE]}${At[kt.XRANGEPLAIN]}$`);Yn("TILDELOOSE",`^${At[kt.LONETILDE]}${At[kt.XRANGEPLAINLOOSE]}$`);Yn("LONECARET","(?:\\^)");Yn("CARETTRIM",`(\\s*)${At[kt.LONECARET]}\\s+`,!0);Ag.caretTrimReplace="$1^";Yn("CARET",`^${At[kt.LONECARET]}${At[kt.XRANGEPLAIN]}$`);Yn("CARETLOOSE",`^${At[kt.LONECARET]}${At[kt.XRANGEPLAINLOOSE]}$`);Yn("COMPARATORLOOSE",`^${At[kt.GTLT]}\\s*(${At[kt.LOOSEPLAIN]})$|^$`);Yn("COMPARATOR",`^${At[kt.GTLT]}\\s*(${At[kt.FULLPLAIN]})$|^$`);Yn("COMPARATORTRIM",`(\\s*)${At[kt.GTLT]}\\s*(${At[kt.LOOSEPLAIN]}|${At[kt.XRANGEPLAIN]})`,!0);Ag.comparatorTrimReplace="$1$2$3";Yn("HYPHENRANGE",`^\\s*(${At[kt.XRANGEPLAIN]})\\s+-\\s+(${At[kt.XRANGEPLAIN]})\\s*$`);Yn("HYPHENRANGELOOSE",`^\\s*(${At[kt.XRANGEPLAINLOOSE]})\\s+-\\s+(${At[kt.XRANGEPLAINLOOSE]})\\s*$`);Yn("STAR","(<|>)?=?\\s*\\*");Yn("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");Yn("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var gK=Tt((_Sn,qUe)=>{"use strict";var mAt=Object.freeze({loose:!0}),hAt=Object.freeze({}),gAt=t=>t?typeof t!="object"?mAt:t:hAt;qUe.exports=gAt});var Bce=Tt((SSn,ZUe)=>{"use strict";var GUe=/^[0-9]+$/,YUe=(t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let n=GUe.test(t),r=GUe.test(e);return n&&r&&(t=+t,e=+e),t===e?0:n&&!r?-1:r&&!n?1:t<e?-1:1},yAt=(t,e)=>YUe(e,t);ZUe.exports={compareIdentifiers:YUe,rcompareIdentifiers:yAt}});var ic=Tt((TSn,XUe)=>{"use strict";var yK=$2(),{MAX_LENGTH:JUe,MAX_SAFE_INTEGER:wK}=D2(),{safeRe:vK,t:xK}=Qk(),wAt=gK(),{compareIdentifiers:zce}=Bce(),jce=class t{constructor(e,n){if(n=wAt(n),e instanceof t){if(e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>JUe)throw new TypeError(`version is longer than ${JUe} characters`);yK("SemVer",e,n),this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease;let r=e.trim().match(n.loose?vK[xK.LOOSE]:vK[xK.FULL]);if(!r)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>wK||this.major<0)throw new TypeError("Invalid major version");if(this.minor>wK||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>wK||this.patch<0)throw new TypeError("Invalid patch version");r[4]?this.prerelease=r[4].split(".").map(o=>{if(/^[0-9]+$/.test(o)){let i=+o;if(i>=0&&i<wK)return i}return o}):this.prerelease=[],this.build=r[5]?r[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(e){if(yK("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let n=0;do{let r=this.prerelease[n],o=e.prerelease[n];if(yK("prerelease compare",n,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return zce(r,o)}while(++n)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let n=0;do{let r=this.build[n],o=e.build[n];if(yK("build compare",n,r,o),r===void 0&&o===void 0)return 0;if(o===void 0)return 1;if(r===void 0)return-1;if(r===o)continue;return zce(r,o)}while(++n)}inc(e,n,r){if(e.startsWith("pre")){if(!n&&r===!1)throw new Error("invalid increment argument: identifier is empty");if(n){let o=`-${n}`.match(this.options.loose?vK[xK.PRERELEASELOOSE]:vK[xK.PRERELEASE]);if(!o||o[1]!==n)throw new Error(`invalid identifier: ${n}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",n,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",n,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",n,r),this.inc("pre",n,r);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",n,r),this.inc("pre",n,r);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let o=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[o];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(n===this.prerelease.join(".")&&r===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(o)}}if(n){let i=[n,o];r===!1&&(i=[n]),zce(this.prerelease[0],n)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};XUe.exports=jce});var oI=Tt((ISn,eBe)=>{"use strict";var QUe=ic(),vAt=(t,e,n=!1)=>{if(t instanceof QUe)return t;try{return new QUe(t,e)}catch(r){if(!n)return null;throw r}};eBe.exports=vAt});var nBe=Tt((PSn,tBe)=>{"use strict";var xAt=oI(),bAt=(t,e)=>{let n=xAt(t,e);return n?n.version:null};tBe.exports=bAt});var oBe=Tt((ESn,rBe)=>{"use strict";var CAt=oI(),_At=(t,e)=>{let n=CAt(t.trim().replace(/^[=v]+/,""),e);return n?n.version:null};rBe.exports=_At});var aBe=Tt((ASn,sBe)=>{"use strict";var iBe=ic(),SAt=(t,e,n,r,o)=>{typeof n=="string"&&(o=r,r=n,n=void 0);try{return new iBe(t instanceof iBe?t.version:t,n).inc(e,r,o).version}catch{return null}};sBe.exports=SAt});var uBe=Tt((kSn,cBe)=>{"use strict";var lBe=oI(),TAt=(t,e)=>{let n=lBe(t,null,!0),r=lBe(e,null,!0),o=n.compare(r);if(o===0)return null;let i=o>0,s=i?n:r,a=i?r:n,l=!!s.prerelease.length;if(!!a.prerelease.length&&!l){if(!a.patch&&!a.minor)return"major";if(a.compareMain(s)===0)return a.minor&&!a.patch?"minor":"patch"}let u=l?"pre":"";return n.major!==r.major?u+"major":n.minor!==r.minor?u+"minor":n.patch!==r.patch?u+"patch":"prerelease"};cBe.exports=TAt});var fBe=Tt((MSn,dBe)=>{"use strict";var IAt=ic(),PAt=(t,e)=>new IAt(t,e).major;dBe.exports=PAt});var mBe=Tt((NSn,pBe)=>{"use strict";var EAt=ic(),AAt=(t,e)=>new EAt(t,e).minor;pBe.exports=AAt});var gBe=Tt((OSn,hBe)=>{"use strict";var kAt=ic(),MAt=(t,e)=>new kAt(t,e).patch;hBe.exports=MAt});var wBe=Tt((RSn,yBe)=>{"use strict";var NAt=oI(),OAt=(t,e)=>{let n=NAt(t,e);return n&&n.prerelease.length?n.prerelease:null};yBe.exports=OAt});var ip=Tt((LSn,xBe)=>{"use strict";var vBe=ic(),RAt=(t,e,n)=>new vBe(t,n).compare(new vBe(e,n));xBe.exports=RAt});var CBe=Tt((DSn,bBe)=>{"use strict";var LAt=ip(),DAt=(t,e,n)=>LAt(e,t,n);bBe.exports=DAt});var SBe=Tt(($Sn,_Be)=>{"use strict";var $At=ip(),FAt=(t,e)=>$At(t,e,!0);_Be.exports=FAt});var bK=Tt((FSn,IBe)=>{"use strict";var TBe=ic(),UAt=(t,e,n)=>{let r=new TBe(t,n),o=new TBe(e,n);return r.compare(o)||r.compareBuild(o)};IBe.exports=UAt});var EBe=Tt((USn,PBe)=>{"use strict";var BAt=bK(),zAt=(t,e)=>t.sort((n,r)=>BAt(n,r,e));PBe.exports=zAt});var kBe=Tt((BSn,ABe)=>{"use strict";var jAt=bK(),VAt=(t,e)=>t.sort((n,r)=>jAt(r,n,e));ABe.exports=VAt});var F2=Tt((zSn,MBe)=>{"use strict";var WAt=ip(),HAt=(t,e,n)=>WAt(t,e,n)>0;MBe.exports=HAt});var CK=Tt((jSn,NBe)=>{"use strict";var KAt=ip(),qAt=(t,e,n)=>KAt(t,e,n)<0;NBe.exports=qAt});var Vce=Tt((VSn,OBe)=>{"use strict";var GAt=ip(),YAt=(t,e,n)=>GAt(t,e,n)===0;OBe.exports=YAt});var Wce=Tt((WSn,RBe)=>{"use strict";var ZAt=ip(),JAt=(t,e,n)=>ZAt(t,e,n)!==0;RBe.exports=JAt});var _K=Tt((HSn,LBe)=>{"use strict";var XAt=ip(),QAt=(t,e,n)=>XAt(t,e,n)>=0;LBe.exports=QAt});var SK=Tt((KSn,DBe)=>{"use strict";var ekt=ip(),tkt=(t,e,n)=>ekt(t,e,n)<=0;DBe.exports=tkt});var Hce=Tt((qSn,$Be)=>{"use strict";var nkt=Vce(),rkt=Wce(),okt=F2(),ikt=_K(),skt=CK(),akt=SK(),lkt=(t,e,n,r)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t===n;case"!==":return typeof t=="object"&&(t=t.version),typeof n=="object"&&(n=n.version),t!==n;case"":case"=":case"==":return nkt(t,n,r);case"!=":return rkt(t,n,r);case">":return okt(t,n,r);case">=":return ikt(t,n,r);case"<":return skt(t,n,r);case"<=":return akt(t,n,r);default:throw new TypeError(`Invalid operator: ${e}`)}};$Be.exports=lkt});var UBe=Tt((GSn,FBe)=>{"use strict";var ckt=ic(),ukt=oI(),{safeRe:TK,t:IK}=Qk(),dkt=(t,e)=>{if(t instanceof ckt)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let n=null;if(!e.rtl)n=t.match(e.includePrerelease?TK[IK.COERCEFULL]:TK[IK.COERCE]);else{let l=e.includePrerelease?TK[IK.COERCERTLFULL]:TK[IK.COERCERTL],c;for(;(c=l.exec(t))&&(!n||n.index+n[0].length!==t.length);)(!n||c.index+c[0].length!==n.index+n[0].length)&&(n=c),l.lastIndex=c.index+c[1].length+c[2].length;l.lastIndex=-1}if(n===null)return null;let r=n[2],o=n[3]||"0",i=n[4]||"0",s=e.includePrerelease&&n[5]?`-${n[5]}`:"",a=e.includePrerelease&&n[6]?`+${n[6]}`:"";return ukt(`${r}.${o}.${i}${s}${a}`,e)};FBe.exports=dkt});var zBe=Tt((YSn,BBe)=>{"use strict";var Kce=class{constructor(){this.max=1e3,this.map=new Map}get(e){let n=this.map.get(e);if(n!==void 0)return this.map.delete(e),this.map.set(e,n),n}delete(e){return this.map.delete(e)}set(e,n){if(!this.delete(e)&&n!==void 0){if(this.map.size>=this.max){let o=this.map.keys().next().value;this.delete(o)}this.map.set(e,n)}return this}};BBe.exports=Kce});var sp=Tt((ZSn,HBe)=>{"use strict";var fkt=/\s+/g,qce=class t{constructor(e,n){if(n=mkt(n),e instanceof t)return e.loose===!!n.loose&&e.includePrerelease===!!n.includePrerelease?e:new t(e.raw,n);if(e instanceof Gce)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=n,this.loose=!!n.loose,this.includePrerelease=!!n.includePrerelease,this.raw=e.trim().replace(fkt," "),this.set=this.raw.split("||").map(r=>this.parseRange(r.trim())).filter(r=>r.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let r=this.set[0];if(this.set=this.set.filter(o=>!VBe(o[0])),this.set.length===0)this.set=[r];else if(this.set.length>1){for(let o of this.set)if(o.length===1&&bkt(o[0])){this.set=[o];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let n=this.set[e];for(let r=0;r<n.length;r++)r>0&&(this.formatted+=" "),this.formatted+=n[r].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let r=((this.options.includePrerelease&&vkt)|(this.options.loose&&xkt))+":"+e,o=jBe.get(r);if(o)return o;let i=this.options.loose,s=i?Vc[sc.HYPHENRANGELOOSE]:Vc[sc.HYPHENRANGE];e=e.replace(s,Mkt(this.options.includePrerelease)),Qo("hyphen replace",e),e=e.replace(Vc[sc.COMPARATORTRIM],gkt),Qo("comparator trim",e),e=e.replace(Vc[sc.TILDETRIM],ykt),Qo("tilde trim",e),e=e.replace(Vc[sc.CARETTRIM],wkt),Qo("caret trim",e);let a=e.split(" ").map(d=>Ckt(d,this.options)).join(" ").split(/\s+/).map(d=>kkt(d,this.options));i&&(a=a.filter(d=>(Qo("loose invalid filter",d,this.options),!!d.match(Vc[sc.COMPARATORLOOSE])))),Qo("range list",a);let l=new Map,c=a.map(d=>new Gce(d,this.options));for(let d of c){if(VBe(d))return[d];l.set(d.value,d)}l.size>1&&l.has("")&&l.delete("");let u=[...l.values()];return jBe.set(r,u),u}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(r=>WBe(r,n)&&e.set.some(o=>WBe(o,n)&&r.every(i=>o.every(s=>i.intersects(s,n)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new hkt(e,this.options)}catch{return!1}for(let n=0;n<this.set.length;n++)if(Nkt(this.set[n],e,this.options))return!0;return!1}};HBe.exports=qce;var pkt=zBe(),jBe=new pkt,mkt=gK(),Gce=U2(),Qo=$2(),hkt=ic(),{safeRe:Vc,t:sc,comparatorTrimReplace:gkt,tildeTrimReplace:ykt,caretTrimReplace:wkt}=Qk(),{FLAG_INCLUDE_PRERELEASE:vkt,FLAG_LOOSE:xkt}=D2(),VBe=t=>t.value==="<0.0.0-0",bkt=t=>t.value==="",WBe=(t,e)=>{let n=!0,r=t.slice(),o=r.pop();for(;n&&r.length;)n=r.every(i=>o.intersects(i,e)),o=r.pop();return n},Ckt=(t,e)=>(t=t.replace(Vc[sc.BUILD],""),Qo("comp",t,e),t=Tkt(t,e),Qo("caret",t),t=_kt(t,e),Qo("tildes",t),t=Pkt(t,e),Qo("xrange",t),t=Akt(t,e),Qo("stars",t),t),Wc=t=>!t||t.toLowerCase()==="x"||t==="*",_kt=(t,e)=>t.trim().split(/\s+/).map(n=>Skt(n,e)).join(" "),Skt=(t,e)=>{let n=e.loose?Vc[sc.TILDELOOSE]:Vc[sc.TILDE];return t.replace(n,(r,o,i,s,a)=>{Qo("tilde",t,r,o,i,s,a);let l;return Wc(o)?l="":Wc(i)?l=`>=${o}.0.0 <${+o+1}.0.0-0`:Wc(s)?l=`>=${o}.${i}.0 <${o}.${+i+1}.0-0`:a?(Qo("replaceTilde pr",a),l=`>=${o}.${i}.${s}-${a} <${o}.${+i+1}.0-0`):l=`>=${o}.${i}.${s} <${o}.${+i+1}.0-0`,Qo("tilde return",l),l})},Tkt=(t,e)=>t.trim().split(/\s+/).map(n=>Ikt(n,e)).join(" "),Ikt=(t,e)=>{Qo("caret",t,e);let n=e.loose?Vc[sc.CARETLOOSE]:Vc[sc.CARET],r=e.includePrerelease?"-0":"";return t.replace(n,(o,i,s,a,l)=>{Qo("caret",t,o,i,s,a,l);let c;return Wc(i)?c="":Wc(s)?c=`>=${i}.0.0${r} <${+i+1}.0.0-0`:Wc(a)?i==="0"?c=`>=${i}.${s}.0${r} <${i}.${+s+1}.0-0`:c=`>=${i}.${s}.0${r} <${+i+1}.0.0-0`:l?(Qo("replaceCaret pr",l),i==="0"?s==="0"?c=`>=${i}.${s}.${a}-${l} <${i}.${s}.${+a+1}-0`:c=`>=${i}.${s}.${a}-${l} <${i}.${+s+1}.0-0`:c=`>=${i}.${s}.${a}-${l} <${+i+1}.0.0-0`):(Qo("no pr"),i==="0"?s==="0"?c=`>=${i}.${s}.${a}${r} <${i}.${s}.${+a+1}-0`:c=`>=${i}.${s}.${a}${r} <${i}.${+s+1}.0-0`:c=`>=${i}.${s}.${a} <${+i+1}.0.0-0`),Qo("caret return",c),c})},Pkt=(t,e)=>(Qo("replaceXRanges",t,e),t.split(/\s+/).map(n=>Ekt(n,e)).join(" ")),Ekt=(t,e)=>{t=t.trim();let n=e.loose?Vc[sc.XRANGELOOSE]:Vc[sc.XRANGE];return t.replace(n,(r,o,i,s,a,l)=>{Qo("xRange",t,r,o,i,s,a,l);let c=Wc(i),u=c||Wc(s),d=u||Wc(a),f=d;return o==="="&&f&&(o=""),l=e.includePrerelease?"-0":"",c?o===">"||o==="<"?r="<0.0.0-0":r="*":o&&f?(u&&(s=0),a=0,o===">"?(o=">=",u?(i=+i+1,s=0,a=0):(s=+s+1,a=0)):o==="<="&&(o="<",u?i=+i+1:s=+s+1),o==="<"&&(l="-0"),r=`${o+i}.${s}.${a}${l}`):u?r=`>=${i}.0.0${l} <${+i+1}.0.0-0`:d&&(r=`>=${i}.${s}.0${l} <${i}.${+s+1}.0-0`),Qo("xRange return",r),r})},Akt=(t,e)=>(Qo("replaceStars",t,e),t.trim().replace(Vc[sc.STAR],"")),kkt=(t,e)=>(Qo("replaceGTE0",t,e),t.trim().replace(Vc[e.includePrerelease?sc.GTE0PRE:sc.GTE0],"")),Mkt=t=>(e,n,r,o,i,s,a,l,c,u,d,f)=>(Wc(r)?n="":Wc(o)?n=`>=${r}.0.0${t?"-0":""}`:Wc(i)?n=`>=${r}.${o}.0${t?"-0":""}`:s?n=`>=${n}`:n=`>=${n}${t?"-0":""}`,Wc(c)?l="":Wc(u)?l=`<${+c+1}.0.0-0`:Wc(d)?l=`<${c}.${+u+1}.0-0`:f?l=`<=${c}.${u}.${d}-${f}`:t?l=`<${c}.${u}.${+d+1}-0`:l=`<=${l}`,`${n} ${l}`.trim()),Nkt=(t,e,n)=>{for(let r=0;r<t.length;r++)if(!t[r].test(e))return!1;if(e.prerelease.length&&!n.includePrerelease){for(let r=0;r<t.length;r++)if(Qo(t[r].semver),t[r].semver!==Gce.ANY&&t[r].semver.prerelease.length>0){let o=t[r].semver;if(o.major===e.major&&o.minor===e.minor&&o.patch===e.patch)return!0}return!1}return!0}});var U2=Tt((JSn,JBe)=>{"use strict";var B2=Symbol("SemVer ANY"),Jce=class t{static get ANY(){return B2}constructor(e,n){if(n=KBe(n),e instanceof t){if(e.loose===!!n.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Zce("comparator",e,n),this.options=n,this.loose=!!n.loose,this.parse(e),this.semver===B2?this.value="":this.value=this.operator+this.semver.version,Zce("comp",this)}parse(e){let n=this.options.loose?qBe[GBe.COMPARATORLOOSE]:qBe[GBe.COMPARATOR],r=e.match(n);if(!r)throw new TypeError(`Invalid comparator: ${e}`);this.operator=r[1]!==void 0?r[1]:"",this.operator==="="&&(this.operator=""),r[2]?this.semver=new YBe(r[2],this.options.loose):this.semver=B2}toString(){return this.value}test(e){if(Zce("Comparator.test",e,this.options.loose),this.semver===B2||e===B2)return!0;if(typeof e=="string")try{e=new YBe(e,this.options)}catch{return!1}return Yce(e,this.operator,this.semver,this.options)}intersects(e,n){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new ZBe(e.value,n).test(this.value):e.operator===""?e.value===""?!0:new ZBe(this.value,n).test(e.semver):(n=KBe(n),n.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!n.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Yce(this.semver,"<",e.semver,n)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Yce(this.semver,">",e.semver,n)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};JBe.exports=Jce;var KBe=gK(),{safeRe:qBe,t:GBe}=Qk(),Yce=Hce(),Zce=$2(),YBe=ic(),ZBe=sp()});var z2=Tt((XSn,XBe)=>{"use strict";var Okt=sp(),Rkt=(t,e,n)=>{try{e=new Okt(e,n)}catch{return!1}return e.test(t)};XBe.exports=Rkt});var eze=Tt((QSn,QBe)=>{"use strict";var Lkt=sp(),Dkt=(t,e)=>new Lkt(t,e).set.map(n=>n.map(r=>r.value).join(" ").trim().split(" "));QBe.exports=Dkt});var nze=Tt((eTn,tze)=>{"use strict";var $kt=ic(),Fkt=sp(),Ukt=(t,e,n)=>{let r=null,o=null,i=null;try{i=new Fkt(e,n)}catch{return null}return t.forEach(s=>{i.test(s)&&(!r||o.compare(s)===-1)&&(r=s,o=new $kt(r,n))}),r};tze.exports=Ukt});var oze=Tt((tTn,rze)=>{"use strict";var Bkt=ic(),zkt=sp(),jkt=(t,e,n)=>{let r=null,o=null,i=null;try{i=new zkt(e,n)}catch{return null}return t.forEach(s=>{i.test(s)&&(!r||o.compare(s)===1)&&(r=s,o=new Bkt(r,n))}),r};rze.exports=jkt});var aze=Tt((nTn,sze)=>{"use strict";var Xce=ic(),Vkt=sp(),ize=F2(),Wkt=(t,e)=>{t=new Vkt(t,e);let n=new Xce("0.0.0");if(t.test(n)||(n=new Xce("0.0.0-0"),t.test(n)))return n;n=null;for(let r=0;r<t.set.length;++r){let o=t.set[r],i=null;o.forEach(s=>{let a=new Xce(s.semver.version);switch(s.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!i||ize(a,i))&&(i=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${s.operator}`)}}),i&&(!n||ize(n,i))&&(n=i)}return n&&t.test(n)?n:null};sze.exports=Wkt});var cze=Tt((rTn,lze)=>{"use strict";var Hkt=sp(),Kkt=(t,e)=>{try{return new Hkt(t,e).range||"*"}catch{return null}};lze.exports=Kkt});var PK=Tt((oTn,pze)=>{"use strict";var qkt=ic(),fze=U2(),{ANY:Gkt}=fze,Ykt=sp(),Zkt=z2(),uze=F2(),dze=CK(),Jkt=SK(),Xkt=_K(),Qkt=(t,e,n,r)=>{t=new qkt(t,r),e=new Ykt(e,r);let o,i,s,a,l;switch(n){case">":o=uze,i=Jkt,s=dze,a=">",l=">=";break;case"<":o=dze,i=Xkt,s=uze,a="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(Zkt(t,e,r))return!1;for(let c=0;c<e.set.length;++c){let u=e.set[c],d=null,f=null;if(u.forEach(p=>{p.semver===Gkt&&(p=new fze(">=0.0.0")),d=d||p,f=f||p,o(p.semver,d.semver,r)?d=p:s(p.semver,f.semver,r)&&(f=p)}),d.operator===a||d.operator===l||(!f.operator||f.operator===a)&&i(t,f.semver))return!1;if(f.operator===l&&s(t,f.semver))return!1}return!0};pze.exports=Qkt});var hze=Tt((iTn,mze)=>{"use strict";var eMt=PK(),tMt=(t,e,n)=>eMt(t,e,">",n);mze.exports=tMt});var yze=Tt((sTn,gze)=>{"use strict";var nMt=PK(),rMt=(t,e,n)=>nMt(t,e,"<",n);gze.exports=rMt});var xze=Tt((aTn,vze)=>{"use strict";var wze=sp(),oMt=(t,e,n)=>(t=new wze(t,n),e=new wze(e,n),t.intersects(e,n));vze.exports=oMt});var Cze=Tt((lTn,bze)=>{"use strict";var iMt=z2(),sMt=ip();bze.exports=(t,e,n)=>{let r=[],o=null,i=null,s=t.sort((u,d)=>sMt(u,d,n));for(let u of s)iMt(u,e,n)?(i=u,o||(o=u)):(i&&r.push([o,i]),i=null,o=null);o&&r.push([o,null]);let a=[];for(let[u,d]of r)u===d?a.push(u):!d&&u===s[0]?a.push("*"):d?u===s[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let l=a.join(" || "),c=typeof e.raw=="string"?e.raw:String(e);return l.length<c.length?l:e}});var Eze=Tt((cTn,Pze)=>{"use strict";var _ze=sp(),eue=U2(),{ANY:Qce}=eue,j2=z2(),tue=ip(),aMt=(t,e,n={})=>{if(t===e)return!0;t=new _ze(t,n),e=new _ze(e,n);let r=!1;e:for(let o of t.set){for(let i of e.set){let s=cMt(o,i,n);if(r=r||s!==null,s)continue e}if(r)return!1}return!0},lMt=[new eue(">=0.0.0-0")],Sze=[new eue(">=0.0.0")],cMt=(t,e,n)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===Qce){if(e.length===1&&e[0].semver===Qce)return!0;n.includePrerelease?t=lMt:t=Sze}if(e.length===1&&e[0].semver===Qce){if(n.includePrerelease)return!0;e=Sze}let r=new Set,o,i;for(let p of t)p.operator===">"||p.operator===">="?o=Tze(o,p,n):p.operator==="<"||p.operator==="<="?i=Ize(i,p,n):r.add(p.semver);if(r.size>1)return null;let s;if(o&&i){if(s=tue(o.semver,i.semver,n),s>0)return null;if(s===0&&(o.operator!==">="||i.operator!=="<="))return null}for(let p of r){if(o&&!j2(p,String(o),n)||i&&!j2(p,String(i),n))return null;for(let m of e)if(!j2(p,String(m),n))return!1;return!0}let a,l,c,u,d=i&&!n.includePrerelease&&i.semver.prerelease.length?i.semver:!1,f=o&&!n.includePrerelease&&o.semver.prerelease.length?o.semver:!1;d&&d.prerelease.length===1&&i.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",c=c||p.operator==="<"||p.operator==="<=",o){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(a=Tze(o,p,n),a===p&&a!==o)return!1}else if(o.operator===">="&&!j2(o.semver,String(p),n))return!1}if(i){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(l=Ize(i,p,n),l===p&&l!==i)return!1}else if(i.operator==="<="&&!j2(i.semver,String(p),n))return!1}if(!p.operator&&(i||o)&&s!==0)return!1}return!(o&&c&&!i&&s!==0||i&&u&&!o&&s!==0||f||d)},Tze=(t,e,n)=>{if(!t)return e;let r=tue(t.semver,e.semver,n);return r>0?t:r<0||e.operator===">"&&t.operator===">="?e:t},Ize=(t,e,n)=>{if(!t)return e;let r=tue(t.semver,e.semver,n);return r<0?t:r>0||e.operator==="<"&&t.operator==="<="?e:t};Pze.exports=aMt});var Nze=Tt((uTn,Mze)=>{"use strict";var nue=Qk(),Aze=D2(),uMt=ic(),kze=Bce(),dMt=oI(),fMt=nBe(),pMt=oBe(),mMt=aBe(),hMt=uBe(),gMt=fBe(),yMt=mBe(),wMt=gBe(),vMt=wBe(),xMt=ip(),bMt=CBe(),CMt=SBe(),_Mt=bK(),SMt=EBe(),TMt=kBe(),IMt=F2(),PMt=CK(),EMt=Vce(),AMt=Wce(),kMt=_K(),MMt=SK(),NMt=Hce(),OMt=UBe(),RMt=U2(),LMt=sp(),DMt=z2(),$Mt=eze(),FMt=nze(),UMt=oze(),BMt=aze(),zMt=cze(),jMt=PK(),VMt=hze(),WMt=yze(),HMt=xze(),KMt=Cze(),qMt=Eze();Mze.exports={parse:dMt,valid:fMt,clean:pMt,inc:mMt,diff:hMt,major:gMt,minor:yMt,patch:wMt,prerelease:vMt,compare:xMt,rcompare:bMt,compareLoose:CMt,compareBuild:_Mt,sort:SMt,rsort:TMt,gt:IMt,lt:PMt,eq:EMt,neq:AMt,gte:kMt,lte:MMt,cmp:NMt,coerce:OMt,Comparator:RMt,Range:LMt,satisfies:DMt,toComparators:$Mt,maxSatisfying:FMt,minSatisfying:UMt,minVersion:BMt,validRange:zMt,outside:jMt,gtr:VMt,ltr:WMt,intersects:HMt,simplifyRange:KMt,subset:qMt,SemVer:uMt,re:nue.re,src:nue.src,tokens:nue.t,SEMVER_SPEC_VERSION:Aze.SEMVER_SPEC_VERSION,RELEASE_TYPES:Aze.RELEASE_TYPES,compareIdentifiers:kze.compareIdentifiers,rcompareIdentifiers:kze.rcompareIdentifiers}});function Ow(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(`Invalid identifier format: ${t}`);let[e,n]=t.split(":"),r=n||"latest";if(e.includes("/")){let[o,i]=e.split("/",2);if(!o||!i)throw new Error(`Invalid identifier format: ${t}`);return[o,i,r]}else{if(!e)throw new Error(`Invalid identifier format: ${t}`);return["-",e,r]}}var GMt,Oze=C(()=>{GMt=N(Nze(),1)});function iue(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}async function zt(t,e,n){let r;if(t.ok){n&&(r=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let a=new Error(`${t.status} ${t.statusText}`);throw a.status=t?.status,a}if(r===void 0)try{r=await t.text()}catch{r=""}let o=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${r}`;if(t.status===404)throw new oue(o);if(t.status===409)throw new rue(o);let i=new Error(o);throw i.status=t.status,i}function Lze(t){return typeof t=="object"&&t!==null&&t.code===Rze}var rue,oue,Rze,EK,sue=C(()=>{rue=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},oue=class extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};Rze="ERR_CONFLICTING_ENDPOINTS",EK=class extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:Rze}),this.name="ConflictingEndpointsError"}}});function JMt(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function AK(t){return ZMt.encode(t)}function $ze(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function XMt(t){return function(e,n){if(t){let r=t.call(this,e,n);if(r!==void 0)return r}return $ze(n)}}function Hu(t,e,n,r,o){try{let i=JSON.stringify(t,XMt(n),r);return AK(i)}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
Context: ${e}`:""}`),AK("[Unserializable]");rs("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
Context: ${e}`:""}`),typeof o>"u"&&(o=JMt()),lue(t,"",0,[],void 0,0,o);let s;try{eM.length===0?s=JSON.stringify(t,n,r):s=JSON.stringify(t,QMt(n),r)}catch{return AK("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;kK.length!==0;){let a=kK.pop();a.length===4?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}}return AK(s)}}function aue(t,e,n,r){var o=Object.getOwnPropertyDescriptor(r,n);o.get!==void 0?o.configurable?(Object.defineProperty(r,n,{value:t}),kK.push([r,n,e,o])):eM.push([e,n,t]):(r[n]=t,kK.push([r,n,e]))}function lue(t,e,n,r,o,i,s){i+=1;var a;if(typeof t=="object"&&t!==null){for(a=0;a<r.length;a++)if(r[a]===t){aue(YMt,t,e,o);return}if(typeof s.depthLimit<"u"&&i>s.depthLimit){aue(Dze,t,e,o);return}if(typeof s.edgesLimit<"u"&&n+1>s.edgesLimit){aue(Dze,t,e,o);return}if(r.push(t),Array.isArray(t))for(a=0;a<t.length;a++)lue(t[a],a,a,r,t,i,s);else{t=$ze(t);var l=Object.keys(t);for(a=0;a<l.length;a++){var c=l[a];lue(t[c],c,a,r,t,i,s)}}r.pop()}}function QMt(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(eM.length>0)for(var r=0;r<eM.length;r++){var o=eM[r];if(o[1]===e&&o[0]===n){n=o[2],eM.splice(r,1);break}}return t.call(this,e,n)}}var Dze,YMt,kK,eM,ZMt,Fze=C(()=>{Mw();Dze="[...]",YMt={result:"[Circular]"},kK=[],eM=[],ZMt=new TextEncoder});function Uze(t,e,n){if(n)return t;let r=sK(),o=e??gce(),i=t.extra??{},s=i.metadata;return t.extra={...i,runtime:{...r,...i?.runtime},metadata:{...o,...o.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??o.revision_id}:{},...s}},t}async function nNt(t){let e=[];for await(let n of t)e.push(n);return e}function MK(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}function Bze(t){return typeof t=="number"?Number(t.toFixed(4)):t}function jze(t){return"dataset_id"in t||"dataset_name"in t}var eNt,tNt,rNt,oNt,Vze,iNt,sNt,zze,cue,rI,dce=C(()=>{q3();EUe();Sce();jUe();VUe();Mw();iK();tK();G3();Oze();sue();uce();oce();Fze();eNt=t=>{let e=t?.toString()??rs("TRACING_SAMPLING_RATE");if(e===void 0)return;let n=parseFloat(e);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},tNt=t=>{let n=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};rNt=async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(n=>setTimeout(n,e)),!0}return!1};oNt=24*1024*1024,Vze=1024*1024*1024,iNt=1e4,sNt=100,zze="https://api.smith.langchain.com",cue=class{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??Vze}peek(){return this.items[0]}push(e){let n,r=new Promise(i=>{n=i}),o=Hu(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+o>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${o} bytes.`),n(),r):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:n,itemPromise:r,size:o}),this.sizeBytes+=o,r)}pop({upToSizeBytes:e,upToSize:n}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let r=[],o=0;for(;o+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<n;){let i=this.items.shift();i&&(r.push(i),o+=i.size,this.sizeBytes-=i.size)}if(r.length===0&&this.items.length>0){let i=this.items.shift();r.push(i),o+=i.size,this.sizeBytes-=i.size}return[r.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>r.forEach(i=>i.itemPromiseResolve())]}},rI=class t{get _fetch(){return this.fetchImplementation||iUe(this.debug)}constructor(e={}){Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Hd("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:rs("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Hd("LANGSMITH_DEBUG")==="true"});let n=t.getDefaultClientConfig();if(this.tracingSampleRate=eNt(e.tracingSamplingRate),this.apiUrl=MK(e.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=MK(e.apiKey??n.apiKey),this.webUrl=MK(e.webUrl??n.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=MK(e.workspaceId??rs("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new L2({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation;let r=e.maxIngestMemoryBytes??Vze;this.batchIngestCaller=new L2({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:r,...e.callerOptions??{},onFailedResponseHook:rNt,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??n.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??n.hideOutputs,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new cue(r),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,aK()&&(this.langSmithToOTELTranslator=new cK),this.cachedLSEnvVarsForMetadata=gce(),e.cache!==void 0&&e.disablePromptCache&&tI("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(tI("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=rK:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=rK)}static getDefaultClientConfig(){let e=rs("API_KEY"),n=rs("ENDPOINT")??zze,r=rs("HIDE_INPUTS")==="true",o=rs("HIDE_OUTPUTS")==="true";return{apiUrl:n,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:o}}getHostUrl(){return this.webUrl?this.webUrl:tNt(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){let e={"User-Agent":`langsmith-js/${oK}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async prepareRunCreateOrUpdateInputs(e){let n={...e};return n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n}async _getResponse(e,n){let r=n?.toString()??"",o=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{let s=await this._fetch(o,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(s,`fetch ${e}`),s})}async _get(e,n){return(await this._getResponse(e,n)).json()}async*_getPaginated(e,n=new URLSearchParams,r){let o=Number(n.get("offset"))||0,i=Number(n.get("limit"))||100;for(;;){n.set("offset",String(o)),n.set("limit",String(i));let s=`${this.apiUrl}${e}?${n}`,a=await this.caller.call(async()=>{let c=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(c,`fetch ${e}`),c}),l=r?r(await a.json()):await a.json();if(l.length===0||(yield l,l.length<i))break;o+=l.length}}async*_getCursorPaginatedList(e,n=null,r="POST",o="runs"){let i=n?{...n}:{};for(;;){let s=JSON.stringify(i),l=await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(u,`fetch ${e}`),u})).json();if(!l||!l[o])break;yield l[o];let c=l.cursors;if(!c||!c.next)break;i.cursor=c.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,n=!1){if(this.tracingSampleRate===void 0)return e;if(n){let r=[];for(let o of e)this.filteredPostUuids.has(o.trace_id)?o.id===o.trace_id&&this.filteredPostUuids.delete(o.trace_id):r.push(o);return r}else{let r=[];for(let o of e){let i=o.trace_id??o.id;this.filteredPostUuids.has(i)||(o.id===i?this._shouldSample()?r.push(o):this.filteredPostUuids.add(i):r.push(o))}return r}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??oNt}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??sNt}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n}){let r=[];for(;this.autoBatchQueue.items.length>0;){let[o,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:n});if(!o.length){i();break}let s=o.reduce((c,u)=>{let d=u.apiUrl??this.apiUrl,f=u.apiKey??this.apiKey,m=u.apiKey===this.apiKey&&u.apiUrl===this.apiUrl?"default":`${d}|${f}`;return c[m]||(c[m]=[]),c[m].push(u),c},{}),a=[];for(let[c,u]of Object.entries(s)){let d=this._processBatch(u,{apiUrl:c==="default"?void 0:c.split("|")[0],apiKey:c==="default"?void 0:c.split("|")[1]});a.push(d)}let l=Promise.all(a).finally(i);r.push(l)}return Promise.all(r)}async _processBatch(e,n){if(!e.length)return;let r=e.reduce((o,i)=>o+(i.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let o={runCreates:e.filter(a=>a.action==="create").map(a=>a.item),runUpdates:e.filter(a=>a.action==="update").map(a=>a.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let a=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(o,{...n,useGzip:a,sizeBytes:r})}catch(l){if(iue(l))this._multipartDisabled=!0,await this.batchIngestRuns(o,{...n,sizeBytes:r});else throw l}}else await this.batchIngestRuns(o,{...n,sizeBytes:r})}}catch(o){console.error("Error exporting batch:",o)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let n=new Map,r=[];for(let o of e)o.item.id&&o.otelContext&&(n.set(o.item.id,o.otelContext),o.action==="create"?r.push({operation:"post",id:o.item.id,trace_id:o.item.trace_id??o.item.id,run:o.item}):r.push({operation:"patch",id:o.item.id,trace_id:o.item.trace_id??o.item.id,run:o.item}));this.langSmithToOTELTranslator.exportBatch(r,n)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Uze(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let n=this.autoBatchQueue.push(e);if(this.manualFlushMode)return n;let r=await this._getBatchSizeLimitBytes(),o=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>o)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:o}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:o})},this.autoBatchAggregationDelayMs)),n}async _getServerInfo(){let n=await(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(iNt),...this.fetchOptions});return await zt(r,"get server info"),r})).json();return this.debug&&console.log(`
=== LangSmith Server Configuration ===
`+JSON.stringify(n,null,2)+`
`),n}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n})}_cloneCurrentOTELContext(){let e=lK(),n=IUe();if(this.langSmithToOTELTranslator!==void 0){let r=e.getActiveSpan();if(r)return e.setSpan(n.active(),r)}}async createRun(e,n){if(!this._filterForSampling([e]).length)return;let r={...this.headers,"Content-Type":"application/json"},o=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:o,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:l,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let s=Uze(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(r["x-tenant-id"]=n.workspaceId);let a=Hu(s,`Creating run with id: ${s.id}`);await this.caller.call(async()=>{let l=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await zt(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let o=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),i=await Promise.all(n?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(o.length>0&&i.length>0){let l=o.reduce((u,d)=>(d.id&&(u[d.id]=d),u),{}),c=[];for(let u of i)u.id!==void 0&&l[u.id]?l[u.id]={...l[u.id],...u}:c.push(u);o=Object.values(l),i=c}let s={post:o,patch:i};if(!s.post.length&&!s.patch.length)return;let a={post:[],patch:[]};for(let l of["post","patch"]){let c=l,u=s[c].reverse(),d=u.pop();for(;d!==void 0;)a[c].push(d),d=u.pop()}if(a.post.length>0||a.patch.length>0){let l=a.post.map(c=>c.id).concat(a.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(Hu(a,`Ingesting runs with ids: ${l}`),r)}}async _postBatchIngestRuns(e,n){let r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};n?.apiKey!==void 0&&(r["x-api-key"]=n.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let o=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await zt(o,"batch create run",!0),o})}async multipartIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let o={},i=[];for(let d of e??[]){let f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(o[f.id]=f.attachments),delete f.attachments,i.push(f)}let s=[];for(let d of n??[])s.push(await this.prepareRunCreateOrUpdateInputs(d));if(i.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(i.length>0&&s.length>0){let d=i.reduce((p,m)=>(m.id&&(p[m.id]=m),p),{}),f=[];for(let p of s)p.id!==void 0&&d[p.id]?d[p.id]={...d[p.id],...p}:f.push(p);i=Object.values(d),s=f}if(i.length===0&&s.length===0)return;let c=[],u=[];for(let[d,f]of[["post",i],["patch",s]])for(let p of f){let{inputs:m,outputs:h,events:g,extra:y,error:w,serialized:v,attachments:x,...b}=p,_={inputs:m,outputs:h,events:g,extra:y,error:w,serialized:v},T=Hu(b,`Serializing for multipart ingestion of run with id: ${b.id}`);u.push({name:`${d}.${b.id}`,payload:new Blob([T],{type:`application/json; length=${T.length}`})});for(let[S,P]of Object.entries(_)){if(P===void 0)continue;let A=Hu(P,`Serializing ${S} for multipart ingestion of run with id: ${b.id}`);u.push({name:`${d}.${b.id}.${S}`,payload:new Blob([A],{type:`application/json; length=${A.length}`})})}if(b.id!==void 0){let S=o[b.id];if(S){delete o[b.id];for(let[P,A]of Object.entries(S)){let O,D;if(Array.isArray(A)?[O,D]=A:(O=A.mimeType,D=A.data),P.includes(".")){console.warn(`Skipping attachment '${P}' for run ${b.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}u.push({name:`attachment.${b.id}.${P}`,payload:new Blob([D],{type:`${O}; length=${D.byteLength}`})})}}}c.push(`trace=${b.trace_id},id=${b.id}`)}await this._sendMultipartRequest(u,c.join("; "),r)}async _createNodeFetchBody(e,n){let r=[];for(let s of e)r.push(new Blob([`--${n}\r
`])),r.push(new Blob([`Content-Disposition: form-data; name="${s.name}"\r
`,`Content-Type: ${s.payload.type}\r
\r
`])),r.push(s.payload),r.push(new Blob([`\r
`]));return r.push(new Blob([`--${n}--\r
`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,n){let r=new TextEncoder;return new ReadableStream({async start(i){let s=async a=>{typeof a=="string"?i.enqueue(r.encode(a)):i.enqueue(a)};for(let a of e){await s(`--${n}\r
`),await s(`Content-Disposition: form-data; name="${a.name}"\r
`),await s(`Content-Type: ${a.payload.type}\r
\r
`);let c=a.payload.stream().getReader();try{let u;for(;!(u=await c.read()).done;)i.enqueue(u.value)}finally{c.releaseLock()}await s(`\r
`)}await s(`--${n}--\r
`),i.close()}})}async _sendMultipartRequest(e,n,r){let o="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=()=>this._createNodeFetchBody(e,o),s=()=>this._createMultipartStream(e,o),a=async l=>this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let c=await l(),u={...this.headers,"Content-Type":`multipart/form-data; boundary=${o}`};r?.apiKey!==void 0&&(u["x-api-key"]=r.apiKey);let d=c;r?.useGzip&&typeof c=="object"&&"pipeThrough"in c&&(d=c.pipeThrough(new CompressionStream("gzip")),u["Content-Encoding"]="gzip");let f=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:u,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(f,"Failed to send multipart request",!0),f});try{let l,c=!1;oUe()&&!this.multipartStreamingDisabled&&hce()!=="bun"?(c=!0,l=await a(s)):l=await a(i),(!this.multipartStreamingDisabled||c)&&l.status===422&&(r?.apiUrl??this.apiUrl)!==zze&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,l=await a(i))}catch(l){if(iue(l))throw l;console.warn(`${l.message.trim()}

Context: ${n}`)}}async updateRun(e,n,r){qn(e),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs));let o={...n,id:e};if(!this._filterForSampling([o],!0).length)return;if(this.autoBatchTracing&&o.trace_id!==void 0&&o.dotted_order!==void 0){let a=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&o.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:o,otelContext:a,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:o,otelContext:a,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};r?.apiKey!==void 0&&(i["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(i["x-tenant-id"]=r.workspaceId);let s=Hu(n,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let a=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(a,"update run",!0),a})}async readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){qn(e);let r=await this._get(`/runs/${e}`);return n&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:n,projectOpts:r}){if(n!==void 0){let o;n.session_id?o=n.session_id:r?.projectName?o=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?o=r?.projectId:o=(await this.readProject({projectName:rs("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${o}/r/${n.id}?poll=true`}else if(e!==void 0){let o=await this.readRun(e);if(!o.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${o.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let n=await nNt(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},o={};n.sort((i,s)=>(i?.dotted_order??"").localeCompare(s?.dotted_order??""));for(let i of n){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in r||(r[i.parent_run_id]=[]),r[i.parent_run_id].push(i),o[i.id]=i)}e.child_runs=r[e.id]||[];for(let i in r)i!==e.id&&(o[i].child_runs=r[i]);return e}async*listRuns(e){let{projectId:n,projectName:r,parentRunId:o,traceId:i,referenceExampleId:s,startTime:a,executionOrder:l,isRoot:c,runType:u,error:d,id:f,query:p,filter:m,traceFilter:h,treeFilter:g,limit:y,select:w,order:v}=e,x=[];if(n&&(x=Array.isArray(n)?n:[n]),r){let S=Array.isArray(r)?r:[r],P=await Promise.all(S.map(A=>this.readProject({projectName:A}).then(O=>O.id)));x.push(...P)}let b=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],_={session:x.length?x:null,run_type:u,reference_example:s,query:p,filter:m,trace_filter:h,tree_filter:g,execution_order:l,parent_run:o,start_time:a?a.toISOString():null,error:d,id:f,limit:y,trace:i,select:w||b,is_root:c,order:v};_.select.includes("child_run_ids")&&tI("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let T=0;for await(let S of this._getCursorPaginatedList("/runs/query",_))if(y){if(T>=y)break;if(S.length+T>y){yield*S.slice(0,y-T);break}T+=S.length,yield*S}else yield*S}async*listGroupRuns(e){let{projectId:n,projectName:r,groupBy:o,filter:i,startTime:s,endTime:a,limit:l,offset:c}=e,d={session_id:n||(await this.readProject({projectName:r})).id,group_by:o,filter:i,start_time:s?s.toISOString():null,end_time:a?a.toISOString():null,limit:Number(l)||100},f=Number(c)||0,p="/runs/group",m=`${this.apiUrl}${p}`;for(;;){let h={...d,offset:f},g=Object.fromEntries(Object.entries(h).filter(([_,T])=>T!==void 0)),y=JSON.stringify(g),v=await(await this.caller.call(async()=>{let _=await this._fetch(m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await zt(_,`Failed to fetch ${p}`),_})).json(),{groups:x,total:b}=v;if(x.length===0)break;for(let _ of x)yield _;if(f+=x.length,f>=b)break}}async getRunStats({id:e,trace:n,parentRun:r,runType:o,projectNames:i,projectIds:s,referenceExampleIds:a,startTime:l,endTime:c,error:u,query:d,filter:f,traceFilter:p,treeFilter:m,isRoot:h,dataSourceType:g}){let y=s||[];i&&(y=[...s||[],...await Promise.all(i.map(T=>this.readProject({projectName:T}).then(S=>S.id)))]);let v=Object.fromEntries(Object.entries({id:e,trace:n,parent_run:r,run_type:o,session:y,reference_example:a,start_time:l,end_time:c,error:u,query:d,filter:f,trace_filter:p,tree_filter:m,is_root:h,data_source_type:g}).filter(([T,S])=>S!==void 0)),x=JSON.stringify(v);return await(await this.caller.call(async()=>{let T=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:x});return await zt(T,"get run stats"),T})).json()}async shareRun(e,{shareId:n}={}){let r={run_id:e,share_token:n||eI()};qn(e);let o=JSON.stringify(r),s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await zt(a,"share run"),a})).json();if(s===null||!("share_token"in s))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${s.share_token}/r`}async unshareRun(e){qn(e),await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(n,"unshare run",!0),n})}async readRunSharedLink(e){qn(e);let r=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(o,"read run shared link"),o})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:n}={}){let r=new URLSearchParams({share_token:e});if(n!==void 0)for(let s of n)r.append("id",s);return qn(e),await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(s,"list shared runs"),s})).json()}async readDatasetSharedSchema(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id),qn(e);let o=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(i,"read dataset shared schema"),i})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async shareDataset(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id);let r={dataset_id:e};qn(e);let o=JSON.stringify(r),s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await zt(a,"share dataset"),a})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async unshareDataset(e){qn(e),await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(n,"unshare dataset",!0),n})}async readSharedDataset(e){return qn(e),await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(o,"read shared dataset"),o})).json()}async listSharedExamples(e,n){let r={};n?.exampleIds&&(r.id=n.exampleIds);let o=new URLSearchParams;Object.entries(r).forEach(([a,l])=>{Array.isArray(l)?l.forEach(c=>o.append(a,c)):o.append(a,l)});let i=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${e}/examples?${o.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(a,"list shared examples"),a}),s=await i.json();if(!i.ok)throw"detail"in s?new Error(`Failed to list shared examples.
Status: ${i.status}
Message: ${Array.isArray(s.detail)?s.detail.join(`
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return s.map(a=>({...a,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:n=null,metadata:r=null,upsert:o=!1,projectExtra:i=null,referenceDatasetId:s=null}){let a=o?"?upsert=true":"",l=`${this.apiUrl}/sessions${a}`,c=i||{};r&&(c.metadata=r);let u={name:e,extra:c,description:n};s!==null&&(u.reference_dataset_id=s);let d=JSON.stringify(u);return await(await this.caller.call(async()=>{let m=await this._fetch(l,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await zt(m,"create project"),m})).json()}async updateProject(e,{name:n=null,description:r=null,metadata:o=null,projectExtra:i=null,endTime:s=null}){let a=`${this.apiUrl}/sessions/${e}`,l=i;o&&(l={...l||{},metadata:o});let c=JSON.stringify({name:n,extra:l,description:r,end_time:s?new Date(s).toISOString():null});return await(await this.caller.call(async()=>{let f=await this._fetch(a,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await zt(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:n}){let r="/sessions",o=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)qn(e),r+=`/${e}`;else if(n!==void 0)o.append("name",n);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${r}?${o}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(s,"has project"),s});try{let s=await i.json();return i.ok?Array.isArray(s)?s.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:n,includeStats:r}){let o="/sessions",i=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)qn(e),o+=`/${e}`;else if(n!==void 0)i.append("name",n);else throw new Error("Must provide projectName or projectId");r!==void 0&&i.append("include_stats",r.toString());let s=await this._get(o,i),a;if(Array.isArray(s)){if(s.length===0)throw new Error(`Project[id=${e}, name=${n}] not found`);a=s[0]}else a=s;return a}async getProjectUrl({projectId:e,projectName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");let r=await this.readProject({projectId:e,projectName:n}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");let r=await this.readDataset({datasetId:e,datasetName:n}),o=await this._getTenantId();return`${this.getHostUrl()}/o/${o}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let n of this._getPaginated("/sessions",e))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:n,nameContains:r,referenceDatasetId:o,referenceDatasetName:i,includeStats:s,datasetVersion:a,referenceFree:l,metadata:c}={}){let u=new URLSearchParams;if(e!==void 0)for(let d of e)u.append("id",d);if(n!==void 0&&u.append("name",n),r!==void 0&&u.append("name_contains",r),o!==void 0)u.append("reference_dataset",o);else if(i!==void 0){let d=await this.readDataset({datasetName:i});u.append("reference_dataset",d.id)}s!==void 0&&u.append("include_stats",s.toString()),a!==void 0&&u.append("dataset_version",a),l!==void 0&&u.append("reference_free",l.toString()),c!==void 0&&u.append("metadata",JSON.stringify(c));for await(let d of this._getPaginated("/sessions",u))yield*d}async deleteProject({projectId:e,projectName:n}){let r;if(e===void 0&&n===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:n})).id:r=e,qn(r),await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(o,`delete session ${r} (${n})`,!0),o})}async uploadCsv({csvFile:e,fileName:n,inputKeys:r,outputKeys:o,description:i,dataType:s,name:a}){let l=`${this.apiUrl}/datasets/upload`,c=new FormData,u=new Blob([e],{type:"text/csv"});return c.append("file",u,n),r.forEach(p=>{c.append("input_keys",p)}),o.forEach(p=>{c.append("output_keys",p)}),i&&c.append("description",i),s&&c.append("data_type",s),a&&c.append("name",a),await(await this.caller.call(async()=>{let p=await this._fetch(l,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await zt(p,"upload CSV"),p})).json()}async createDataset(e,{description:n,dataType:r,inputsSchema:o,outputsSchema:i,metadata:s}={}){let a={name:e,description:n,extra:s?{metadata:s}:void 0};r&&(a.data_type=r),o&&(a.inputs_schema_definition=o),i&&(a.outputs_schema_definition=i);let l=JSON.stringify(a);return await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await zt(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:n}){let r="/datasets",o=new URLSearchParams({limit:"1"});if(e&&n)throw new Error("Must provide either datasetName or datasetId, not both");if(e)qn(e),r+=`/${e}`;else if(n)o.append("name",n);else throw new Error("Must provide datasetName or datasetId");let i=await this._get(r,o),s;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${e}, name=${n}] not found`);s=i[0]}else s=i;return s}async hasDataset({datasetId:e,datasetName:n}){try{return await this.readDataset({datasetId:e,datasetName:n}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:n,fromVersion:r,toVersion:o}){let i=e;if(i===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:n})).id);let s=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof o=="string"?o:o.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,s)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:n}){let r="/datasets";if(e===void 0)if(n!==void 0)e=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(`
`).map(a=>JSON.parse(a))}async*listDatasets({limit:e=100,offset:n=0,datasetIds:r,datasetName:o,datasetNameContains:i,metadata:s}={}){let a="/datasets",l=new URLSearchParams({limit:e.toString(),offset:n.toString()});if(r!==void 0)for(let c of r)l.append("id",c);o!==void 0&&l.append("name",o),i!==void 0&&l.append("name_contains",i),s!==void 0&&l.append("metadata",JSON.stringify(s));for await(let c of this._getPaginated(a,l))yield*c}async updateDataset(e){let{datasetId:n,datasetName:r,...o}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");let i=n??(await this.readDataset({datasetName:r})).id;qn(i);let s=JSON.stringify(o);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:n,datasetName:r,asOf:o,tag:i}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");let s=n??(await this.readDataset({datasetName:r})).id;qn(s);let a=JSON.stringify({as_of:typeof o=="string"?o:o.toISOString(),tag:i});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await zt(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:n}){let r="/datasets",o=e;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(o=(await this.readDataset({datasetName:n})).id),o!==void 0)qn(o),r+=`/${o}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(i,`delete ${r}`,!0),i})}async indexDataset({datasetId:e,datasetName:n,tag:r}){let o=e;if(!o&&!n)throw new Error("Must provide either datasetName or datasetId");if(o&&n)throw new Error("Must provide either datasetName or datasetId, not both");o||(o=(await this.readDataset({datasetName:n})).id),qn(o);let s=JSON.stringify({tag:r});await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${o}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(l,"index dataset"),l})).json()}async similarExamples(e,n,r,{filter:o}={}){let i={limit:r,inputs:e};o!==void 0&&(i.filter=o),qn(n);let s=JSON.stringify(i);return(await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${n}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:s});return await zt(c,"fetch similar examples"),c})).json()).examples}async createExample(e,n,r){if(jze(e)&&(n!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let o=n?r?.datasetId:e.dataset_id,i=n?r?.datasetName:e.dataset_name;if(o===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(o!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");o===void 0&&(o=(await this.readDataset({datasetName:i})).id);let s=(n?r?.createdAt:e.created_at)||new Date,a;jze(e)?a=e:a={inputs:e,outputs:n,created_at:s?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};let l=await this._uploadExamplesMultipart(o,[a]);return await this.readExample(l.example_ids?.[0]??eI())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let w=e,v=w[0].dataset_id,x=w[0].dataset_name;if(v===void 0&&x===void 0)throw new Error("Must provide either datasetName or datasetId");if(v!==void 0&&x!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");v===void 0&&(v=(await this.readDataset({datasetName:x})).id);let b=await this._uploadExamplesMultipart(v,w);return await Promise.all(b.example_ids.map(T=>this.readExample(T)))}let{inputs:n,outputs:r,metadata:o,splits:i,sourceRunIds:s,useSourceRunIOs:a,useSourceRunAttachments:l,attachments:c,exampleIds:u,datasetId:d,datasetName:f}=e;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let p=d,m=f;if(p===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:m})).id);let h=n.map((w,v)=>({dataset_id:p,inputs:w,outputs:r?.[v],metadata:o?.[v],split:i?.[v],id:u?.[v],attachments:c?.[v],source_run_id:s?.[v],use_source_run_io:a?.[v],use_source_run_attachments:l?.[v]})),g=await this._uploadExamplesMultipart(p,h);return await Promise.all(g.example_ids.map(w=>this.readExample(w)))}async createLLMExample(e,n,r){return this.createExample({input:e},{output:n},r)}async createChatExample(e,n,r){let o=e.map(s=>Dce(s)?$ce(s):s),i=Dce(n)?$ce(n):n;return this.createExample({input:o},{output:i},r)}async readExample(e){qn(e);let n=`/examples/${e}`,r=await this._get(n),{attachment_urls:o,...i}=r,s=i;return o&&(s.attachments=Object.entries(o).reduce((a,[l,c])=>(a[l.slice(11)]={presigned_url:c.presigned_url,mime_type:c.mime_type},a),{})),s}async*listExamples({datasetId:e,datasetName:n,exampleIds:r,asOf:o,splits:i,inlineS3Urls:s,metadata:a,limit:l,offset:c,filter:u,includeAttachments:d}={}){let f;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(n!==void 0)f=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide a datasetName or datasetId");let p=new URLSearchParams({dataset:f}),m=o?typeof o=="string"?o:o?.toISOString():void 0;m&&p.append("as_of",m);let h=s??!0;if(p.append("inline_s3_urls",h.toString()),r!==void 0)for(let y of r)p.append("id",y);if(i!==void 0)for(let y of i)p.append("splits",y);if(a!==void 0){let y=JSON.stringify(a);p.append("metadata",y)}l!==void 0&&p.append("limit",l.toString()),c!==void 0&&p.append("offset",c.toString()),u!==void 0&&p.append("filter",u),d===!0&&["attachment_urls","outputs","metadata"].forEach(y=>p.append("select",y));let g=0;for await(let y of this._getPaginated("/examples",p)){for(let w of y){let{attachment_urls:v,...x}=w,b=x;v&&(b.attachments=Object.entries(v).reduce((_,[T,S])=>(_[T.slice(11)]={presigned_url:S.presigned_url,mime_type:S.mime_type||void 0},_),{})),yield b,g++}if(l!==void 0&&g>=l)break}}async deleteExample(e){qn(e);let n=`/examples/${e}`;await this.caller.call(async()=>{let r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(r,`delete ${n}`,!0),r})}async deleteExamples(e,n){if(e.forEach(r=>qn(r)),n?.hardDelete){let r=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${r}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(o,"hard delete examples",!0),o})}else{let r=new URLSearchParams;e.forEach(o=>r.append("example_ids",o)),await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/examples?${r.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(o,"delete examples",!0),o})}}async updateExample(e,n){let r;n?r=e:r=e.id,qn(r);let o;n?o={id:r,...n}:o=e;let i;return o.dataset_id!==void 0?i=o.dataset_id:i=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(i,[o])}async updateExamples(e){let n;return e[0].dataset_id===void 0?n=(await this.readExample(e[0].id)).dataset_id:n=e[0].dataset_id,this._updateExamplesMultipart(n,e)}async readDatasetVersion({datasetId:e,datasetName:n,asOf:r,tag:o}){let i;if(e?i=e:i=(await this.readDataset({datasetName:n})).id,qn(i),r&&o||!r&&!o)throw new Error("Exactly one of asOf and tag must be specified.");let s=new URLSearchParams;return r!==void 0&&s.append("as_of",typeof r=="string"?r:r.toISOString()),o!==void 0&&s.append("tag",o),await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${s.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(l,"read dataset version"),l})).json()}async listDatasetSplits({datasetId:e,datasetName:n,asOf:r}){let o;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?o=(await this.readDataset({datasetName:n})).id:o=e,qn(o);let i=new URLSearchParams,s=r?typeof r=="string"?r:r?.toISOString():void 0;return s&&i.append("as_of",s),await this._get(`/datasets/${o}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:n,splitName:r,exampleIds:o,remove:i=!1}){let s;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:n})).id:s=e,qn(s);let a={split_name:r,examples:o.map(c=>(qn(c),c)),remove:i},l=JSON.stringify(a);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${s}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await zt(c,"update dataset splits",!0),c})}async createFeedback(e,n,{score:r,value:o,correction:i,comment:s,sourceInfo:a,feedbackSourceType:l="api",sourceRunId:c,feedbackId:u,feedbackConfig:d,projectId:f,comparativeExperimentId:p,sessionId:m,startTime:h}){if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");let g={type:l??"api",metadata:a??{}};c!==void 0&&g?.metadata!==void 0&&!g.metadata.__run&&(g.metadata.__run={run_id:c}),g?.metadata!==void 0&&g.metadata.__run?.run_id!==void 0&&qn(g.metadata.__run.run_id);let y={id:u??eI(),run_id:e,key:n,score:Bze(r),value:o,correction:i,comment:s,feedback_source:g,comparative_experiment_id:p,feedbackConfig:d,session_id:m??f,start_time:h},w=JSON.stringify(y),v=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let x=await this._fetch(v,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:w});return await zt(x,"create feedback",!0),x}),y}async updateFeedback(e,{score:n,value:r,correction:o,comment:i}){let s={};n!=null&&(s.score=Bze(n)),r!=null&&(s.value=r),o!=null&&(s.correction=o),i!=null&&(s.comment=i),qn(e);let a=JSON.stringify(s);await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await zt(l,"update feedback",!0),l})}async readFeedback(e){qn(e);let n=`/feedback/${e}`;return await this._get(n)}async deleteFeedback(e){qn(e);let n=`/feedback/${e}`;await this.caller.call(async()=>{let r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(r,`delete ${n}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:n,feedbackSourceTypes:r}={}){let o=new URLSearchParams;if(e)for(let i of e)qn(i),o.append("run",i);if(n)for(let i of n)o.append("key",i);if(r)for(let i of r)o.append("source",i);for await(let i of this._getPaginated("/feedback",o))yield*i}async createPresignedFeedbackToken(e,n,{expiration:r,feedbackConfig:o}={}){let i={run_id:e,feedback_key:n,feedback_config:o};r?typeof r=="string"?i.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(i.expires_in=r):i.expires_in={hours:3};let s=JSON.stringify(i);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(l,"create presigned feedback token"),l})).json()}async createComparativeExperiment({name:e,experimentIds:n,referenceDatasetId:r,createdAt:o,description:i,metadata:s,id:a}){if(n.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:n[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");let l={id:a,name:e,experiment_ids:n,reference_dataset_id:r,description:i,created_at:(o??new Date)?.toISOString(),extra:{}};s&&(l.extra.metadata=s);let c=JSON.stringify(l);return(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await zt(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){qn(e);let n=new URLSearchParams({run_id:e});for await(let r of this._getPaginated("/feedback/tokens",n))yield*r}_selectEvalResults(e){let n;return"results"in e?n=e.results:Array.isArray(e)?n=e:n=[e],n}async _logEvaluationFeedback(e,n,r){let o=this._selectEvalResults(e),i=[];for(let s of o){let a=r||{};s.evaluatorInfo&&(a={...s.evaluatorInfo,...a});let l=null;s.targetRunId?l=s.targetRunId:n&&(l=n.id),i.push(await this.createFeedback(l,s.key,{score:s.score,value:s.value,comment:s.comment,correction:s.correction,sourceInfo:a,sourceRunId:s.sourceRunId,feedbackConfig:s.feedbackConfig,feedbackSourceType:"model",sessionId:n?.session_id,startTime:n?.start_time}))}return[o,i]}async logEvaluationFeedback(e,n,r){let[o]=await this._logEvaluationFeedback(e,n,r);return o}async createFeedbackConfig(e){let{feedbackKey:n,feedbackConfig:r,isLowerScoreBetter:o=!1}=e,i={feedback_key:n,feedback_config:r,is_lower_score_better:o};return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await zt(a,"create feedback config"),a})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:n,nameContains:r,limit:o}=e,i=new URLSearchParams;n&&n.forEach(a=>{i.append("key",a)}),r&&i.append("name_contains",r),i.append("limit",(o!==void 0?Math.min(o,100):100).toString());let s=0;for await(let a of this._getPaginated("/feedback-configs",i))if(yield*a,s+=a.length,o!==void 0&&s>=o)break}async updateFeedbackConfig(e,n={}){let{feedbackConfig:r,isLowerScoreBetter:o}=n,i={feedback_key:e};return r!==void 0&&(i.feedback_config=r),o!==void 0&&(i.is_lower_score_better=o),(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await zt(a,"update feedback config"),a})).json()}async deleteFeedbackConfig(e){let n=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/feedback-configs?${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(r,"delete feedback config",!0),r})}async*listAnnotationQueues(e={}){let{queueIds:n,name:r,nameContains:o,limit:i}=e,s=new URLSearchParams;n&&n.forEach((l,c)=>{qn(l,`queueIds[${c}]`),s.append("ids",l)}),r&&s.append("name",r),o&&s.append("name_contains",o),s.append("limit",(i!==void 0?Math.min(i,100):100).toString());let a=0;for await(let l of this._getPaginated("/annotation-queues",s))if(yield*l,a++,i!==void 0&&a>=i)break}async createAnnotationQueue(e){let{name:n,description:r,queueId:o,rubricInstructions:i,rubricItems:s}=e,a={name:n,description:r,id:o||eI(),rubric_instructions:i,rubric_items:s},l=JSON.stringify(Object.fromEntries(Object.entries(a).filter(([u,d])=>d!==void 0)));return(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await zt(u,"create annotation queue"),u})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${qn(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,n){let{name:r,description:o,rubricInstructions:i,rubricItems:s}=n,a={};r!==void 0&&(a.name=r),o!==void 0&&(a.description=o),i!==void 0&&(a.rubric_instructions=i),s!==void 0&&(a.rubric_items=s);let l=JSON.stringify(a);await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/annotation-queues/${qn(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await zt(c,"update annotation queue",!0),c})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${qn(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(n,"delete annotation queue",!0),n})}async addRunsToAnnotationQueue(e,n){let r=JSON.stringify(n.map((o,i)=>qn(o,`runIds[${i}]`).toString()));await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/annotation-queues/${qn(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await zt(o,"add runs to annotation queue",!0),o})}async getRunFromAnnotationQueue(e,n){let r=`/annotation-queues/${qn(e,"queueId")}/run`;return(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(i,"get run from annotation queue"),i})).json()}async deleteRunFromAnnotationQueue(e,n){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${qn(e,"queueId")}/runs/${qn(n,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${qn(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){let n=await this._getSettings();return e=="-"||n.tenant_handle===e}async _ownerConflictError(e,n){let r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.

      Current tenant: ${r.tenant_handle}

      Requested tenant: ${n}`)}async _getLatestCommitHash(e){let r=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(o,"get latest commit hash"),o})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,n){let[r,o,i]=Ow(e),s=JSON.stringify({like:n});return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/likes/${r}/${o}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(l,`${n?"like":"unlike"} prompt`),l})).json()}async _getPromptUrl(e){let[n,r,o]=Ow(e);if(await this._currentTenantIsOwner(n)){let i=await this._getSettings();return o!=="latest"?`${this.getHostUrl()}/prompts/${r}/${o.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${i.id}`}else return o!=="latest"?`${this.getHostUrl()}/hub/${n}/${r}/${o.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){for await(let n of this._getPaginated(`/commits/${e}/`,new URLSearchParams,r=>r.commits))yield*n}async*listPrompts(e){let n=new URLSearchParams;n.append("sort_field",e?.sortField??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&n.append("is_public",e.isPublic.toString()),e?.query&&n.append("query",e.query);for await(let r of this._getPaginated("/repos",n,o=>o.repos))yield*r}async getPrompt(e){let[n,r,o]=Ow(e),s=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return a?.status===404?null:(await zt(a,"get prompt"),a)}))?.json();return s?.repo?s.repo:null}async createPrompt(e,n){let r=await this._getSettings();if(n?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first

        creating a LangChain Hub handle.
        You can add a handle by creating a public prompt at:

        https://smith.langchain.com/prompts`);let[o,i,s]=Ow(e);if(!await this._currentTenantIsOwner(o))throw await this._ownerConflictError("create a prompt",o);let a={repo_handle:i,...n?.description&&{description:n.description},...n?.readme&&{readme:n.readme},...n?.tags&&{tags:n.tags},is_public:!!n?.isPublic},l=JSON.stringify(a),c=await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await zt(d,"create prompt"),d}),{repo:u}=await c.json();return u}async createCommit(e,n,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[o,i,s]=Ow(e),a=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${o}/${i}`):r?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(n)),parent_commit:a},c=JSON.stringify(l),d=await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/commits/${o}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await zt(f,"create commit"),f})).json();return this._getPromptUrl(`${o}/${i}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,n=[]){return this._updateExamplesMultipart(e,n)}async _updateExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let s of n){let a=s.id,l={...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split}},c=Hu(l,`Serializing body for example with id: ${a}`),u=new Blob([c],{type:"application/json"});if(r.append(a,u),s.inputs){let d=Hu(s.inputs,`Serializing inputs for example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.inputs`,f)}if(s.outputs){let d=Hu(s.outputs,`Serializing outputs whle updating example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.outputs`,f)}if(s.attachments)for(let[d,f]of Object.entries(s.attachments)){let p,m;Array.isArray(f)?[p,m]=f:(p=f.mimeType,m=f.data);let h=new Blob([m],{type:`${p}; length=${m.byteLength}`});r.append(`${a}.attachment.${d}`,h)}if(s.attachments_operations){let d=Hu(s.attachments_operations,`Serializing attachments while updating example with id: ${a}`),f=new Blob([d],{type:"application/json"});r.append(`${a}.attachments_operations`,f)}}let o=e??n[0]?.dataset_id;return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${o}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await zt(s,"update examples"),s})).json()}async uploadExamplesMultipart(e,n=[]){return this._uploadExamplesMultipart(e,n)}async _uploadExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");let r=new FormData;for(let i of n){let s=(i.id??eI()).toString(),a={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},l=Hu(a,`Serializing body for uploaded example with id: ${s}`),c=new Blob([l],{type:"application/json"});if(r.append(s,c),i.inputs){let u=Hu(i.inputs,`Serializing inputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});r.append(`${s}.inputs`,d)}if(i.outputs){let u=Hu(i.outputs,`Serializing outputs for uploaded example with id: ${s}`),d=new Blob([u],{type:"application/json"});r.append(`${s}.outputs`,d)}if(i.attachments)for(let[u,d]of Object.entries(i.attachments)){let f,p;Array.isArray(d)?[f,p]=d:(f=d.mimeType,p=d.data);let m=new Blob([p],{type:`${f}; length=${p.byteLength}`});r.append(`${s}.attachment.${u}`,m)}}return(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await zt(i,"upload examples"),i})).json()}async updatePrompt(e,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,o]=Ow(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);let i={};if(n?.description!==void 0&&(i.description=n.description),n?.readme!==void 0&&(i.readme=n.readme),n?.tags!==void 0&&(i.tags=n.tags),n?.isPublic!==void 0&&(i.is_public=n.isPublic),n?.isArchived!==void 0&&(i.is_archived=n.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let s=JSON.stringify(i);return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${r}/${o}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await zt(l,"update prompt"),l})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,r,o]=Ow(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(s,"delete prompt"),s})).json()}_getPromptCacheKey(e,n){return`${e}${n?":with_model":""}`}async _fetchPromptFromApi(e,n){let[r,o,i]=Ow(e),a=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/commits/${r}/${o}/${i}${n?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await zt(l,"pull prompt commit"),l})).json();return{owner:r,repo:o,commit_hash:a.commit_hash,manifest:a.manifest,examples:a.examples}}async pullPromptCommit(e,n){let r=this._fetchPromptFromApi.bind(this,e,n);if(!n?.skipCache&&this._promptCache){let o=this._getPromptCacheKey(e,n?.includeModel),i=this._promptCache.get(o,r);if(i)return i;let s=await r();return this._promptCache.set(o,s,r),s}return this._fetchPromptFromApi(e,n)}async _pullPrompt(e,n){let r=await this.pullPromptCommit(e,{includeModel:n?.includeModel,skipCache:n?.skipCache});return JSON.stringify(r.manifest)}async pushPrompt(e,n){return await this.promptExists(e)?n&&Object.keys(n).some(o=>o!=="object")&&await this.updatePrompt(e,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}):await this.createPrompt(e,{description:n?.description,readme:n?.readme,tags:n?.tags,isPublic:n?.isPublic}),n?.object?await this.createCommit(e,n?.object,{parentCommitHash:n?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,n={}){let{sourceApiUrl:r=this.apiUrl,datasetName:o}=n,[i,s]=this.parseTokenOrUrl(e,r),a=new t({apiUrl:i,apiKey:"placeholder"}),l=await a.readSharedDataset(s),c=o||l.name;try{if(await this.hasDataset({datasetId:c})){console.log(`Dataset ${c} already exists in your tenant. Skipping.`);return}}catch{}let u=await a.listSharedExamples(s),d=await this.createDataset(c,{description:l.description,dataType:l.data_type||"kv",inputsSchema:l.inputs_schema_definition??void 0,outputsSchema:l.outputs_schema_definition??void 0});try{await this.createExamples({inputs:u.map(f=>f.inputs),outputs:u.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),f}}parseTokenOrUrl(e,n,r=2,o="dataset"){try{return qn(e),[n,e]}catch{}try{let s=new URL(e).pathname.split("/").filter(a=>a!=="");if(s.length>=r){let a=s[s.length-r];return[n,a]}else throw new Error(`Invalid public ${o} URL: ${e}`)}catch{throw new Error(`Invalid public ${o} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();await new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await PUe()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}});var Wze,Hze=C(()=>{Mw();Wze=t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(n=>rs(n)==="true")});var kg,MTn,NK,uue=C(()=>{kg=Symbol.for("lc:context_variables"),MTn=Symbol.for("lc:child_run_end_promises"),NK=Symbol.for("langsmith:replica_trace_roots")});function due(t,e){if(kg in t)return t[kg][e]}function Kze(t,e,n){let r=kg in t?t[kg]:{};r[e]=n,t[kg]=r}var qze=C(()=>{uue()});function Gze(t){let n=Object.keys(t).sort().map(r=>`${r}:${t[r]??""}`).join("|");return Jle(n,aNt)}function lNt(t){return t.replace(/[-:.]/g,"")}function Zze(t,e=1){let n=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${n}Z`}function fue(t,e,n=1){let r=Zze(t,n);return{dottedOrder:lNt(r)+e,microsecondPrecisionDatestring:r}}function uNt(t){let e={};for(let n of Object.keys(t))cNt.has(n)&&(e[n]=t[n]);return e}function Jze(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function Xze(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function Yze(t){return Array.isArray(t)&&t.some(e=>Xze(e))}function dNt(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function fNt(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(Yze(e?.handlers)||Yze(e))}function pNt(){let t=Hd("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let n=[];for(let r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}n.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return n}else if(typeof e=="object"&&e!==null){hNt(e);let n=[];for(let[r,o]of Object.entries(e)){let i=r.replace(/\/$/,"");if(typeof o=="string")n.push({apiUrl:i,apiKey:o});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof o}`);continue}}return n}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(Lze(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function mNt(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):pNt()}function hNt(t){if(Object.keys(t).length>0&&rs("ENDPOINT"))throw new EK}var V2,aNt,cNt,OK,Fm,fce=C(()=>{dce();Hze();sue();uue();qze();Mw();ice();Mw();G3();tK();q3();V2=36,aNt="6ba7b810-9dad-11d1-80b4-00c04fd430c8";cNt=new Set(["projectName","updates","reroot"]);OK=class t{constructor(e,n,r,o){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=n,this.project_name=r,this.replicas=o}static fromHeader(e){let n=e.split(","),r={},o=[],i,s;for(let a of n){let[l,c]=a.split("="),u=decodeURIComponent(c);l==="langsmith-metadata"?r=JSON.parse(u):l==="langsmith-tags"?o=u.split(","):l==="langsmith-project"?i=u:l==="langsmith-replicas"&&(s=JSON.parse(u).map(f=>Array.isArray(f)?f:uNt(f)))}return new t(r,o,i,s)}toHeader(){let e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}},Fm=class t{constructor(e){if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Jze(e)){Object.assign(this,{...e});return}let n=t.getDefaultConfig(),{metadata:r,...o}=e,i=o.client??t.getSharedClient(),s={...r,...o?.extra?.metadata};if(o.extra={...o.extra,metadata:s},"id"in o&&o.id==null&&delete o.id,Object.assign(this,{...n,...o,client:i}),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),this.dotted_order||(this._serialized_start_time=Zze(this.start_time,this.execution_order)),this.id||(this.id=eK(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=mNt(this.replicas),!this.dotted_order){let{dottedOrder:a}=fue(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+a:this.dotted_order=a}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:N2(),child_runs:[],api_url:Hd("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Hd("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new rI),t.sharedClient}createChild(e){let n=this.child_execution_order+1,r=this.replicas?.map(u=>{let{reroot:d,...f}=u;return f}),o=e.replicas??r,i=new t({...e,parent_run:this,project_name:this.project_name,replicas:o,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n});kg in this&&(i[kg]=this[kg]);let s=Symbol.for("lc:child_config"),a=e.extra?.[s]??this.extra[s];if(fNt(a)){let u={...a},d=dNt(u.callbacks)?u.callbacks.copy?.():void 0;d&&(Object.assign(d,{_parentRunId:i.id}),d.handlers?.find(Xze)?.updateFromRunTree?.(i),u.callbacks=d),i.extra[s]=u}let l=new Set,c=this;for(;c!=null&&!l.has(c.id);)l.add(c.id),c.child_execution_order=Math.max(c.child_execution_order,n),c=c.parent_run;return this.child_runs.push(i),i}async end(e,n,r=Date.now(),o){this.outputs=this.outputs??e,this.error=this.error??n,this.end_time=this.end_time??r,o&&Object.keys(o).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...o}}:{metadata:o})}_convertToCreate(e,n,r=!0){let o=e.extra??{};if(o?.runtime?.library===void 0&&(o.runtime||(o.runtime={}),n))for(let[a,l]of Object.entries(n))o.runtime[a]||(o.runtime[a]=l);let i,s;return r?(s=e.parent_run?.id??e.parent_run_id,i=[]):(i=e.child_runs.map(a=>this._convertToCreate(a,n,r)),s=void 0),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:o,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:i,parent_run_id:s,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,n){if(n.dotted_order){let r=n.dotted_order.split("."),o=null;for(let i=0;i<r.length;i++)if(r[i].slice(-V2)===e){o=i;break}if(o!==null){let i=r.slice(o+1);n.dotted_order=i.join("."),i.length>0?n.trace_id=i[0].slice(-V2):n.trace_id=n.id}}n.parent_run_id===e&&(n.parent_run_id=void 0)}_setReplicaTraceRoot(e,n){let r=due(this,NK)??{};r[e]=n,Kze(this,NK,r);for(let o of this.child_runs)o._setReplicaTraceRoot(e,n)}_remapForProject(e){let{projectName:n,runtimeEnv:r,excludeChildRuns:o=!0,reroot:i=!1,distributedParentId:s,apiUrl:a,apiKey:l,workspaceId:c}=e,u=this._convertToCreate(this,r,o);if(n===this.project_name)return{...u,session_name:n};if(i){if(s)this._sliceParentId(s,u);else if(u.parent_run_id=void 0,u.dotted_order){let w=u.dotted_order.split(".");w.length>0&&(u.dotted_order=w[w.length-1],u.trace_id=u.id)}let y=Gze({projectName:n,apiUrl:a,apiKey:l,workspaceId:c});this._setReplicaTraceRoot(y,u.id)}let d;if(!i){let y=due(this,NK)??{},w=Gze({projectName:n,apiUrl:a,apiKey:l,workspaceId:c});if(d=y[w],d&&(u.trace_id=d,u.dotted_order)){let v=u.dotted_order.split("."),x=null;for(let b=0;b<v.length;b++)if(v[b].slice(-V2)===d){x=b;break}if(x!==null){let b=v.slice(x);u.dotted_order=b.join(".")}}}let f=u.id,p=O2(f,n),m;u.trace_id?m=O2(u.trace_id,n):m=p;let h;u.parent_run_id&&(h=O2(u.parent_run_id,n));let g;return u.dotted_order&&(g=u.dotted_order.split(".").map(v=>{let x=v.slice(-V2),b=O2(x,n);return v.slice(0,-V2)+b}).join(".")),{...u,id:p,trace_id:m,parent_run_id:h,dotted_order:g,session_name:n}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let n=sK();if(this.replicas&&this.replicas.length>0)for(let{projectName:r,apiKey:o,apiUrl:i,workspaceId:s,reroot:a}of this.replicas){let l=this._remapForProject({projectName:r??this.project_name,runtimeEnv:n,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:o,workspaceId:s});await this.client.createRun(l,{apiKey:o,apiUrl:i,workspaceId:s})}else{let r=this._convertToCreate(this,n,e);await this.client.createRun(r)}if(!e){tI("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let r of this.child_runs)await r.postRun(!1)}this.child_runs=[]}catch(n){console.error(`Error in postRun for run ${this.id}:`,n)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:r,apiUrl:o,workspaceId:i,updates:s,reroot:a}of this.replicas){let l=this._remapForProject({projectName:n??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:a,distributedParentId:this.distributedParentId,apiUrl:o,apiKey:r,workspaceId:i}),c={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...s};e?.excludeInputs||(c.inputs=l.inputs),await this.client.updateRun(l.id,c,{apiKey:r,apiUrl:o,workspaceId:i})}else try{let n={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.id??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e?.excludeInputs||(n.inputs=this.inputs),await this.client.updateRun(this.id,n)}catch(n){console.error(`Error in patchRun for run ${this.id}`,n)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,n){let r=e?.callbacks,o,i,s,a=Wze();if(r){let c=r?.getParentRunId?.()??"",u=r?.handlers?.find(d=>d?.name=="langchain_tracer");o=u?.getRun?.(c),i=u?.projectName,s=u?.client,a=a||!!u}return o?new t({name:o.name,id:o.id,trace_id:o.trace_id,dotted_order:o.dotted_order,client:s,tracingEnabled:a,project_name:i,tags:[...new Set((o?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...o?.extra?.metadata,...e?.metadata}}}).createChild(n):new t({...n,client:s,tracingEnabled:a,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,n){let r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,o=r["langsmith-trace"];if(!o||typeof o!="string")return;let i=o.trim(),s=i.split(".").map(u=>{let[d,f]=u.split("Z");return{strTime:d,time:Date.parse(d+"Z"),uuid:f}}),a=s[0].uuid,l={...n,name:n?.name??"parent",run_type:n?.run_type??"chain",start_time:n?.start_time??Date.now(),id:s.at(-1)?.uuid,trace_id:a,dotted_order:i};if(r.baggage&&typeof r.baggage=="string"){let u=OK.fromHeader(r.baggage);l.metadata=u.metadata,l.tags=u.tags,l.project_name=u.project_name,l.replicas=u.replicas}let c=new t(l);return c.distributedParentId=c.id,c}toHeaders(e){let n={"langsmith-trace":this.dotted_order,baggage:new OK(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[r,o]of Object.entries(n))e.set(r,o);return n}};Object.defineProperty(Fm,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null})});var RK=C(()=>{fce()});function mue(t,e){if(t)return new Fm({...t,start_time:t._serialized_start_time??t.start_time,parent_run:mue(e),child_runs:t.child_runs.map(n=>mue(n)).filter(n=>n!==void 0),extra:{...t.extra,runtime:u2e()},tracingEnabled:!1})}function pue(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function tM(t){return typeof t._addRunToRunMap=="function"}var gNt,Mg,iI=C(()=>{$n();Jo();k2();RK();gNt=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};Mg=class extends Gk{constructor(e){super(...arguments);I(this,"runMap",new Map);I(this,"runTreeMap",new Map);I(this,"usesRunTreeMap",!1)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?gNt(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`

${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,n){e.child_runs.push(n)}_addRunToRunMap(e){let{dottedOrder:n,microsecondPrecisionDatestring:r}=fue(new Date(e.start_time).getTime(),e.id,e.execution_order),o={...e},i=this.getRunById(o.parent_run_id);if(o.parent_run_id!==void 0?i?(this._addChildRun(i,o),i.child_execution_order=Math.max(i.child_execution_order,o.child_execution_order),o.trace_id=i.trace_id,i.dotted_order!==void 0&&(o.dotted_order=[i.dotted_order,n].join("."),o._serialized_start_time=r)):o.parent_run_id=void 0:(o.trace_id=o.id,o.dotted_order=n,o._serialized_start_time=r),this.usesRunTreeMap){let s=mue(o,i);s!==void 0&&this.runTreeMap.set(o.id,s)}else this.runMap.set(o.id,o);return o}async _endTrace(e){let n=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);n?n.child_execution_order=Math.max(n.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){let n=e!==void 0&&this.getRunById(e);return n?n.child_execution_order+1:1}_createRunForLLMStart(e,n,r,o,i,s,a,l){let c=this._getExecutionOrder(o),u=Date.now(),d=a?{...i,metadata:a}:i,f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:n},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForLLMStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,n,r,o,i,s,a,l){let c=this._getExecutionOrder(o),u=Date.now(),d=a?{...i,metadata:a}:i,f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:u,serialized:e,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:n},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForChatModelStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,n,r,o,i){let s=this.getRunById(n);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=e,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(e,n,r,o,i){let s=this.getRunById(n);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(e,n,r,o,i,s,a,l,c){let u=this._getExecutionOrder(o),d=Date.now(),f={id:r,name:l??e.id[e.id.length-1],parent_run_id:o,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:n,execution_order:u,child_execution_order:u,run_type:a??"chain",child_runs:[],extra:s?{...c,metadata:s}:{...c},tags:i||[]};return this._addRunToRunMap(f)}async handleChainStart(e,n,r,o,i,s,a,l){let c=this.getRunById(r)??this._createRunForChainStart(e,n,r,o,i,s,a,l);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,n,r,o,i){let s=this.getRunById(n);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=pue(e,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=pue(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(e,n,r,o,i){let s=this.getRunById(n);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(e),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=pue(i.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(e,n,r,o,i,s,a){let l=this._getExecutionOrder(o),c=Date.now(),u={id:r,name:a??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:n},execution_order:l,child_execution_order:l,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(e,n,r,o,i,s,a){let l=this.getRunById(r)??this._createRunForToolStart(e,n,r,o,i,s,a);return await this.onRunCreate?.(l),await this.onToolStart?.(l),l}async handleToolEnd(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="chain")return;let o=r;o.actions=o.actions||[],o.actions.push(e),o.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,n){let r=this.getRunById(n);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,n,r,o,i,s,a){let l=this._getExecutionOrder(o),c=Date.now(),u={id:r,name:a??e.id[e.id.length-1],parent_run_id:o,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:n},execution_order:l,child_execution_order:l,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(e,n,r,o,i,s,a){let l=this.getRunById(r)??this._createRunForRetrieverStart(e,n,r,o,i,s,a);return await this.onRunCreate?.(l),await this.onRetrieverStart?.(l),l}async handleRetrieverEnd(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,n){let r=this.getRunById(n);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,n){let r=this.getRunById(n);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,n,r,o,i,s){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:n,chunk:s?.chunk}}),await this.onLLMNewToken?.(a,e,{chunk:s?.chunk}),a}}});function Hc(t,e){return`${t.open}${e}${t.close}`}function ap(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function Qze(t){return typeof t=="string"?t.trim():t==null?t:ap(t,t.toString())}function Vb(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}var eje,Ku,hue,tje=C(()=>{$n();iI();eje={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};({color:Ku}=eje),hue=class extends Mg{constructor(){super(...arguments);I(this,"name","console_callback_handler")}persistRun(e){return Promise.resolve()}getParents(e){let n=[],r=e;for(;r.parent_run_id;){let o=this.runMap.get(r.parent_run_id);if(o)n.push(o),r=o;else break}return n}getBreadcrumbs(e){let n=[...this.getParents(e).reverse(),e].map((r,o,i)=>{let s=`${r.execution_order}:${r.run_type}:${r.name}`;return o===i.length-1?Hc(eje.bold,s):s}).join(" > ");return Hc(Ku.grey,n)}onChainStart(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.green,"[chain/start]")} [${n}] Entering Chain run with input: ${ap(e.inputs,"[inputs]")}`)}onChainEnd(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.cyan,"[chain/end]")} [${n}] [${Vb(e)}] Exiting Chain run with output: ${ap(e.outputs,"[outputs]")}`)}onChainError(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.red,"[chain/error]")} [${n}] [${Vb(e)}] Chain run errored with error: ${ap(e.error,"[error]")}`)}onLLMStart(e){let n=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(o=>o.trim())}:e.inputs;console.log(`${Hc(Ku.green,"[llm/start]")} [${n}] Entering LLM run with input: ${ap(r,"[inputs]")}`)}onLLMEnd(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.cyan,"[llm/end]")} [${n}] [${Vb(e)}] Exiting LLM run with output: ${ap(e.outputs,"[response]")}`)}onLLMError(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.red,"[llm/error]")} [${n}] [${Vb(e)}] LLM run errored with error: ${ap(e.error,"[error]")}`)}onToolStart(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.green,"[tool/start]")} [${n}] Entering Tool run with input: "${Qze(e.inputs.input)}"`)}onToolEnd(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.cyan,"[tool/end]")} [${n}] [${Vb(e)}] Exiting Tool run with output: "${Qze(e.outputs?.output)}"`)}onToolError(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.red,"[tool/error]")} [${n}] [${Vb(e)}] Tool run errored with error: ${ap(e.error,"[error]")}`)}onRetrieverStart(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.green,"[retriever/start]")} [${n}] Entering Retriever run with input: ${ap(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.cyan,"[retriever/end]")} [${n}] [${Vb(e)}] Exiting Retriever run with output: ${ap(e.outputs,"[outputs]")}`)}onRetrieverError(e){let n=this.getBreadcrumbs(e);console.log(`${Hc(Ku.red,"[retriever/error]")} [${n}] [${Vb(e)}] Retriever run errored with error: ${ap(e.error,"[error]")}`)}onAgentAction(e){let n=e,r=this.getBreadcrumbs(e);console.log(`${Hc(Ku.blue,"[agent/action]")} [${r}] Agent selected action: ${ap(n.actions[n.actions.length-1],"[action]")}`)}}});var LK=C(()=>{iK()});var gue,yue,wue=C(()=>{Jo();LK();yue=()=>(gue===void 0&&(gue=new rI(In("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),gue)});function nje(t=!1){let e=wNt.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.

Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function DK(t){return typeof t=="function"&&"langsmith:traceable"in t}var xue,vue,yNt,bue,wNt,fIn,rje=C(()=>{xue=class{getStore(){}run(e,n){return n()}},vue=Symbol.for("ls:tracing_async_local_storage"),yNt=new xue,bue=class{getInstance(){return globalThis[vue]??yNt}initializeGlobalInstance(e){globalThis[vue]===void 0&&(globalThis[vue]=e)}},wNt=new bue;fIn=Symbol.for("langsmith:traceable:root")});var Cue=C(()=>{rje()});function vNt(t){let e;for(let n of t)for(let r of n)kn.isInstance(r.message)&&r.message.usage_metadata!==void 0&&(e=_2(e,r.message.usage_metadata));return e}function oje(t,e){if(t.tracingMetadata){e.extra??(e.extra={});let n=e.extra.metadata??{},r=!1;for(let[o,i]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(n,o)||ije.has(o))&&n[o]!==i&&(n[o]=i,r=!0);r&&(e.extra.metadata=n)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}var ije,W2,sje=C(()=>{$n();R3();Wu();iI();wue();RK();LK();Cue();ije=new Set(["ls_agent_type"]);W2=class _ue extends Mg{constructor(n={}){super(n);I(this,"name","langchain_tracer");I(this,"projectName");I(this,"exampleId");I(this,"client");I(this,"replicas");I(this,"usesRunTreeMap",!0);I(this,"tracingMetadata");I(this,"tracingTags",[]);this.fields=n;let{exampleId:r,projectName:o,client:i,replicas:s,metadata:a,tags:l}=n;this.projectName=o??N2(),this.replicas=s,this.exampleId=r,this.client=i??yue(),this.tracingMetadata=a?{...a}:void 0,this.tracingTags=l??[];let c=_ue.getTraceableRunTree();c&&this.updateFromRunTree(c)}async persistRun(n){}async onRunCreate(n){oje(this,n),n.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(n.id)?.postRun()}async onRunUpdate(n){oje(this,n);let r=this.getRunTreeWithTracingConfig(n.id);n.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(n){let r=n.outputs;if(r?.generations){let o=vNt(r.generations);if(o!==void 0){n.extra=n.extra??{};let i=n.extra.metadata??{};i.usage_metadata=o,n.extra.metadata=i}}}copyWithTracingConfig({metadata:n,tags:r}){let o;if(n===void 0)o=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)o={...n};else{o={...this.tracingMetadata};for(let[a,l]of Object.entries(n))(!Object.prototype.hasOwnProperty.call(o,a)||ije.has(a))&&(o[a]=l)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],s=new _ue({...this.fields,metadata:o,tags:i});return s.runMap=this.runMap,s.runTreeMap=this.runTreeMap,s}getRun(n){return this.runTreeMap.get(n)}updateFromRunTree(n){this.runTreeMap.set(n.id,n);let r=n,o=new Set;for(;r.parent_run&&!(o.has(r.id)||(o.add(r.id),!r.parent_run));)r=r.parent_run;o.clear();let i=[r];for(;i.length>0;){let s=i.shift();!s||o.has(s.id)||(o.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&i.push(...s.child_runs))}this.client=n.client??this.client,this.replicas=n.replicas??this.replicas,this.projectName=n.project_name??this.projectName,this.exampleId=n.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(n){let r=this.runTreeMap.get(n);if(r)return new Fm({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return nje(!0)}catch{return}}static[Symbol.hasInstance](n){if(typeof n!="object"||n===null)return!1;let r=n;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}}});var lje=Tt((IIn,FK)=>{"use strict";var xNt=kce(),$K=class extends Error{constructor(e){super(e),this.name="TimeoutError"}},aje=(t,e,n)=>new Promise((r,o)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){r(t);return}let i=setTimeout(()=>{if(typeof n=="function"){try{r(n())}catch(l){o(l)}return}let s=typeof n=="string"?n:`Promise timed out after ${e} milliseconds`,a=n instanceof Error?n:new $K(s);typeof t.cancel=="function"&&t.cancel(),o(a)},e);xNt(t.then(r,o),()=>{clearTimeout(i)})});FK.exports=aje;FK.exports.default=aje;FK.exports.TimeoutError=$K});var cje=Tt(Sue=>{"use strict";Object.defineProperty(Sue,"__esModule",{value:!0});function bNt(t,e,n){let r=0,o=t.length;for(;o>0;){let i=o/2|0,s=r+i;n(t[s],e)<=0?(r=++s,o-=i+1):o=i}return r}Sue.default=bNt});var uje=Tt(Iue=>{"use strict";Object.defineProperty(Iue,"__esModule",{value:!0});var CNt=cje(),Tue=class{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);let r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}let o=CNt.default(this._queue,r,(i,s)=>s.priority-i.priority);this._queue.splice(o,0,r)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this._queue.length}};Iue.default=Tue});var Aue=Tt(Eue=>{"use strict";Object.defineProperty(Eue,"__esModule",{value:!0});var _Nt=Ace(),dje=lje(),SNt=uje(),UK=()=>{},TNt=new dje.TimeoutError,Pue=class extends _Nt{constructor(e){var n,r,o,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=UK,this._resolveIdle=UK,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:SNt.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(n=e.intervalCap)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(o=e.interval)===null||o===void 0?void 0:o.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=UK,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=UK,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let n=this._intervalEnd-e;if(n<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},n)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let n=this._queue.dequeue();return n?(this.emit("active"),n(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,n={}){return new Promise((r,o)=>{let i=async()=>{this._pendingCount++,this._intervalCount++;try{let s=this._timeout===void 0&&n.timeout===void 0?e():dje.default(Promise.resolve(e()),n.timeout===void 0?this._timeout:n.timeout,()=>{(n.throwOnTimeout===void 0?this._throwOnTimeout:n.throwOnTimeout)&&o(TNt)});r(await s)}catch(s){o(s)}this._next()};this._queue.enqueue(i,n),this._tryToStartAnother(),this.emit("add")})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let n=this._resolveEmpty;this._resolveEmpty=()=>{n(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let n=this._resolveIdle;this._resolveIdle=()=>{n(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Eue.default=Pue});function INt(){return new("default"in BK.default?BK.default.default:BK.default)({autoStart:!0,concurrency:1})}function PNt(){return typeof H2>"u"&&(H2=INt()),H2}async function Pi(t,e){if(e===!0){let n=zb();n!==void 0?await n.run(void 0,async()=>t()):await t()}else H2=PNt(),H2.add(async()=>{let n=zb();n!==void 0?await n.run(void 0,async()=>t()):await t()})}var BK,H2,kue=C(()=>{wue();A2();BK=N(Aue(),1)});var fje=C(()=>{$n();kue()});var pje,mje=C(()=>{Jo();pje=t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>In(e)==="true")});function Mue(t){let e=zb();if(e!==void 0)return e.getStore()?.[QT]?.[t]}var ENt,hje,gje=C(()=>{A2();RK();ENt=Symbol("lc:configure_hooks"),hje=()=>Mue(ENt)||[]});function Wb(t){return t?Array.isArray(t)||"name"in t?{callbacks:t}:t:{}}function q2(t){return"name"in t?t:Gk.fromMethods(t)}var ANt,zK,kNt,yje,MNt,NNt,Ws,Hb=C(()=>{$n();Dm();P2();E2();Jo();k2();iI();tje();sje();kue();fje();mje();gje();ANt=class{setHandler(t){return this.setHandlers([t])}},zK=class{constructor(t,e,n,r,o,i,s,a){this.runId=t,this.handlers=e,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=o,this.metadata=i,this.inheritableMetadata=s,this._parentRunId=a}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Pi(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleCustomEvent(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Pi(async()=>{try{await i.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}},kNt=class extends zK{getChild(t){let e=new Ws(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>Pi(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw n}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>Pi(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${n}`),e.raiseError)throw t}},e.awaitHandlers)))}},yje=class extends zK{async handleLLMNewToken(t,e,n,r,o,i){await Promise.all(this.handlers.map(s=>Pi(async()=>{if(!s.ignoreLLM)try{await s.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(a){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMNewToken: ${a}`),s.raiseError)throw a}},s.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>Pi(async()=>{if(!e.ignoreLLM)try{await e.handleChatModelStreamEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleLLMError(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Pi(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,o)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleLLMEnd(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Pi(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,o)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}},MNt=class extends zK{getChild(t){let e=new Ws(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Pi(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(t,this.runId,this._parentRunId,this.tags,o)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleChainEnd(t,e,n,r,o){await Promise.all(this.handlers.map(i=>Pi(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,o)}catch(s){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${s}`),i.raiseError)throw s}},i.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Pi(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>Pi(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}},NNt=class extends zK{getChild(t){let e=new Ws(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>Pi(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>Pi(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if(e.raiseError)throw n}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>Pi(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(n){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${n}`),e.raiseError)throw n}},e.awaitHandlers)))}},Ws=class K2 extends ANt{constructor(n,r){super();I(this,"handlers",[]);I(this,"inheritableHandlers",[]);I(this,"tags",[]);I(this,"inheritableTags",[]);I(this,"metadata",{});I(this,"inheritableMetadata",{});I(this,"name","callback_manager");I(this,"_parentRunId");this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=n}getParentRunId(){return this._parentRunId}async handleLLMStart(n,r,o=void 0,i=void 0,s=void 0,a=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&o?o:op();return await Promise.all(this.handlers.map(p=>{if(!p.ignoreLLM)return tM(p)&&p._createRunForLLMStart(n,[u],f,this._parentRunId,s,this.tags,this.metadata,c),Pi(async()=>{try{await p.handleLLMStart?.(n,[u],f,this._parentRunId,s,this.tags,this.metadata,c)}catch(m){if((p.raiseError?console.error:console.warn)(`Error in handler ${p.constructor.name}, handleLLMStart: ${m}`),p.raiseError)throw m}},p.awaitHandlers)})),new yje(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(n,r,o=void 0,i=void 0,s=void 0,a=void 0,l=void 0,c=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&o?o:op();return await Promise.all(this.handlers.map(p=>{if(!p.ignoreLLM)return tM(p)&&p._createRunForChatModelStart(n,[u],f,this._parentRunId,s,this.tags,this.metadata,c),Pi(async()=>{try{if(p.handleChatModelStart)await p.handleChatModelStart?.(n,[u],f,this._parentRunId,s,this.tags,this.metadata,c);else if(p.handleLLMStart){let m=ui(u);await p.handleLLMStart?.(n,[m],f,this._parentRunId,s,this.tags,this.metadata,c)}}catch(m){if((p.raiseError?console.error:console.warn)(`Error in handler ${p.constructor.name}, handleLLMStart: ${m}`),p.raiseError)throw m}},p.awaitHandlers)})),new yje(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(n,r,o=op(),i=void 0,s=void 0,a=void 0,l=void 0,c=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return tM(d)&&d._createRunForChainStart(n,r,o,this._parentRunId,this.tags,this.metadata,i,l,u),Pi(async()=>{try{await d.handleChainStart?.(n,r,o,this._parentRunId,this.tags,this.metadata,i,l,u)}catch(f){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${f}`),d.raiseError)throw f}},d.awaitHandlers)})),new MNt(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(n,r,o=op(),i=void 0,s=void 0,a=void 0,l=void 0,c=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return tM(u)&&u._createRunForToolStart(n,r,o,this._parentRunId,this.tags,this.metadata,l),Pi(async()=>{try{await u.handleToolStart?.(n,r,o,this._parentRunId,this.tags,this.metadata,l,c)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new NNt(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(n,r,o=op(),i=void 0,s=void 0,a=void 0,l=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreRetriever)return tM(c)&&c._createRunForRetrieverStart(n,r,o,this._parentRunId,this.tags,this.metadata,l),Pi(async()=>{try{await c.handleRetrieverStart?.(n,r,o,this._parentRunId,this.tags,this.metadata,l)}catch(u){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleRetrieverStart: ${u}`),c.raiseError)throw u}},c.awaitHandlers)})),new kNt(o,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(n,r,o,i,s){await Promise.all(this.handlers.map(a=>Pi(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(n,r,o,this.tags,this.metadata)}catch(l){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${l}`),a.raiseError)throw l}},a.awaitHandlers)))}addHandler(n,r=!0){this.handlers.push(n),r&&this.inheritableHandlers.push(n)}removeHandler(n){this.handlers=this.handlers.filter(r=>r!==n),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==n)}setHandlers(n,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let o of n)this.addHandler(o,r)}addTags(n,r=!0){this.removeTags(n),this.tags.push(...n),r&&this.inheritableTags.push(...n)}removeTags(n){this.tags=this.tags.filter(r=>!n.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!n.includes(r))}addMetadata(n,r=!0){this.metadata={...this.metadata,...n},r&&(this.inheritableMetadata={...this.inheritableMetadata,...n})}removeMetadata(n){for(let r of Object.keys(n))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(n=[],r=!0){let o=new K2(this._parentRunId);for(let i of this.handlers){let s=this.inheritableHandlers.includes(i);o.addHandler(i,s)}for(let i of this.tags){let s=this.inheritableTags.includes(i);o.addTags([i],s)}for(let i of Object.keys(this.metadata)){let s=Object.keys(this.inheritableMetadata).includes(i);o.addMetadata({[i]:this.metadata[i]},s)}for(let i of n)o.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===i.name)||o.addHandler(i,r);return o}static fromHandlers(n){class r extends Gk{constructor(){super();I(this,"name",op());Object.assign(this,n)}}let o=new this;return o.addHandler(new r),o}static configure(n,r,o,i,s,a,l){return this._configureSync(n,r,o,i,s,a,l)}static _configureSync(n,r,o,i,s,a,l){let c;(n||r)&&(Array.isArray(n)||!n?(c=new K2,c.setHandlers(n?.map(q2)??[],!0)):c=n,c=c.copy(Array.isArray(r)?r.map(q2):r?.handlers,!1));let u=In("LANGCHAIN_VERBOSE")==="true"||l?.verbose,d=W2.getTraceableRunTree(),f=d?.tracingEnabled??pje();if(d?.tracingEnabled===!1&&c){let g=c.handlers.filter(y=>y.name==="langchain_tracer");for(let y of g)c.removeHandler(y)}let p=f||(In("LANGCHAIN_TRACING")??!1);if(u||p){if(c||(c=new K2),u&&!c.handlers.some(g=>g.name===hue.prototype.name)){let g=new hue;c.addHandler(g,!0)}if(p&&!c.handlers.some(g=>g.name==="langchain_tracer")&&f){let g=new W2;c.addHandler(g,!0)}f&&d&&c._parentRunId===void 0&&(c._parentRunId=d.id,c.handlers.find(g=>g.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:g,inheritable:y=!0,handlerClass:w,envVar:v}of hje()){let x=v&&In(v)==="true"&&w,b,_=g!==void 0?Mue(g):void 0;_&&f2e(_)?b=_:x&&(b=new w({})),b!==void 0&&(c||(c=new K2),c.handlers.some(T=>T.name===b.name)||c.addHandler(b,y))}(o||i)&&c&&(c.addTags(o??[]),c.addTags(i??[],!1)),(s||a)&&c&&(c.addMetadata(s??{}),c.addMetadata(a??{},!1));let m=l?.tracerInheritableMetadata,h=l?.tracerInheritableTags;return c&&(m||h)&&(c.handlers=c.handlers.map(g=>g instanceof W2?g.copyWithTracingConfig({metadata:m,tags:h}):g),c.inheritableHandlers=c.inheritableHandlers.map(g=>g instanceof W2?g.copyWithTracingConfig({metadata:m,tags:h}):g)),c}}});var vje,ONt,wje,RNt,vl,sI=C(()=>{A2();Hb();LK();vje=class{getStore(){}run(t,e){return e()}enterWith(t){}},ONt=new vje,wje=Symbol.for("lc:child_config"),RNt=class{getInstance(){return zb()??ONt}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[wje]}runWithConfig(t,e,n){let r=Ws._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),o=this.getInstance(),i=o.getStore(),s=r?.getParentRunId(),a=r?.handlers?.find(c=>c?.name==="langchain_tracer"),l;return a&&s?l=a.getRunTreeWithTracingConfig(s):n||(l=new Fm({name:"<runnable_lambda>",tracingEnabled:!1})),l&&(l.extra={...l.extra,[wje]:t}),i!==void 0&&i[QT]!==void 0&&(l===void 0&&(l={}),l[QT]=i[QT]),o.run(l,e)}initializeGlobalInstance(t){zb()===void 0&&c2e(t)}},vl=new RNt});var aI=C(()=>{$n();A2();sI()});function $Nt(t){let e=t.configurable??{},n=t.metadata??{},r={};for(let[o,i]of Object.entries(e))!o.startsWith("__")&&!Object.prototype.hasOwnProperty.call(n,o)&&!LNt.has(o)&&DNt.has(typeof i)&&(r[o]=i);return Object.keys(r).length>0?r:void 0}async function qu(t){return Ws._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata,void 0,{tracerInheritableMetadata:t?$Nt(t):void 0})}function nM(...t){let e={};for(let n of t.filter(r=>!!r))for(let r of Object.keys(n))if(r==="metadata")e[r]={...e[r],...n[r]};else if(r==="tags"){let o=e[r]??[];e[r]=[...new Set(o.concat(n[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...n[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=n.timeout:n.timeout!==void 0&&(e.timeout=Math.min(e.timeout,n.timeout));else if(r==="signal")e.signal===void 0?e.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,n.signal]):e.signal=n.signal);else if(r==="callbacks"){let o=e.callbacks,i=n.callbacks;if(Array.isArray(i))if(!o)e.callbacks=i;else if(Array.isArray(o))e.callbacks=o.concat(i);else{let s=o.copy();for(let a of i)s.addHandler(q2(a),!0);e.callbacks=s}else if(i)if(!o)e.callbacks=i;else if(Array.isArray(o)){let s=i.copy();for(let a of o)s.addHandler(q2(a),!0);e.callbacks=s}else e.callbacks=new Ws(i._parentRunId,{handlers:o.handlers.concat(i.handlers),inheritableHandlers:o.inheritableHandlers.concat(i.inheritableHandlers),tags:Array.from(new Set(o.tags.concat(i.tags))),inheritableTags:Array.from(new Set(o.inheritableTags.concat(i.inheritableTags))),metadata:{...o.metadata,...i.metadata}})}else{let o=r;e[o]=n[o]??e[o]}return e}function fr(t){let e=vl.getRunnableConfig(),n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){let{runId:r,runName:o,...i}=e;n=Object.entries(i).reduce((s,[a,l])=>(l!==void 0&&(s[a]=l),s),n)}if(t&&(n=Object.entries(t).reduce((r,[o,i])=>(i!==void 0&&(r[o]=i),r),n)),n?.configurable&&typeof n.configurable.model=="string"&&n.metadata?.model===void 0&&(n.metadata||(n.metadata={}),n.metadata.model=n.configurable.model),n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");let r=n.timeout,o=AbortSignal.timeout(r);n.metadata||(n.metadata={}),n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=r),n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,o])):n.signal=o,delete n.timeout}return n}function Fi(t={},{callbacks:e,maxConcurrency:n,recursionLimit:r,runName:o,configurable:i,runId:s}={}){let a=fr(t);return e!==void 0&&(delete a.runName,a.callbacks=e),r!==void 0&&(a.recursionLimit=r),n!==void 0&&(a.maxConcurrency=n),o!==void 0&&(a.runName=o),i!==void 0&&(a.configurable={...a.configurable,...i}),s!==void 0&&delete a.runId,a}function Gu(t){if(t)return{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal,store:t.store}}var LNt,DNt,Ng=C(()=>{Hb();sI();aI();LNt=new Set(["api_key"]),DNt=new Set(["string","number","boolean"])});async function lp(t,e){if(e===void 0)return t;let n;return Promise.race([t.catch(r=>{if(!e?.aborted)throw r}),new Promise((r,o)=>{n=()=>{o(Kb(e))},e.addEventListener("abort",n,{once:!0}),e.aborted&&o(Kb(e))})]).finally(()=>e.removeEventListener("abort",n))}function Kb(t){return t?.reason instanceof Error?t.reason:typeof t?.reason=="string"?new Error(t.reason):new Error("Aborted")}var rM=C(()=>{});function Oue(t,e=2){let n=Array.from({length:e},()=>[]);return n.map(async function*(o){for(;;)if(o.length===0){let i=await t.next();for(let s of n)s.push(i)}else{if(o[0].done)return;yield o.shift().value}})}function Um(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){let n={...t};for(let[r,o]of Object.entries(e))r in n&&!Array.isArray(n[r])?n[r]=Um(n[r],o):n[r]=o;return n}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}async function xje(t,e,n,r,...o){let i=new lI({generator:e,startSetup:n,signal:r}),s=await i.setup;return{output:t(i,s,...o),setup:s}}var Yu,lI,Og=C(()=>{$n();sI();aI();Ng();rM();Yu=class Nue extends ReadableStream{constructor(){super(...arguments);I(this,"reader")}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{let n=await this.reader.read();return n.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:n.value}}catch(n){throw this.reader.releaseLock(),n}}async return(){if(this.ensureReader(),this.locked){let n=this.reader.cancel();this.reader.releaseLock(),await n}return{done:!0,value:void 0}}async throw(n){if(this.ensureReader(),this.locked){let r=this.reader.cancel();this.reader.releaseLock(),await r}throw n}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(n){let r=n.getReader();return new Nue({start(o){return i();function i(){return r.read().then(({done:s,value:a})=>{if(s){o.close();return}return o.enqueue(a),i()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(n){return new Nue({async pull(r){let{value:o,done:i}=await n.next();i&&r.close(),r.enqueue(o)},async cancel(r){await n.return(r)}})}};lI=class{constructor(t){I(this,"generator");I(this,"setup");I(this,"config");I(this,"signal");I(this,"firstResult");I(this,"firstResultUsed",!1);this.generator=t.generator,this.config=t.config,this.signal=t.signal??this.config?.signal,this.setup=new Promise((e,n)=>{vl.runWithConfig(Gu(t.config),async()=>{this.firstResult=this.signal?lp(t.generator.next(),this.signal):t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(e,n):this.firstResult.then(r=>e(void 0),n)},!0)})}async next(...t){return this.signal?.throwIfAborted(),this.firstResultUsed?vl.runWithConfig(Gu(this.config),this.signal?async()=>lp(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}});function VK(t,e){return FNt.call(t,e)}function WK(t){if(Array.isArray(t)){let n=new Array(t.length);for(let r=0;r<n.length;r++)n[r]=""+r;return n}if(Object.keys)return Object.keys(t);let e=[];for(let n in t)VK(t,n)&&e.push(n);return e}function Kd(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function HK(t){let e=0,n=t.length,r;for(;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function cI(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Cje(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function jK(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(jK(t[n]))return!0}else if(typeof t=="object"){let n=WK(t),r=n.length;for(var e=0;e<r;e++)if(jK(t[n[e]]))return!0}}return!1}function bje(t,e){let n=[t];for(let r in e){let o=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof o<"u"&&n.push(`${r}: ${o}`)}return n.join(`
`)}var FNt,_je,KK=C(()=>{FNt=Object.prototype.hasOwnProperty;_je=class extends Error{constructor(t,e,n,r,o){super(bje(t,{name:e,index:n,operation:r,tree:o})),this.name=e,this.index=n,this.operation=r,this.tree=o,Object.setPrototypeOf(this,new.target.prototype),this.message=bje(t,{name:e,index:n,operation:r,tree:o})}}});function qK(t,e){if(e=="")return t;var n={op:"_get",path:e};return uI(t,n),n.value}function uI(t,e,n=!1,r=!0,o=!0,i=0){if(n&&(typeof n=="function"?n(e,0,t,e.path):GK(e,0)),e.path===""){let s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=qK(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=G2(t,e.value),s.test===!1)throw new Ui("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(n)throw new Ui("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{r||(t=Kd(t));let s=(e.path||"").split("/"),a=t,l=1,c=s.length,u,d,f;for(typeof n=="function"?f=n:f=GK;;){if(d=s[l],d&&d.indexOf("~")!=-1&&(d=Cje(d)),o&&(d=="__proto__"||d=="prototype"&&l>0&&s[l-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&u===void 0&&(a[d]===void 0?u=s.slice(0,l).join("/"):l==c-1&&(u=e.path),u!==void 0&&f(e,0,t,u)),l++,Array.isArray(a)){if(d==="-")d=a.length;else{if(n&&!HK(d))throw new Ui("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);HK(d)&&(d=~~d)}if(l>=c){if(n&&e.op==="add"&&d>a.length)throw new Ui("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let p=BNt[e.op].call(e,a,d,t);if(p.test===!1)throw new Ui("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}}else if(l>=c){let p=oM[e.op].call(e,a,d,t);if(p.test===!1)throw new Ui("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return p}if(a=a[d],n&&l<c&&(!a||typeof a!="object"))throw new Ui("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function dI(t,e,n,r=!0,o=!0){if(n&&!Array.isArray(e))throw new Ui("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=Kd(t));let i=new Array(e.length);for(let s=0,a=e.length;s<a;s++)i[s]=uI(t,e[s],n,!0,o,s),t=i[s].newDocument;return i.newDocument=t,i}function zNt(t,e,n){let r=uI(t,e);if(r.test===!1)throw new Ui("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function GK(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new Ui("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(oM[t.op]){if(typeof t.path!="string")throw new Ui("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new Ui('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new Ui("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new Ui("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&jK(t.value))throw new Ui("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,i=r.split("/").length;if(o!==i+1&&o!==i)throw new Ui("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new Ui("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var s=Tje([{op:"_get",path:t.from,value:void 0}],n);if(s&&s.name==="OPERATION_PATH_UNRESOLVABLE")throw new Ui("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new Ui("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function Tje(t,e,n){try{if(!Array.isArray(t))throw new Ui("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)dI(Kd(e),Kd(t),n||!0);else{n=n||GK;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof Ui)return o;throw o}}function G2(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),o,i,s;if(n&&r){if(i=t.length,i!=e.length)return!1;for(o=i;o--!==0;)if(!G2(t[o],e[o]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(i=a.length,i!==Object.keys(e).length)return!1;for(o=i;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=i;o--!==0;)if(s=a[o],!G2(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var Sje,Ui,UNt,oM,BNt,Y2=C(()=>{$n();KK();Sje=Dn({JsonPatchError:()=>Ui,_areEquals:()=>G2,applyOperation:()=>uI,applyPatch:()=>dI,applyReducer:()=>zNt,deepClone:()=>UNt,getValueByPointer:()=>qK,validate:()=>Tje,validator:()=>GK}),Ui=_je,UNt=Kd,oM={add:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){let r=qK(n,this.path);r&&(r=Kd(r));let o=uI(n,{op:"remove",path:this.from}).removed;return uI(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(t,e,n){let r=qK(n,this.from);return uI(n,{op:"add",path:this.path,value:Kd(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:G2(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},BNt={add:function(t,e,n){return HK(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){return{newDocument:n,removed:t.splice(e,1)[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:oM.move,copy:oM.copy,test:oM.test,_get:oM._get}});function Ije(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=WK(e),s=WK(t),a=!1,l=s.length-1;l>=0;l--){var c=s[l],u=t[c];if(VK(e,c)&&!(e[c]===void 0&&u!==void 0&&Array.isArray(e)===!1)){var d=e[c];typeof u=="object"&&u!=null&&typeof d=="object"&&d!=null&&Array.isArray(u)===Array.isArray(d)?Ije(u,d,n,r+"/"+cI(c),o):u!==d&&(o&&n.push({op:"test",path:r+"/"+cI(c),value:Kd(u)}),n.push({op:"replace",path:r+"/"+cI(c),value:Kd(d)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+cI(c),value:Kd(u)}),n.push({op:"remove",path:r+"/"+cI(c)}),a=!0):(o&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}))}if(!(!a&&i.length==s.length))for(var l=0;l<i.length;l++){var c=i[l];!VK(t,c)&&e[c]!==void 0&&n.push({op:"add",path:r+"/"+cI(c),value:Kd(e[c])})}}}function YK(t,e,n=!1){var r=[];return Ije(t,e,r,"",n),r}var Z2=C(()=>{KK();Y2();});var Rue=C(()=>{KK();Y2();Z2();({...Sje})});async function Pje(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");let{inputs:n}=t;if(["retriever","llm","prompt"].includes(t.run_type))return n;if(!(Object.keys(n).length===1&&n?.input===""))return n.input}async function Eje(t,e){let{outputs:n}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?n:n!==void 0&&Object.keys(n).length===1&&n?.output!==void 0?n.output:n}function jNt(t){return t!==void 0&&t.message!==void 0}var Rw,Due,Aje,$ue,kje=C(()=>{$n();Wu();iI();Y2();Rue();Og();Rw=class{constructor(t){I(this,"ops");this.ops=t.ops??[]}concat(t){let e=this.ops.concat(t.ops),n=dI({},e);return new Due({ops:e,state:n[n.length-1].newDocument})}},Due=class Lue extends Rw{constructor(n){super(n);I(this,"state");this.state=n.state}concat(n){let r=this.ops.concat(n.ops),o=dI(this.state,n.ops);return new Lue({ops:r,state:o[o.length-1].newDocument})}static fromRunLogPatch(n){let r=dI({},n.ops);return new Lue({ops:n.ops,state:r[r.length-1].newDocument})}},Aje=t=>t.name==="log_stream_tracer";$ue=class extends Mg{constructor(e){super({_awaitHandler:!0,...e});I(this,"autoClose",!0);I(this,"includeNames");I(this,"includeTypes");I(this,"includeTags");I(this,"excludeNames");I(this,"excludeTypes");I(this,"excludeTags");I(this,"_schemaFormat","original");I(this,"rootId");I(this,"keyMapByRunId",{});I(this,"counterMapByRunName",{});I(this,"transformStream");I(this,"writer");I(this,"receiveStream");I(this,"name","log_stream_tracer");I(this,"lc_prefer_streaming",!0);this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Yu.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;let n=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||n.find(o=>this.includeTags?.includes(o))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&n.every(o=>!this.excludeTags?.includes(o))),r}async*tapOutputIterable(e,n){for await(let r of n){if(e!==this.rootId){let o=this.keyMapByRunId[e];o&&await this.writer.write(new Rw({ops:[{op:"add",path:`/logs/${o}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new Rw({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;let n=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=n===1?e.name:`${e.name}:${n}`;let r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.metadata??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await Pje(e,this._schemaFormat)),await this.writer.write(new Rw({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{let n=this.keyMapByRunId[e.id];if(n===void 0)return;let r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${n}/inputs`,value:await Pje(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${n}/final_output`,value:await Eje(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${n}/end_time`,value:new Date(e.end_time).toISOString()});let o=new Rw({ops:r});await this.writer.write(o)}finally{if(e.id===this.rootId){let n=new Rw({ops:[{op:"replace",path:"/final_output",value:await Eje(e,this._schemaFormat)}]});await this.writer.write(n),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,n,r){let o=this.keyMapByRunId[e.id];if(o===void 0)return;let i=e.inputs.messages!==void 0,s;i?jNt(r?.chunk)?s=r?.chunk:s=new Yt({id:`run-${e.id}`,content:n}):s=n;let a=new Rw({ops:[{op:"add",path:`/logs/${o}/streamed_output_str/-`,value:n},{op:"add",path:`/logs/${o}/streamed_output/-`,value:s}]});await this.writer.write(a)}}});var iM,Lw,Jr,ac=C(()=>{$n();iM="__run",Lw=class Mje{constructor(e){I(this,"text");I(this,"generationInfo");this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new Mje({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},Jr=class Nje extends Lw{constructor(n){super(n);I(this,"message");this.message=n.message}concat(n){return new Nje({text:this.text+n.text,generationInfo:{...this.generationInfo,...n.generationInfo},message:this.message.concat(n.message)})}}});function ZK({name:t,serialized:e}){return t!==void 0?t:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}var Oje,Rje,Lje=C(()=>{Wu();iI();Og();ac();Oje=t=>t.name==="event_stream_tracer",Rje=class extends Mg{constructor(e){super({_awaitHandler:!0,...e});I(this,"autoClose",!0);I(this,"includeNames");I(this,"includeTypes");I(this,"includeTags");I(this,"excludeNames");I(this,"excludeTypes");I(this,"excludeTags");I(this,"runInfoMap",new Map);I(this,"tappedPromises",new Map);I(this,"transformStream");I(this,"writer");I(this,"receiveStream");I(this,"readableStreamClosed",!1);I(this,"name","event_stream_tracer");I(this,"lc_prefer_streaming",!0);this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=Yu.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){let n=e.tags??[],r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||n.find(o=>this.includeTags?.includes(o))!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&n.every(o=>!this.excludeTags?.includes(o))),r}async*tapOutputIterable(e,n){let r=await n.next();if(r.done)return;let o=this.runInfoMap.get(e);if(o===void 0){yield r.value;return}function i(a,l){return a==="llm"&&typeof l=="string"?new Lw({text:l}):l}let s=this.tappedPromises.get(e);if(s===void 0){let a;s=new Promise(l=>{a=l}),this.tappedPromises.set(e,s);try{let l={event:`on_${o.runType}_stream`,run_id:e,name:o.name,tags:o.tags,metadata:o.metadata,data:{}};await this.send({...l,data:{chunk:i(o.runType,r.value)}},o),yield r.value;for await(let c of n)o.runType!=="tool"&&o.runType!=="retriever"&&await this.send({...l,data:{chunk:i(o.runType,c)}},o),yield c}finally{a?.()}}else{yield r.value;for await(let a of n)yield a}}async send(e,n){this.readableStreamClosed||this._includeRun(n)&&await this.writer.write(e)}async sendEndEvent(e,n){let r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,n)}):await this.send(e,n)}async onLLMStart(e){let n=ZK(e),r=e.inputs.messages!==void 0?"chat_model":"llm",o={tags:e.tags??[],metadata:e.extra?.metadata??{},name:n,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,o);let i=`on_${r}_start`;await this.send({event:i,data:{input:e.inputs},name:n,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},o)}async onLLMNewToken(e,n,r){let o=this.runInfoMap.get(e.id),i,s;if(o===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(o.runType==="chat_model")s="on_chat_model_stream",r?.chunk===void 0?i=new Yt({content:n,id:`run-${e.id}`}):i=r.chunk.message;else if(o.runType==="llm")s="on_llm_stream",r?.chunk===void 0?i=new Lw({text:n}):i=r.chunk;else throw new Error(`Unexpected run type ${o.runType}`);await this.send({event:s,data:{chunk:i},run_id:e.id,name:o.name,tags:o.tags,metadata:o.metadata},o)}}async onLLMEnd(e){let n=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(n===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);let o=e.outputs?.generations,i;if(n.runType==="chat_model"){for(let s of o??[]){if(i!==void 0)break;i=s[0]?.message}r="on_chat_model_end"}else if(n.runType==="llm")i={generations:o?.map(s=>s.map(a=>({text:a.text,generationInfo:a.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${n.runType}`);await this.sendEndEvent({event:r,data:{output:i,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onChainStart(e){let n=ZK(e),r=e.run_type??"chain",o={tags:e.tags??[],metadata:e.extra?.metadata??{},name:n,runType:e.run_type},i={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(i={},o.inputs={}):e.inputs.input!==void 0?(i.input=e.inputs.input,o.inputs=e.inputs.input):(i.input=e.inputs,o.inputs=e.inputs),this.runInfoMap.set(e.id,o),await this.send({event:`on_${r}_start`,data:i,name:n,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},o)}async onChainEnd(e){let n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);let r=`on_${e.run_type}_end`,o=e.inputs??n.inputs??{},i={output:e.outputs?.output??e.outputs,input:o};o.input&&Object.keys(o).length===1&&(i.input=o.input,n.inputs=o.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata??{}},n)}async onToolStart(e){let n=ZK(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:n,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:n,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){let n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);let r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onToolError(e){let n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:n.inputs,error:e.error},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onRetrieverStart(e){let n=ZK(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:n,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:n,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},r)}async onRetrieverEnd(e){let n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async handleCustomEvent(e,n,r){let o=this.runInfoMap.get(r);if(o===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:o.tags,metadata:o.metadata,data:n},o)}async finish(){let e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}}});function Dje(t){if(!(t&&WNt(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:e,stack:n}=t;return e==="Load failed"?n===void 0||"__sentry_captured__"in t:e.startsWith("error sending request for url")?!0:HNt.has(e)}var VNt,WNt,HNt,$je=C(()=>{VNt=Object.prototype.toString,WNt=t=>VNt.call(t)==="[object Error]",HNt=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"])});function KNt(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function JK(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be \u2265 ${n}.`)}}function GNt(t,e){let n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1,o=Math.round(r*e.minTimeout*e.factor**(n-1));return o=Math.min(o,e.maxTimeout),o}function Fje(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function YNt({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:o}){let i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof qNt)throw i.originalError;let s=Number.isFinite(o.retries)?Math.max(0,o.retries-n):o.retries,a=o.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:i,attemptNumber:e,retriesLeft:s,retriesConsumed:n});if(await o.onFailedAttempt(l),Fje(r,a)<=0)throw i;let c=await o.shouldConsumeRetry(l),u=Fje(r,a);if(u<=0||s<=0)throw i;if(i instanceof TypeError&&!Dje(i)){if(c)throw i;return o.signal?.throwIfAborted(),!1}if(!await o.shouldRetry(l))throw i;if(!c)return o.signal?.throwIfAborted(),!1;let d=GNt(n,o),f=Math.min(d,u);return f>0&&await new Promise((p,m)=>{let h=()=>{clearTimeout(g),o.signal?.removeEventListener("abort",h),m(o.signal.reason)},g=setTimeout(()=>{o.signal?.removeEventListener("abort",h),p()},f);o.unref&&g.unref?.(),o.signal?.addEventListener("abort",h,{once:!0})}),o.signal?.throwIfAborted(),!0}async function J2(t,e={}){if(e={...e},KNt(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),JK("factor",e.factor,{min:0,allowInfinity:!1}),JK("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),JK("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),JK("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let n=0,r=0,o=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{e.signal?.throwIfAborted();let i=await t(n);return e.signal?.throwIfAborted(),i}catch(i){await YNt({error:i,attemptNumber:n,retriesConsumed:r,startTime:o,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var qNt,Fue=C(()=>{$je();qNt=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}}});var XK,ZNt,JNt,qb,X2=C(()=>{$n();rM();Fue();XK=N(Aue(),1),ZNt=[400,401,402,403,404,405,406,407,409],JNt=t=>{if(typeof t!="object"||t===null)return;if("message"in t&&typeof t.message=="string"&&(t.message.startsWith("Cancel")||t.message.startsWith("AbortError"))||"name"in t&&typeof t.name=="string"&&t.name==="AbortError"||"code"in t&&typeof t.code=="string"&&t.code==="ECONNABORTED")throw t;let e="response"in t&&typeof t.response=="object"&&t.response!==null&&"status"in t.response&&typeof t.response.status=="number"?t.response.status:void 0,n="status"in t&&typeof t.status=="number"?t.status:void 0,r=e??n;if(r&&ZNt.includes(+r))throw t;if(("error"in t&&typeof t.error=="object"&&t.error!==null&&"code"in t.error&&typeof t.error.code=="string"?t.error.code:void 0)==="insufficient_quota"){let o=new Error("message"in t&&typeof t.message=="string"?t.message:"Insufficient quota");throw o.name="InsufficientQuotaError",o}},qb=class{constructor(t){I(this,"maxConcurrency");I(this,"maxRetries");I(this,"onFailedAttempt");I(this,"queue");this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??JNt;let e="default"in XK.default?XK.default.default:XK.default;this.queue=new e({concurrency:this.maxConcurrency})}async call(t,...e){return this.queue.add(()=>J2(()=>t(...e).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:({error:n})=>this.onFailedAttempt?.(n),retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...n){if(t.signal){let r;return Promise.race([this.call(e,...n),new Promise((o,i)=>{r=()=>{i(Kb(t.signal))},t.signal?.addEventListener("abort",r,{once:!0})})]).finally(()=>{t.signal&&r&&t.signal.removeEventListener("abort",r)})}return this.call(e,...n)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}}});var Uue,Uje=C(()=>{iI();Uue=class extends Mg{constructor({config:e,onStart:n,onEnd:r,onError:o}){super({_awaitHandler:!0});I(this,"name","RootListenersTracer");I(this,"rootId");I(this,"config");I(this,"argOnStart");I(this,"argOnEnd");I(this,"argOnError");this.config=e,this.argOnStart=n,this.argOnEnd=r,this.argOnError=o}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}}});function Q2(t){return t?t.lc_runnable:!1}var Bje,zje,QK=C(()=>{Bje=class{constructor(t){I(this,"includeNames");I(this,"includeTypes");I(this,"includeTags");I(this,"excludeNames");I(this,"excludeTypes");I(this,"excludeTags");this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0,r=t.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e)),this.includeTags!==void 0&&(n=n||r.some(o=>this.includeTags?.includes(o))),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(n=n&&r.every(o=>!this.excludeTags?.includes(o))),n}},zje=t=>btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")});function Bue(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}function QNt(t){let e="";for(let[n,r]of Object.entries(t))e+=`	classDef ${n} ${r};
`;return e}function jje(t,e,n){let{firstNode:r,lastNode:o,nodeColors:i,withStyles:s=!0,curveStyle:a="linear",wrapLabelNWords:l=9}=n??{},c=s?`%%{init: {'flowchart': {'curve': '${a}'}}}%%
graph TD;
`:`graph TD;
`;if(s){let m="default",h={[m]:"{0}({1})"};r!==void 0&&(h[r]="{0}([{1}]):::first"),o!==void 0&&(h[o]="{0}([{1}]):::last");for(let[g,y]of Object.entries(t)){let w=y.name.split(":").pop()??"",v=XNt.some(b=>w.startsWith(b)&&w.endsWith(b))?`<p>${w}</p>`:w;Object.keys(y.metadata??{}).length&&(v+=`<hr/><small><em>${Object.entries(y.metadata??{}).map(([b,_])=>`${b} = ${_}`).join(`
`)}</em></small>`);let x=(h[g]??h[m]).replace("{0}",Bue(g)).replace("{1}",v);c+=`	${x}
`}}let u={};for(let m of e){let h=m.source.split(":"),g=m.target.split(":"),y=h.filter((w,v)=>w===g[v]).join(":");u[y]||(u[y]=[]),u[y].push(m)}let d=new Set;function f(m){return[...m].sort((h,g)=>h.split(":").length-g.split(":").length)}function p(m,h){let g=m.length===1&&m[0].source===m[0].target;if(h&&!g){let w=h.split(":").pop();if(d.has(h))throw new Error(`Found duplicate subgraph '${w}' at '${h} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(h),c+=`	subgraph ${w}
`}let y=f(Object.keys(u).filter(w=>w.startsWith(`${h}:`)&&w!==h&&w.split(":").length===h.split(":").length+1));for(let w of y)p(u[w],w);for(let w of m){let{source:v,target:x,data:b,conditional:_}=w,T="";if(b!==void 0){let S=b,P=S.split(" ");P.length>l&&(S=Array.from({length:Math.ceil(P.length/l)},(A,O)=>P.slice(O*l,(O+1)*l).join(" ")).join("&nbsp;<br>&nbsp;")),T=_?` -. &nbsp;${S}&nbsp; .-> `:` -- &nbsp;${S}&nbsp; --> `}else T=_?" -.-> ":" --> ";c+=`	${Bue(v)}${T}${Bue(x)};
`}h&&!g&&(c+=`	end
`)}p(u[""]??[],"");for(let m in u)!m.includes(":")&&m!==""&&p(u[m],m);return s&&(c+=QNt(i??{})),c}async function Vje(t,e){let n=e?.backgroundColor??"white",r=e?.imageType??"png",o=zje(t);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));let i=`https://mermaid.ink/img/${o}?bgColor=${n}&type=${r}`,s=await fetch(i);if(!s.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${s.status}`,`Status text: ${s.statusText}`].join(`
`));return await s.blob()}var XNt,Wje=C(()=>{QK();XNt=["*","_","`"]});function eOt(t,e){if(t!==void 0&&!Tg(t))return t;if(Q2(e))try{let n=e.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return e.getName()}else return e.name??"UnknownSchema"}function tOt(t){return Q2(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...Hr(t.data.schema),title:t.data.name}}}function Hje(t,e=[]){let n=new Set(t.edges.filter(o=>!e.includes(o.source)).map(o=>o.target)),r=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!n.has(o.id)&&r.push(o);return r.length===1?r[0]:void 0}function Kje(t,e=[]){let n=new Set(t.edges.filter(o=>!e.includes(o.target)).map(o=>o.source)),r=[];for(let o of Object.values(t.nodes))!e.includes(o.id)&&!n.has(o.id)&&r.push(o);return r.length===1?r[0]:void 0}var zue,Gje=C(()=>{$n();Hk();Ble();E2();QK();Wje();Bu();zue=class qje{constructor(e){I(this,"nodes",{});I(this,"edges",[]);this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){let e={};return Object.values(this.nodes).forEach((n,r)=>{e[n.id]=Tg(n.id)?r:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:e[n.id],...tOt(n)})),edges:this.edges.map(n=>{let r={source:e[n.source],target:e[n.target]};return typeof n.data<"u"&&(r.data=n.data),typeof n.conditional<"u"&&(r.conditional=n.conditional),r})}}addNode(e,n,r){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);let o=n??Ule(),i={id:o,data:e,name:eOt(n,e),metadata:r};return this.nodes[o]=i,i}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(n=>n.source!==e.id&&n.target!==e.id)}addEdge(e,n,r,o){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);let i={source:e.id,target:n.id,data:r,conditional:o};return this.edges.push(i),i}firstNode(){return Hje(this)}lastNode(){return Kje(this)}extend(e,n=""){let r=n;Object.values(e.nodes).map(l=>l.id).every(Tg)&&(r="");let o=l=>r?`${r}:${l}`:l;Object.entries(e.nodes).forEach(([l,c])=>{this.nodes[o(l)]={...c,id:o(l)}});let i=e.edges.map(l=>({...l,source:o(l.source),target:o(l.target)}));this.edges=[...this.edges,...i];let s=e.firstNode(),a=e.lastNode();return[s?{id:o(s.id),data:s.data}:void 0,a?{id:o(a.id),data:a.data}:void 0]}trimFirstNode(){let e=this.firstNode();e&&Hje(this,[e.id])&&this.removeNode(e)}trimLastNode(){let e=this.lastNode();e&&Kje(this,[e.id])&&this.removeNode(e)}reid(){let e=Object.fromEntries(Object.values(this.nodes).map(o=>[o.id,o.name])),n=new Map;Object.values(e).forEach(o=>{n.set(o,(n.get(o)||0)+1)});let r=o=>{let i=e[o];return Tg(o)&&n.get(i)===1?i:o};return new qje({nodes:Object.fromEntries(Object.entries(this.nodes).map(([o,i])=>[r(o),{...i,id:r(o)}])),edges:this.edges.map(o=>({...o,source:r(o.source),target:r(o.target)}))})}drawMermaid(e){let{withStyles:n,curveStyle:r,nodeColors:o={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:i}=e??{},s=this.reid(),a=s.firstNode(),l=s.lastNode();return jje(s.nodes,s.edges,{firstNode:a?.id,lastNode:l?.id,withStyles:n,curveStyle:r,nodeColors:o,wrapLabelNWords:i})}async drawMermaidPng(e){return Vje(this.drawMermaid(e),{backgroundColor:e?.backgroundColor})}}});function Yje(t){let e=new TextEncoder,n=new ReadableStream({async start(r){for await(let o of t)r.enqueue(e.encode(`event: data
data: ${JSON.stringify(o)}

`));r.enqueue(e.encode(`event: end

`)),r.close()}});return Yu.fromReadableStream(n)}var Zje=C(()=>{Og()});function jue(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}function e5(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function Vue(t){return t!=null&&typeof t=="object"&&typeof t.next=="function"}async function Xje(t,e){try{let n=await t.next();for(;!n.done;)await e?.(n.value),n=await t.next();return n.value}finally{await t.return?.(void 0)}}function*Wue(t,e){for(;;){let{value:n,done:r}=vl.runWithConfig(Gu(t),e.next.bind(e),!0);if(r)break;yield n}}async function*t5(t,e){let n=e[Symbol.asyncIterator]();for(;;){let{value:r,done:o}=await vl.runWithConfig(Gu(t),n.next.bind(e),!0);if(o)break;yield r}}var Jje,Hue=C(()=>{sI();aI();Ng();Jje=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function"});function Hs(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}function rOt(t){if(DK(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}function Dw(t){if(typeof t=="function")return new $w({func:t});if(gr.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){let e={};for(let[n,r]of Object.entries(t))e[n]=Dw(r);return new sM({steps:e})}else throw new Error(`Expected a Runnable, function or object.
Instead got an unsupported type.`)}function oOt(t,e){let n=e.name??t.getName(),r=e.description??NT(e.schema);return u2(e.schema)?new Kue({name:n,description:r,schema:we.object({input:we.string()}).transform(o=>o.input),bound:t}):new Kue({name:n,description:r,schema:e.schema,bound:t})}var gr,fI,que,Kc,sM,nOt,$w,r4e,n5,o4e,Kue,Ra=C(()=>{L3();Rb();P2();E2();sI();aI();Ng();rM();Og();kje();Lje();Fue();X2();Uje();QK();vg();Gje();Zje();Hue();Cue();_g();gr=class extends zu{constructor(){super(...arguments);I(this,"lc_runnable",!0);I(this,"name")}getName(e){let n=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${n}${e}`:n}withRetry(e){return new que({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new fI({bound:this,config:e,kwargs:{}})}withFallbacks(e){let n=Array.isArray(e)?e:e.fallbacks;return new r4e({runnable:this,fallbacks:n})}_getOptionsList(e,n=0){if(Array.isArray(e)&&e.length!==n)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${n} inputs`);if(Array.isArray(e))return e.map(fr);if(n>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");let r=Object.fromEntries(Object.entries(e).filter(([o])=>o!=="runId"));return Array.from({length:n},(o,i)=>fr(i===0?e:r))}return Array.from({length:n},()=>fr(e))}async batch(e,n,r){let o=this._getOptionsList(n??{},e.length),i=new qb({maxConcurrency:o[0]?.maxConcurrency??r?.maxConcurrency,onFailedAttempt:a=>{throw a}}),s=e.map((a,l)=>i.call(async()=>{try{return await this.invoke(a,o[l])}catch(c){if(r?.returnExceptions)return c;throw c}}));return Promise.all(s)}async*_streamIterator(e,n){yield this.invoke(e,n)}async stream(e,n){let r=fr(n),o=new lI({generator:this._streamIterator(e,r),config:r});return await o.setup,Yu.fromAsyncGenerator(o)}_separateRunnableConfigFromCallOptions(e){let n;e===void 0?n=fr(e):n=fr({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});let r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[n,r]}async _callWithConfig(e,n,r){let o=fr(r),i=await(await qu(o))?.handleChainStart(this.toJSON(),Hs(n,"input"),o.runId,o?.runType,void 0,void 0,o?.runName??this.getName());delete o.runId;let s;try{s=await lp(e.call(this,n,o,i),o.signal)}catch(a){throw await i?.handleChainError(a),a}return await i?.handleChainEnd(Hs(s,"output")),s}async _batchWithConfig(e,n,r,o){let i=this._getOptionsList(r??{},n.length),s=await Promise.all(i.map(qu)),a=await Promise.all(s.map(async(c,u)=>{let d=await c?.handleChainStart(this.toJSON(),Hs(n[u],"input"),i[u].runId,i[u].runType,void 0,void 0,i[u].runName??this.getName());return delete i[u].runId,d})),l;try{l=await lp(e.call(this,n,i,a,o),i?.[0]?.signal)}catch(c){throw await Promise.all(a.map(u=>u?.handleChainError(c))),c}return await Promise.all(a.map(c=>c?.handleChainEnd(Hs(l,"output")))),l}_concatOutputChunks(e,n){return Um(e,n)}async*_transformStreamWithConfig(e,n,r){let o,i=!0,s,a=!0,l=fr(r),c=await qu(l),u=this;async function*d(){for await(let p of e){if(i)if(o===void 0)o=p;else try{o=u._concatOutputChunks(o,p)}catch{o=void 0,i=!1}yield p}}let f;try{let p=await xje(n.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},l.runId,l.runType,void 0,void 0,l.runName??this.getName(),void 0,{lc_defers_inputs:!0}),l.signal,l);delete l.runId,f=p.setup;let m=f?.handlers.find(Oje),h=p.output;m!==void 0&&f!==void 0&&(h=m.tapOutputIterable(f.runId,h));let g=f?.handlers.find(Aje);g!==void 0&&f!==void 0&&(h=g.tapOutputIterable(f.runId,h));for await(let y of h)if(yield y,a)if(s===void 0)s=y;else try{s=this._concatOutputChunks(s,y)}catch{s=void 0,a=!1}}catch(p){throw await f?.handleChainError(p,void 0,void 0,void 0,{inputs:Hs(o,"input")}),p}await f?.handleChainEnd(s??{},void 0,void 0,void 0,{inputs:Hs(o,"input")})}getGraph(e){let n=new zue,r=n.addNode({name:`${this.getName()}Input`,schema:we.any()}),o=n.addNode(this),i=n.addNode({name:`${this.getName()}Output`,schema:we.any()});return n.addEdge(r,o),n.addEdge(o,i),n}pipe(e){return new Kc({first:this,last:Dw(e)})}pick(e){return this.pipe(new o4e(e))}assign(e){return this.pipe(new n5(new sM({steps:e})))}async*transform(e,n){let r;for await(let o of e)r===void 0?r=o:r=this._concatOutputChunks(r,o);yield*this._streamIterator(r,fr(n))}async*streamLog(e,n,r){let o=new $ue({...r,autoClose:!1,_schemaFormat:"original"}),i=fr(n);yield*this._streamLog(e,o,i)}async*_streamLog(e,n,r){let{callbacks:o}=r;if(o===void 0)r.callbacks=[n];else if(Array.isArray(o))r.callbacks=o.concat([n]);else{let l=o.copy();l.addHandler(n,!0),r.callbacks=l}let i=this.stream(e,r);async function s(){try{let l=await i;for await(let c of l){let u=new Rw({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await n.writer.write(u)}}finally{await n.writer.close()}}let a=s();try{for await(let l of n)yield l}finally{await a}}streamEvents(e,n,r){let o;if(n.version==="v1")o=this._streamEventsV1(e,n,r);else if(n.version==="v2")o=this._streamEventsV2(e,n,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return n.encoding==="text/event-stream"?Yje(o):Yu.fromAsyncGenerator(o)}async*_streamEventsV2(e,n,r){let o=new Rje({...r,autoClose:!1}),i=fr(n),s=i.runId??op();i.runId=s;let a=i.callbacks;if(a===void 0)i.callbacks=[o];else if(Array.isArray(a))i.callbacks=a.concat(o);else{let m=a.copy();m.addHandler(o,!0),i.callbacks=m}let l=new AbortController,c=this;async function u(){let m;try{if(i.signal)if("any"in AbortSignal)m=AbortSignal.any([l.signal,i.signal]);else{let y=new AbortController;i.signal.addEventListener("abort",()=>y.abort(),{once:!0}),l.signal.addEventListener("abort",()=>y.abort(),{once:!0}),m=y.signal}else m=l.signal;let h=await c.stream(e,{...i,signal:m}),g=o.tapOutputIterable(s,h);for await(let y of g)if(l.signal.aborted)break}finally{await o.finish()}}let d=u(),f=!1,p;try{for await(let m of o){if(!f){m.data.input=e,f=!0,p=m.run_id,yield m;continue}m.run_id===p&&m.event.endsWith("_end")&&m.data?.input&&delete m.data.input,yield m}}finally{l.abort(),await d}}async*_streamEventsV1(e,n,r){let o,i=!1,s=fr(n),a=s.tags??[],l=s.metadata??{},c=s.runName??this.getName(),u=new $ue({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new Bje({...r}),f=this._streamLog(e,u,s);for await(let m of f){if(o?o=o.concat(m):o=Due.fromRunLogPatch(m),o.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!i){i=!0;let w={...o.state},v={run_id:w.id,event:`on_${w.type}_start`,name:c,tags:a,metadata:l,data:{input:e}};d.includeEvent(v,w.type)&&(yield v)}let h=m.ops.filter(w=>w.path.startsWith("/logs/")).map(w=>w.path.split("/")[2]),g=[...new Set(h)];for(let w of g){let v,x={},b=o.state.logs[w];if(b.end_time===void 0?b.streamed_output.length>0?v="stream":v="start":v="end",v==="start")b.inputs!==void 0&&(x.input=b.inputs);else if(v==="end")b.inputs!==void 0&&(x.input=b.inputs),x.output=b.final_output;else if(v==="stream"){let _=b.streamed_output.length;if(_!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${_} instead. Encountered in: "${b.name}"`);x={chunk:b.streamed_output[0]},b.streamed_output=[]}yield{event:`on_${b.type}_${v}`,name:b.name,run_id:b.id,tags:b.tags,metadata:b.metadata,data:x}}let{state:y}=o;if(y.streamed_output.length>0){let w=y.streamed_output.length;if(w!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${w} instead. Encountered in: "${y.name}"`);let v={chunk:y.streamed_output[0]};y.streamed_output=[];let x={event:`on_${y.type}_stream`,run_id:y.id,tags:a,metadata:l,name:c,data:v};d.includeEvent(x,y.type)&&(yield x)}}let p=o?.state;if(p!==void 0){let m={event:`on_${p.type}_end`,name:c,run_id:p.id,tags:a,metadata:l,data:{output:p.final_output}};d.includeEvent(m,p.type)&&(yield m)}}static isRunnable(e){return Q2(e)}withListeners({onStart:e,onEnd:n,onError:r}){return new fI({bound:this,config:{},configFactories:[o=>({callbacks:[new Uue({config:o,onStart:e,onEnd:n,onError:r})]})]})}asTool(e){return oOt(this,e)}},fI=class Qje extends gr{constructor(n){super(n);I(this,"lc_namespace",["langchain_core","runnables"]);I(this,"lc_serializable",!0);I(this,"bound");I(this,"config");I(this,"kwargs");I(this,"configFactories");this.bound=n.bound,this.kwargs=n.kwargs,this.config=n.config,this.configFactories=n.configFactories}static lc_name(){return"RunnableBinding"}getName(n){return this.bound.getName(n)}async _mergeConfig(...n){let r=nM(this.config,...n);return nM(r,...this.configFactories?await Promise.all(this.configFactories.map(async o=>await o(r))):[])}withConfig(n){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...n}})}withRetry(n){return new que({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:n?.stopAfterAttempt,...n})}async invoke(n,r){return this.bound.invoke(n,await this._mergeConfig(r,this.kwargs))}async batch(n,r,o){let i=Array.isArray(r)?await Promise.all(r.map(async s=>this._mergeConfig(fr(s),this.kwargs))):await this._mergeConfig(fr(r),this.kwargs);return this.bound.batch(n,i,o)}_concatOutputChunks(n,r){return this.bound._concatOutputChunks(n,r)}async*_streamIterator(n,r){yield*this.bound._streamIterator(n,await this._mergeConfig(fr(r),this.kwargs))}async stream(n,r){return this.bound.stream(n,await this._mergeConfig(fr(r),this.kwargs))}async*transform(n,r){yield*this.bound.transform(n,await this._mergeConfig(fr(r),this.kwargs))}streamEvents(n,r,o){let i=this,s=async function*(){yield*i.bound.streamEvents(n,{...await i._mergeConfig(fr(r),i.kwargs),version:r.version},o)};return Yu.fromAsyncGenerator(s())}static isRunnableBinding(n){return n.bound&&gr.isRunnable(n.bound)}withListeners({onStart:n,onEnd:r,onError:o}){return new Qje({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[i=>({callbacks:[new Uue({config:i,onStart:n,onEnd:r,onError:o})]})]})}},que=class extends fI{constructor(e){super(e);I(this,"lc_namespace",["langchain_core","runnables"]);I(this,"maxAttemptNumber",3);I(this,"onFailedAttempt",()=>{});this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}static lc_name(){return"RunnableRetry"}_patchConfigForRetry(e,n,r){let o=e>1?`retry:attempt:${e}`:void 0;return Fi(n,{callbacks:r?.getChild(o)})}async _invoke(e,n,r){return J2(o=>super.invoke(e,this._patchConfigForRetry(o,n,r)),{onFailedAttempt:({error:o})=>this.onFailedAttempt(o,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,n){return this._callWithConfig(this._invoke.bind(this),e,n)}async _batch(e,n,r,o){let i={};try{await J2(async s=>{let a=e.map((f,p)=>p).filter(f=>i[f.toString()]===void 0||i[f.toString()]instanceof Error),l=a.map(f=>e[f]),c=a.map(f=>this._patchConfigForRetry(s,n?.[f],r?.[f])),u=await super.batch(l,c,{...o,returnExceptions:!0}),d;for(let f=0;f<u.length;f+=1){let p=u[f],m=a[f];p instanceof Error&&d===void 0&&(d=p,d.input=l[f]),i[m.toString()]=p}if(d)throw d;return u},{onFailedAttempt:({error:s})=>this.onFailedAttempt(s,s.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(s){if(o?.returnExceptions!==!0)throw s}return Object.keys(i).sort((s,a)=>parseInt(s,10)-parseInt(a,10)).map(s=>i[parseInt(s,10)])}async batch(e,n,r){return this._batchWithConfig(this._batch.bind(this),e,n,r)}},Kc=class eU extends gr{constructor(n){super(n);I(this,"first");I(this,"middle",[]);I(this,"last");I(this,"omitSequenceTags",!1);I(this,"lc_serializable",!0);I(this,"lc_namespace",["langchain_core","runnables"]);this.first=n.first,this.middle=n.middle??this.middle,this.last=n.last,this.name=n.name,this.omitSequenceTags=n.omitSequenceTags??this.omitSequenceTags}static lc_name(){return"RunnableSequence"}get steps(){return[this.first,...this.middle,this.last]}async invoke(n,r){let o=fr(r),i=await(await qu(o))?.handleChainStart(this.toJSON(),Hs(n,"input"),o.runId,void 0,void 0,void 0,o?.runName);delete o.runId;let s=n,a;try{let l=[this.first,...this.middle];for(let c=0;c<l.length;c+=1)s=await lp(l[c].invoke(s,Fi(o,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)})),o.signal);if(o.signal?.aborted)throw Kb(o.signal);a=await this.last.invoke(s,Fi(o,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(l){throw await i?.handleChainError(l),l}return await i?.handleChainEnd(Hs(a,"output")),a}async batch(n,r,o){let i=this._getOptionsList(r??{},n.length),s=await Promise.all(i.map(qu)),a=await Promise.all(s.map(async(c,u)=>{let d=await c?.handleChainStart(this.toJSON(),Hs(n[u],"input"),i[u].runId,void 0,void 0,void 0,i[u].runName);return delete i[u].runId,d})),l=n;try{for(let c=0;c<this.steps.length;c+=1)l=await lp(this.steps[c].batch(l,a.map((u,d)=>{let f=u?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return Fi(i[d],{callbacks:f})}),o),i[0]?.signal)}catch(c){throw await Promise.all(a.map(u=>u?.handleChainError(c))),c}return await Promise.all(a.map(c=>c?.handleChainEnd(Hs(l,"output")))),l}_concatOutputChunks(n,r){return this.last._concatOutputChunks(n,r)}async*_streamIterator(n,r){let o=await qu(r),{runId:i,...s}=r??{},a=await o?.handleChainStart(this.toJSON(),Hs(n,"input"),i,void 0,void 0,void 0,s?.runName),l=[this.first,...this.middle,this.last],c=!0,u;async function*d(){yield n}try{let f=l[0].transform(d(),Fi(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let p=1;p<l.length;p+=1)f=await l[p].transform(f,Fi(s,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${p+1}`)}));for await(let p of f)if(r?.signal?.throwIfAborted(),yield p,c)if(u===void 0)u=p;else try{u=this._concatOutputChunks(u,p)}catch{u=void 0,c=!1}}catch(f){throw await a?.handleChainError(f),f}await a?.handleChainEnd(Hs(u,"output"))}getGraph(n){let r=new zue,o=null;return this.steps.forEach((i,s)=>{let a=i.getGraph(n);s!==0&&a.trimFirstNode(),s!==this.steps.length-1&&a.trimLastNode(),r.extend(a);let l=a.firstNode();if(!l)throw new Error(`Runnable ${i} has no first node`);o&&r.addEdge(o,l),o=a.lastNode()}),r}pipe(n){return eU.isRunnableSequence(n)?new eU({first:this.first,middle:this.middle.concat([this.last,n.first,...n.middle]),last:n.last,name:this.name??n.name}):new eU({first:this.first,middle:[...this.middle,this.last],last:Dw(n),name:this.name})}static isRunnableSequence(n){return Array.isArray(n.middle)&&gr.isRunnable(n)}static from([n,...r],o){let i={};return typeof o=="string"?i.name=o:o!==void 0&&(i=o),new eU({...i,first:Dw(n),middle:r.slice(0,-1).map(Dw),last:Dw(r[r.length-1])})}},sM=class e4e extends gr{constructor(n){super(n);I(this,"lc_namespace",["langchain_core","runnables"]);I(this,"lc_serializable",!0);I(this,"steps");this.steps={};for(let[r,o]of Object.entries(n.steps))this.steps[r]=Dw(o)}static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}static from(n){return new e4e({steps:n})}async invoke(n,r){let o=fr(r),i=await(await qu(o))?.handleChainStart(this.toJSON(),{input:n},o.runId,void 0,void 0,void 0,o?.runName);delete o.runId;let s={};try{let a=Object.entries(this.steps).map(async([l,c])=>{s[l]=await c.invoke(n,Fi(o,{callbacks:i?.getChild(`map:key:${l}`)}))});await lp(Promise.all(a),o.signal)}catch(a){throw await i?.handleChainError(a),a}return await i?.handleChainEnd(s),s}async*_transform(n,r,o){let i={...this.steps},s=Oue(n,Object.keys(i).length),a=new Map(Object.entries(i).map(([l,c],u)=>{let d=c.transform(s[u],Fi(o,{callbacks:r?.getChild(`map:key:${l}`)}));return[l,d.next().then(f=>({key:l,gen:d,result:f}))]}));for(;a.size;){let{key:l,result:c,gen:u}=await lp(Promise.race(a.values()),o?.signal);a.delete(l),c.done||(yield{[l]:c.value},a.set(l,u.next().then(d=>({key:l,gen:u,result:d}))))}}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*o(){yield n}let i=fr(r),s=new lI({generator:this.transform(o(),i),config:i});return await s.setup,Yu.fromAsyncGenerator(s)}},nOt=class t4e extends gr{constructor(n){super(n);I(this,"lc_serializable",!1);I(this,"lc_namespace",["langchain_core","runnables"]);I(this,"func");if(!DK(n.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=n.func}async invoke(n,r){let[o]=this._getOptionsList(r??{},1),i=await qu(o);return lp(this.func(Fi(o,{callbacks:i}),n),o?.signal)}async*_streamIterator(n,r){let[o]=this._getOptionsList(r??{},1),i=await this.invoke(n,r);if(e5(i)){for await(let s of i)o?.signal?.throwIfAborted(),yield s;return}if(Jje(i)){for(;;){o?.signal?.throwIfAborted();let s=i.next();if(s.done)break;yield s.value}return}yield i}static from(n){return new t4e({func:n})}};$w=class n4e extends gr{constructor(n){if(DK(n.func))return nOt.from(n.func);super(n);I(this,"lc_namespace",["langchain_core","runnables"]);I(this,"func");rOt(n.func),this.func=n.func}static lc_name(){return"RunnableLambda"}static from(n){return new n4e({func:n})}async _invoke(n,r,o){return new Promise((i,s)=>{let a=Fi(r,{callbacks:o?.getChild(),recursionLimit:(r?.recursionLimit??25)-1});vl.runWithConfig(Gu(a),async()=>{try{let l=await this.func(n,{...a});if(l&&gr.isRunnable(l)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");l=await l.invoke(n,{...a,recursionLimit:(a.recursionLimit??25)-1})}else if(e5(l)){let c;for await(let u of t5(a,l))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}l=c}else if(jue(l)){let c;for(let u of Wue(a,l))if(r?.signal?.throwIfAborted(),c===void 0)c=u;else try{c=this._concatOutputChunks(c,u)}catch{c=u}l=c}i(l)}catch(l){s(l)}})})}async invoke(n,r){return this._callWithConfig(this._invoke.bind(this),n,r)}async*_transform(n,r,o){let i;for await(let l of n)if(i===void 0)i=l;else try{i=this._concatOutputChunks(i,l)}catch{i=l}let s=Fi(o,{callbacks:r?.getChild(),recursionLimit:(o?.recursionLimit??25)-1}),a=await new Promise((l,c)=>{vl.runWithConfig(Gu(s),async()=>{try{l(await this.func(i,{...s,config:s}))}catch(u){c(u)}})});if(a&&gr.isRunnable(a)){if(o?.recursionLimit===0)throw new Error("Recursion limit reached.");let l=await a.stream(i,s);for await(let c of l)yield c}else if(e5(a))for await(let l of t5(s,a))o?.signal?.throwIfAborted(),yield l;else if(jue(a))for(let l of Wue(s,a))o?.signal?.throwIfAborted(),yield l;else yield a}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*o(){yield n}let i=fr(r),s=new lI({generator:this.transform(o(),i),config:i});return await s.setup,Yu.fromAsyncGenerator(s)}},r4e=class extends gr{constructor(e){super(e);I(this,"lc_namespace",["langchain_core","runnables"]);I(this,"lc_serializable",!0);I(this,"runnable");I(this,"fallbacks");this.runnable=e.runnable,this.fallbacks=e.fallbacks}static lc_name(){return"RunnableWithFallbacks"}*runnables(){yield this.runnable;for(let e of this.fallbacks)yield e}async invoke(e,n){let r=fr(n),o=await qu(r),{runId:i,...s}=r,a=await o?.handleChainStart(this.toJSON(),Hs(e,"input"),i,void 0,void 0,void 0,s?.runName),l=Fi(s,{callbacks:a?.getChild()});return await vl.runWithConfig(l,async()=>{let c;for(let u of this.runnables()){r?.signal?.throwIfAborted();try{let d=await u.invoke(e,l);return await a?.handleChainEnd(Hs(d,"output")),d}catch(d){c===void 0&&(c=d)}}throw c===void 0?new Error("No error stored at end of fallback."):(await a?.handleChainError(c),c)})}async*_streamIterator(e,n){let r=fr(n),o=await qu(r),{runId:i,...s}=r,a=await o?.handleChainStart(this.toJSON(),Hs(e,"input"),i,void 0,void 0,void 0,s?.runName),l,c;for(let d of this.runnables()){r?.signal?.throwIfAborted();let f=Fi(s,{callbacks:a?.getChild()});try{c=t5(f,await d.stream(e,f));break}catch(p){l===void 0&&(l=p)}}if(c===void 0){let d=l??new Error("No error stored at end of fallback.");throw await a?.handleChainError(d),d}let u;try{for await(let d of c){yield d;try{u=u===void 0?u:this._concatOutputChunks(u,d)}catch{u=void 0}}}catch(d){throw await a?.handleChainError(d),d}await a?.handleChainEnd(Hs(u,"output"))}async batch(e,n,r){if(r?.returnExceptions)throw new Error("Not implemented.");let o=this._getOptionsList(n??{},e.length),i=await Promise.all(o.map(l=>qu(l))),s=await Promise.all(i.map(async(l,c)=>{let u=await l?.handleChainStart(this.toJSON(),Hs(e[c],"input"),o[c].runId,void 0,void 0,void 0,o[c].runName);return delete o[c].runId,u})),a;for(let l of this.runnables()){o[0].signal?.throwIfAborted();try{let c=await l.batch(e,s.map((u,d)=>Fi(o[d],{callbacks:u?.getChild()})),r);return await Promise.all(s.map((u,d)=>u?.handleChainEnd(Hs(c[d],"output")))),c}catch(c){a===void 0&&(a=c)}}throw a?(await Promise.all(s.map(l=>l?.handleChainError(a))),a):new Error("No error stored at end of fallbacks.")}};n5=class extends gr{constructor(e){e instanceof sM&&(e={mapper:e});super(e);I(this,"lc_namespace",["langchain_core","runnables"]);I(this,"lc_serializable",!0);I(this,"mapper");this.mapper=e.mapper}static lc_name(){return"RunnableAssign"}async invoke(e,n){let r=await this.mapper.invoke(e,n);return{...e,...r}}async*_transform(e,n,r){let o=this.mapper.getStepsKeys(),[i,s]=Oue(e),a=this.mapper.transform(s,Fi(r,{callbacks:n?.getChild()})),l=a.next();for await(let c of i){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);let u=Object.fromEntries(Object.entries(c).filter(([d])=>!o.includes(d)));Object.keys(u).length>0&&(yield u)}yield(await l).value;for await(let c of a)yield c}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}let o=fr(n),i=new lI({generator:this.transform(r(),o),config:o});return await i.setup,Yu.fromAsyncGenerator(i)}},o4e=class extends gr{constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e});super(e);I(this,"lc_namespace",["langchain_core","runnables"]);I(this,"lc_serializable",!0);I(this,"keys");this.keys=e.keys}static lc_name(){return"RunnablePick"}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{let n=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return n.length===0?void 0:Object.fromEntries(n)}}async invoke(e,n){return this._callWithConfig(this._pick.bind(this),e,n)}async*_transform(e){for await(let n of e){let r=await this._pick(n);r!==void 0&&(yield r)}}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}let o=fr(n),i=new lI({generator:this.transform(r(),o),config:o});return await i.setup,Yu.fromAsyncGenerator(i)}},Kue=class extends fI{constructor(e){let n=Kc.from([$w.from(async r=>{let o;if(Db(r))try{o=await MT(this.schema,r.args)}catch{throw new S2("Received tool input did not match expected schema",JSON.stringify(r.args))}else o=r;return o}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:n,config:e.config??{}});I(this,"name");I(this,"description");I(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}});var i4e=C(()=>{nc();zk();Wu();T2();D3();Bb();F3();I2();Dm();Ra()});var s4e,a4e=C(()=>{s4e=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"]});var l4e,c4e=C(()=>{l4e=["image","video","audio","text-plain","file"]});var iOt,u4e=C(()=>{a4e();c4e();iOt=["text","reasoning",...s4e,...l4e]});var Kr=C(()=>{$n();C2();gle();nc();R3();zk();Wu();T2();D3();Bb();F3();I2();Dm();i4e();u4e()});function Gue(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function Yue(t){return t!==void 0&&gr.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function Zue(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(jr(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function cp(t){return Zue(t)||Yue(t)||Gue(t)}var Jue=C(()=>{vg();Ra()});function aOt(t,e){let n=typeof e=="number"?void 0:e;return{name:t.name,description:t.description,parameters:Hr(t.schema),...n?.strict!==void 0?{strict:n.strict}:{}}}function Gb(t,e){let n=typeof e=="number"?void 0:e,r;return cp(t)?r={type:"function",function:aOt(t)}:r=t,n?.strict!==void 0&&(r.function.strict=n.strict),r}var pI=C(()=>{$n();Bu();Jue()});function zm(t,e){e?(La[0]=La[16]=La[1]=La[2]=La[3]=La[4]=La[5]=La[6]=La[7]=La[8]=La[9]=La[10]=La[11]=La[12]=La[13]=La[14]=La[15]=0,this.blocks=La):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}var Ft,lOt,Bm,r5,La,Xue,Que=C(()=>{Ft="0123456789abcdef".split(""),lOt=[-2147483648,8388608,32768,128],Bm=[24,16,8,0],r5=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],La=[];zm.prototype.update=function(t){if(!this.finalized){var e,n=typeof t;if(n!=="string"){if(n==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var r,o=0,i,s=t.length,a=this.blocks;o<s;){if(this.hashed&&(this.hashed=!1,a[0]=this.block,this.block=a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),e)for(i=this.start;o<s&&i<64;++o)a[i>>>2]|=t[o]<<Bm[i++&3];else for(i=this.start;o<s&&i<64;++o)r=t.charCodeAt(o),r<128?a[i>>>2]|=r<<Bm[i++&3]:r<2048?(a[i>>>2]|=(192|r>>>6)<<Bm[i++&3],a[i>>>2]|=(128|r&63)<<Bm[i++&3]):r<55296||r>=57344?(a[i>>>2]|=(224|r>>>12)<<Bm[i++&3],a[i>>>2]|=(128|r>>>6&63)<<Bm[i++&3],a[i>>>2]|=(128|r&63)<<Bm[i++&3]):(r=65536+((r&1023)<<10|t.charCodeAt(++o)&1023),a[i>>>2]|=(240|r>>>18)<<Bm[i++&3],a[i>>>2]|=(128|r>>>12&63)<<Bm[i++&3],a[i>>>2]|=(128|r>>>6&63)<<Bm[i++&3],a[i>>>2]|=(128|r&63)<<Bm[i++&3]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=a[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};zm.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=lOt[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};zm.prototype.hash=function(){var t=this.h0,e=this.h1,n=this.h2,r=this.h3,o=this.h4,i=this.h5,s=this.h6,a=this.h7,l=this.blocks,c,u,d,f,p,m,h,g,y,w,v;for(c=16;c<64;++c)p=l[c-15],u=(p>>>7|p<<25)^(p>>>18|p<<14)^p>>>3,p=l[c-2],d=(p>>>17|p<<15)^(p>>>19|p<<13)^p>>>10,l[c]=l[c-16]+u+l[c-7]+d<<0;for(v=e&n,c=0;c<64;c+=4)this.first?(this.is224?(g=300032,p=l[0]-1413257819,a=p-150054599<<0,r=p+24177077<<0):(g=704751109,p=l[0]-210244248,a=p-1521486534<<0,r=p+143694565<<0),this.first=!1):(u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),g=t&e,f=g^t&n^v,h=o&i^~o&s,p=a+d+h+r5[c]+l[c],m=u+f,a=r+p<<0,r=p+m<<0),u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),y=r&t,f=y^r&e^g,h=s&a^~s&o,p=i+d+h+r5[c+1]+l[c+1],m=u+f,s=n+p<<0,n=p+m<<0,u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),w=n&r,f=w^n&t^y,h=i&s^~i&a,p=o+d+h+r5[c+2]+l[c+2],m=u+f,i=e+p<<0,e=p+m<<0,u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=e&n,f=v^e&r^w,h=i&s^~i&a,p=o+d+h+r5[c+3]+l[c+3],m=u+f,o=t+p<<0,t=p+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+o<<0,this.h5=this.h5+i<<0,this.h6=this.h6+s<<0,this.h7=this.h7+a<<0};zm.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,o=this.h4,i=this.h5,s=this.h6,a=this.h7,l=Ft[t>>>28&15]+Ft[t>>>24&15]+Ft[t>>>20&15]+Ft[t>>>16&15]+Ft[t>>>12&15]+Ft[t>>>8&15]+Ft[t>>>4&15]+Ft[t&15]+Ft[e>>>28&15]+Ft[e>>>24&15]+Ft[e>>>20&15]+Ft[e>>>16&15]+Ft[e>>>12&15]+Ft[e>>>8&15]+Ft[e>>>4&15]+Ft[e&15]+Ft[n>>>28&15]+Ft[n>>>24&15]+Ft[n>>>20&15]+Ft[n>>>16&15]+Ft[n>>>12&15]+Ft[n>>>8&15]+Ft[n>>>4&15]+Ft[n&15]+Ft[r>>>28&15]+Ft[r>>>24&15]+Ft[r>>>20&15]+Ft[r>>>16&15]+Ft[r>>>12&15]+Ft[r>>>8&15]+Ft[r>>>4&15]+Ft[r&15]+Ft[o>>>28&15]+Ft[o>>>24&15]+Ft[o>>>20&15]+Ft[o>>>16&15]+Ft[o>>>12&15]+Ft[o>>>8&15]+Ft[o>>>4&15]+Ft[o&15]+Ft[i>>>28&15]+Ft[i>>>24&15]+Ft[i>>>20&15]+Ft[i>>>16&15]+Ft[i>>>12&15]+Ft[i>>>8&15]+Ft[i>>>4&15]+Ft[i&15]+Ft[s>>>28&15]+Ft[s>>>24&15]+Ft[s>>>20&15]+Ft[s>>>16&15]+Ft[s>>>12&15]+Ft[s>>>8&15]+Ft[s>>>4&15]+Ft[s&15];return this.is224||(l+=Ft[a>>>28&15]+Ft[a>>>24&15]+Ft[a>>>20&15]+Ft[a>>>16&15]+Ft[a>>>12&15]+Ft[a>>>8&15]+Ft[a>>>4&15]+Ft[a&15]),l};zm.prototype.toString=zm.prototype.hex;zm.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,o=this.h4,i=this.h5,s=this.h6,a=this.h7,l=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255];return this.is224||l.push(a>>>24&255,a>>>16&255,a>>>8&255,a&255),l};zm.prototype.array=zm.prototype.digest;zm.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};Xue=(...t)=>new zm(!1,!0).update(t.join("")).hex()});var d4e=C(()=>{$n();Que()});var cOt,uOt,dOt,f4e,m4e=C(()=>{$n();Que();d4e();Dm();cOt=(...t)=>Xue(t.join("_")),uOt=class{constructor(){I(this,"keyEncoder",cOt)}makeDefaultKeyEncoder(t){this.keyEncoder=t}},dOt=new Map,f4e=class p4e extends uOt{constructor(n){super();I(this,"cache");this.cache=n??new Map}lookup(n,r){return Promise.resolve(this.cache.get(this.keyEncoder(n,r))??null)}async update(n,r,o){this.cache.set(this.keyEncoder(n,r),o)}static global(){return new p4e(dOt)}}});var ede,o5,i5,h4e,tU=C(()=>{$n();Rb();Bb();Dm();ede=class extends zu{},o5=class extends ede{constructor(e){super({value:e});I(this,"lc_namespace",["langchain_core","prompt_values"]);I(this,"lc_serializable",!0);I(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new Zo(this.value)]}},i5=class extends ede{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);I(this,"lc_namespace",["langchain_core","prompt_values"]);I(this,"lc_serializable",!0);I(this,"messages");this.messages=e.messages}static lc_name(){return"ChatPromptValue"}toString(){return ui(this.messages)}toChatMessages(){return this.messages}},h4e=class extends ede{constructor(e){"imageUrl"in e||(e={imageUrl:e});super(e);I(this,"lc_namespace",["langchain_core","prompt_values"]);I(this,"lc_serializable",!0);I(this,"imageUrl");I(this,"value");this.imageUrl=e.imageUrl}static lc_name(){return"ImagePromptValue"}toString(){return this.imageUrl.url}toChatMessages(){return[new Zo({content:[{type:"image_url",image_url:{detail:this.imageUrl.detail,url:this.imageUrl.url}}]})]}}});function hOt(t,e){let n=Array.from({length:t.length},(r,o)=>({start:o,end:o+1}));for(;n.length>1;){let r=null;for(let o=0;o<n.length-1;o++){let i=t.slice(n[o].start,n[o+1].end),s=e.get(i.join(","));s!=null&&(r==null||s<r[0])&&(r=[s,o])}if(r!=null){let o=r[1];n[o]={start:n[o].start,end:n[o+1].end},n.splice(o+1,1)}else break}return n}function gOt(t,e){return t.length===1?[e.get(t.join(","))]:hOt(t,e).map(n=>e.get(t.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function yOt(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}function nde(t){switch(t){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":return"o200k_base";default:throw new Error("Unknown model")}}var g4e,fOt,pOt,mOt,tde,s5,y4e=C(()=>{g4e=N(uee(),1),fOt=Object.defineProperty,pOt=(t,e,n)=>e in t?fOt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,mOt=(t,e,n)=>(pOt(t,typeof e!="symbol"?e+"":e,n),n);tde=class{constructor(t,e){I(this,"specialTokens");I(this,"inverseSpecialTokens");I(this,"patStr");I(this,"textEncoder",new TextEncoder);I(this,"textDecoder",new TextDecoder("utf-8"));I(this,"rankMap",new Map);I(this,"textMap",new Map);this.patStr=t.pat_str;let n=t.bpe_ranks.split(`
`).filter(Boolean).reduce((r,o)=>{let[i,s,...a]=o.split(" "),l=Number.parseInt(s,10);return a.forEach((c,u)=>r[c]=l+u),r},{});for(let[r,o]of Object.entries(n)){let i=g4e.default.toByteArray(r);this.rankMap.set(i.join(","),o),this.textMap.set(o,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[o,i])=>(r[i]=this.textEncoder.encode(o),r),{})}encode(t,e=[],n="all"){let r=new RegExp(this.patStr,"ug"),o=tde.specialTokenRegex(Object.keys(this.specialTokens)),i=[],s=new Set(e==="all"?Object.keys(this.specialTokens):e),a=new Set(n==="all"?Object.keys(this.specialTokens).filter(c=>!s.has(c)):n);if(a.size>0){let c=tde.specialTokenRegex([...a]),u=t.match(c);if(u!=null)throw new Error(`The text contains a special token that is not allowed: ${u[0]}`)}let l=0;for(;;){let c=null,u=l;for(;o.lastIndex=u,c=o.exec(t),!(c==null||s.has(c[0]));)u=c.index+1;let d=c?.index??t.length;for(let p of t.substring(l,d).matchAll(r)){let m=this.textEncoder.encode(p[0]),h=this.rankMap.get(m.join(","));if(h!=null){i.push(h);continue}i.push(...gOt(m,this.rankMap))}if(c==null)break;let f=this.specialTokens[c[0]];i.push(f),l=c.index+c[0].length}return i}decode(t){let e=[],n=0;for(let i=0;i<t.length;++i){let s=t[i],a=this.textMap.get(s)??this.inverseSpecialTokens[s];a!=null&&(e.push(a),n+=a.length)}let r=new Uint8Array(n),o=0;for(let i of e)r.set(i,o),o+=i.length;return this.textDecoder.decode(r)}},s5=tde;mOt(s5,"specialTokenRegex",t=>new RegExp(t.map(e=>yOt(e)).join("|"),"g"))});var w4e=C(()=>{y4e()});async function v4e(t){return t in a5||(a5[t]=wOt.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new s5(e)).catch(e=>{throw delete a5[t],e})),await a5[t]}async function x4e(t){return v4e(nde(t))}var a5,wOt,rde=C(()=>{$n();X2();w4e();a5={},wOt=new qb({})});function Rg(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}var vOt,xOt,nU,mI,qd=C(()=>{$n();Dm();m4e();X2();Ra();tU();rde();vOt=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t;xOt=()=>!1,nU=class extends gr{constructor(e){super(e);I(this,"verbose");I(this,"callbacks");I(this,"tags");I(this,"metadata");this.verbose=e.verbose??xOt(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.1.46")}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}_addVersion(e,n){let r=this.metadata?.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:n}}}},mI=class extends nU{constructor({callbacks:e,callbackManager:n,...r}){let{cache:o,...i}=r;super({callbacks:e??n,...i});I(this,"caller");I(this,"cache");I(this,"_encoding");typeof o=="object"?this.cache=o:o?this.cache=f4e.global():this.cache=void 0,this.caller=new qb(r??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let n;typeof e=="string"?n=e:n=e.map(o=>typeof o=="string"?o:o.type==="text"&&"text"in o?o.text:"").join("");let r=Math.ceil(n.length/4);if(!this._encoding)try{this._encoding=await x4e("modelName"in this?vOt(this.modelName):"gpt2")}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}if(this._encoding)try{r=this._encoding.encode(n).length}catch(o){console.warn("Failed to calculate number of tokens, falling back to approximate count",o)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new o5(e):Array.isArray(e)?new i5(e.map(Lm)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...n}){let r={...this._identifyingParams(),...n,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([o,i])=>i!==void 0).map(([o,i])=>`${o}:${JSON.stringify(i)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}_filterInvocationParamsForTracing(e){let{tools:n,functions:r,messages:o,response_format:i,...s}=e;return s}}});function _Ot(t){return rc.isInstance(t)?t.role:t.type}function SOt(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function TOt(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function IOt(t,e){return e.map(n=>rp(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function POt(t){return{providerName:"Google Gemini",fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(e){if(!t)throw new Error("This model does not support images");if(e.source_type==="url"){let n=Bc({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardAudioBlock(e){if(!t)throw new Error("This model does not support audio");if(e.source_type==="url"){let n=Bc({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardFileBlock(e){if(!t)throw new Error("This model does not support files");if(e.source_type==="text")return{text:e.text};if(e.source_type==="url"){let n=Bc({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)}}}function b4e(t,e){if(tc(t))return kw(t,POt(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");let[r,o]=n.split(",");if(!r.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");let[i,s]=r.replace(/^data:/,"").split(";");if(s!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:o,mimeType:i}}}else{if(t.type==="media")return TOt(t);if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type==="tool_call")return{functionCall:{name:t.name,args:t.args}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}function EOt(t,e,n,r){if(Ale(t)){let a=t.name??IOt(t,n);if(a===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);let l=Array.isArray(t.content)?t.content.map(c=>b4e(c,e)).filter(c=>c!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:a,response:{error:{details:l}}}}]:[{functionResponse:{name:a,response:{result:l}}}]}let o=[],i=[];typeof t.content=="string"&&t.content&&i.push({text:t.content}),Array.isArray(t.content)&&i.push(...t.content.map(a=>b4e(a,e)).filter(a=>a!==void 0));let s=t.additional_kwargs?.[ode];return rp(t)&&t.tool_calls?.length&&(o=t.tool_calls.map(a=>{let l=COt(()=>{if(a.id){let c=s?.[a.id];if(c)return c}return r?.includes("gemini-3")?bOt:""});return{functionCall:{name:a.name,args:a.args},...l?{thoughtSignature:l}:{}}})),[...i,...o]}function ide(t,e,n=!1,r){return t.reduce((o,i,s)=>{if(!np(i))throw new Error("Unsupported message input");let a=_Ot(i);if(a==="system"&&s!==0)throw new Error("System message should be the first one");let l=SOt(a),c=o.content[o.content.length];if(!o.mergeWithPreviousContent&&c&&c.role===l)throw new Error("Google Generative AI requires alternate messages between authors");let u=EOt(i,e,t.slice(0,s),r);if(o.mergeWithPreviousContent){let p=o.content[o.content.length-1];if(!p)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return p.parts.push(...u),{mergeWithPreviousContent:!1,content:o.content}}let d=l;(d==="function"||d==="system"&&!n)&&(d="user");let f={role:d,parts:u};return{mergeWithPreviousContent:a==="system"&&!n,content:[...o.content,f]}},{content:[],mergeWithPreviousContent:!1}).content}function C4e(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};let[n]=t.candidates,{content:r,...o}=n,i=r.parts?.reduce((u,d)=>("functionCall"in d&&d.functionCall&&u.push({...d,id:"id"in d.functionCall&&typeof d.functionCall.id=="string"?d.functionCall.id:si()}),u),[]),s,a=r?.parts;Array.isArray(a)&&a.length===1&&"text"in a[0]&&a[0].text&&!a[0].thought?s=a[0].text:Array.isArray(a)&&a.length>0?s=a.map(u=>u.thought&&"text"in u&&u.text?{type:"thinking",thinking:u.text,...u.thoughtSignature?{signature:u.thoughtSignature}:{}}:"text"in u?{type:"text",text:u.text}:"inlineData"in u?{type:"inlineData",inlineData:u.inlineData}:"functionCall"in u?{type:"functionCall",functionCall:u.functionCall}:"functionResponse"in u?{type:"functionResponse",functionResponse:u.functionResponse}:"fileData"in u?{type:"fileData",fileData:u.fileData}:"executableCode"in u?{type:"executableCode",executableCode:u.executableCode}:"codeExecutionResult"in u?{type:"codeExecutionResult",codeExecutionResult:u.codeExecutionResult}:u):s=[];let l=i?.reduce((u,d)=>("thoughtSignature"in d&&typeof d.thoughtSignature=="string"&&(u[d.id]=d.thoughtSignature),u),{}),c="";return typeof s=="string"?c=s:Array.isArray(s)&&s.length>0&&(c=s.find(u=>"text"in u)?.text??c),{generations:[{text:c,message:new kn({content:s??"",tool_calls:i?.map(u=>({type:"tool_call",id:u.id,name:u.functionCall.name,args:u.functionCall.args})),additional_kwargs:{...o,[ode]:l},usage_metadata:e?.usageMetadata}),generationInfo:o}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function _4e(t,e){if(!t.candidates||t.candidates.length===0)return null;let[n]=t.candidates,{content:r,...o}=n,i=r.parts?.reduce((d,f)=>("functionCall"in f&&f.functionCall&&d.push({...f,id:"id"in f.functionCall&&typeof f.functionCall.id=="string"?f.functionCall.id:si()}),d),[]),s,a=r?.parts;Array.isArray(a)&&a.every(d=>"text"in d&&!d.thought)?s=a.map(d=>d.text).join(""):Array.isArray(a)?s=a.map(d=>d.thought&&"text"in d&&d.text?{type:"thinking",thinking:d.text,...d.thoughtSignature?{signature:d.thoughtSignature}:{}}:"text"in d?{type:"text",text:d.text}:"inlineData"in d?{type:"inlineData",inlineData:d.inlineData}:"functionCall"in d?{type:"functionCall",functionCall:d.functionCall}:"functionResponse"in d?{type:"functionResponse",functionResponse:d.functionResponse}:"fileData"in d?{type:"fileData",fileData:d.fileData}:"executableCode"in d?{type:"executableCode",executableCode:d.executableCode}:"codeExecutionResult"in d?{type:"codeExecutionResult",codeExecutionResult:d.codeExecutionResult}:d):s=[];let l="";s&&typeof s=="string"?l=s:Array.isArray(s)&&(l=s.find(d=>"text"in d)?.text??"");let c=[];i&&c.push(...i.map(d=>({type:"tool_call_chunk",id:d.id,name:d.functionCall.name,args:JSON.stringify(d.functionCall.args)})));let u=i?.reduce((d,f)=>("thoughtSignature"in f&&typeof f.thoughtSignature=="string"&&(d[f.id]=f.thoughtSignature),d),{});return new Jr({text:l,message:new Yt({content:s||"",name:r?r.role:void 0,tool_call_chunks:c,additional_kwargs:{[ode]:u},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:o})}function S4e(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(cp(e)){let n=v2(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:(YT(n,e.name),{name:e.name,description:e.description,parameters:n})}if(Rg(e)){let n=z$e(e.function.parameters);return YT(n,e.function.name),{name:e.function.name,description:e.function.description??"A function available to call.",parameters:n}}return e})}]}function sde(t,e){let n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??(n.input_token_details={}),n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){let r=Math.max(0,t?.promptTokenCount??-2e5),o=Math.max(0,t?.cachedContentTokenCount??-2e5);r&&(n.input_token_details={...n.input_token_details,over_200k:r}),o&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:o})}return n}var ode,bOt,COt,ade=C(()=>{E3();j$e();Kr();ac();pI();qd();qh();ode="__gemini_function_call_thought_signatures__",bOt="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",COt=t=>t()});var xl,l5=C(()=>{Ng();Og();Ra();xl=class extends gr{constructor(e){super(e);I(this,"lc_namespace",["langchain_core","runnables"]);I(this,"lc_serializable",!0);I(this,"func");e&&(this.func=e.func)}static lc_name(){return"RunnablePassthrough"}async invoke(e,n){let r=fr(n);return this.func&&await this.func(e,r),this._callWithConfig(o=>Promise.resolve(o),e,r)}async*transform(e,n){let r=fr(n),o,i=!0;for await(let s of this._transformStreamWithConfig(e,a=>a,r))if(yield s,i)if(o===void 0)o=s;else try{o=Um(o,s)}catch{o=void 0,i=!1}this.func&&o!==void 0&&await this.func(o,r)}static assign(e){return new n5(new sM({steps:e}))}}});var T4e=C(()=>{Ng();Ra()});var I4e=C(()=>{Ng();Og();Ra()});var P4e=C(()=>{nc();Wu();Bb();Ra();Kr();l5()});var jm=C(()=>{$n();Ng();rM();Ra();l5();T4e();I4e();P4e()});var aM,Fw,lc,hI=C(()=>{JT();Ra();jm();aM=class extends gr{parseResultWithPrompt(t,e,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r?.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r?.callbacks),t,{...e,runType:"parser"})}},Fw=class extends aM{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},lc=class extends Error{constructor(e,n,r,o=!1){super(e);I(this,"llmOutput");I(this,"observation");I(this,"sendToLLM");if(this.llmOutput=n,this.observation=r,this.sendToLLM=o,o&&(r===void 0||n===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");Lb(this,"OUTPUT_PARSING_FAILURE")}}});var rU,lM,Yb=C(()=>{nc();Dm();ac();hI();P3();rU=class extends Fw{async*_transform(t){for await(let e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},lM=class extends rU{constructor(e){super(e);I(this,"diff",!1);this.diff=e?.diff??this.diff}async*_transform(e){let n,r;for await(let o of e){if(typeof o!="string"&&typeof o.content!="string")throw new Error("Cannot handle non-string output.");let i;if(O3(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new Jr({message:o,text:o.content})}else if(np(o)){if(typeof o.content!="string")throw new Error("Cannot handle non-string message output.");i=new Jr({message:B3(o),text:o.content})}else i=new Lw({text:o});r===void 0?r=i:r=r.concat(i);let s=await this.parsePartialResult([r]);s!=null&&!Pw(s,n)&&(this.diff?yield this._diff(n,s):yield s,n=s)}}getFormatInstructions(){return""}}});var E4e=C(()=>{Yb()});var A4e=C(()=>{hI();Yb()});var k4e=C(()=>{Yb()});var lde=C(()=>{$n();Y2();Z2();Rue()});var Gd,oU=C(()=>{Wk();Z2();Yb();lde();Gd=class extends lM{constructor(){super(...arguments);I(this,"lc_namespace",["langchain_core","output_parsers"]);I(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,n){return this.diff?super._concatOutputChunks(e,n):n}_diff(e,n){if(n)return e?YK(e,n):[{op:"replace",path:"",value:n}]}async parsePartialResult(e){return jk(e[0].text)}async parse(e){return jk(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}}});var cde,ude=C(()=>{Wk();hI();oU();cde=class extends Fw{constructor(e){super();I(this,"lc_namespace",["langchain","output_parsers","standard_schema"]);I(this,"schema");this.schema=e}static lc_name(){return"StandardSchemaOutputParser"}static fromSerializableSchema(e){return new this(e)}async parse(e){try{let n=jk(e,JSON.parse),r=await this.schema["~standard"].validate(n);if(r.issues)throw new Error(`Validation failed: ${JSON.stringify(r.issues)}`);return r.value}catch(n){throw new lc(`Failed to parse. Text: "${e}". Error: ${n}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return""}}});var Vm,dde=C(()=>{vg();Bu();hI();_g();Vm=class extends Fw{constructor(e){super(e);I(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){let n=we.object(Object.fromEntries(Object.entries(e).map(([r,o])=>[r,we.string().describe(o)])));return new this(n)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.

"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.

For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.

Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!

Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(Hr(this.schema))}
\`\`\`
`}async parse(e){try{let n=e.trim(),r=(n.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||n.match(/```json\s*([\s\S]*?)```/)?.[1]||n).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(o,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await MT(this.schema,JSON.parse(r))}catch(n){throw new lc(`Failed to parse. Text: "${e}". Error: ${n}`,e)}}_baseMessageToString(e){return e.text}}});var AOt,kOt,M4e=C(()=>{AOt=function(){let t={};t.parser=function(M,E){return new n(M,E)},t.SAXParser=n,t.SAXStream=c,t.createStream=l,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(M,E){if(!(this instanceof n))return new n(M,E);var R=this;o(R),R.q=R.c="",R.bufferCheckPosition=t.MAX_BUFFER_LENGTH,R.opt=E||{},R.opt.lowercase=R.opt.lowercase||R.opt.lowercasetags,R.looseCase=R.opt.lowercase?"toLowerCase":"toUpperCase",R.tags=[],R.closed=R.closedRoot=R.sawRoot=!1,R.tag=R.error=null,R.strict=!!M,R.noscript=!!(M||R.opt.noscript),R.state=S.BEGIN,R.strictEntities=R.opt.strictEntities,R.ENTITIES=R.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),R.attribList=[],R.opt.xmlns&&(R.ns=Object.create(m)),R.trackPosition=R.opt.position!==!1,R.trackPosition&&(R.position=R.line=R.column=0),A(R,"onready")}Object.create||(Object.create=function(M){function E(){}return E.prototype=M,new E}),Object.keys||(Object.keys=function(M){var E=[];for(var R in M)M.hasOwnProperty(R)&&E.push(R);return E});function r(M){for(var E=Math.max(t.MAX_BUFFER_LENGTH,10),R=0,L=0,K=e.length;L<K;L++){var Y=M[e[L]].length;if(Y>E)switch(e[L]){case"textNode":D(M);break;case"cdata":O(M,"oncdata",M.cdata),M.cdata="";break;case"script":O(M,"onscript",M.script),M.script="";break;default:B(M,"Max buffer length exceeded: "+e[L])}R=Math.max(R,Y)}M.bufferCheckPosition=t.MAX_BUFFER_LENGTH-R+M.position}function o(M){for(var E=0,R=e.length;E<R;E++)M[e[E]]=""}function i(M){D(M),M.cdata!==""&&(O(M,"oncdata",M.cdata),M.cdata=""),M.script!==""&&(O(M,"onscript",M.script),M.script="")}n.prototype={end:function(){W(this)},write:J,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){i(this)}};var s=ReadableStream;s||(s=function(){});var a=t.EVENTS.filter(function(M){return M!=="error"&&M!=="end"});function l(M,E){return new c(M,E)}function c(M,E){if(!(this instanceof c))return new c(M,E);s.apply(this),this._parser=new n(M,E),this.writable=!0,this.readable=!0;var R=this;this._parser.onend=function(){R.emit("end")},this._parser.onerror=function(L){R.emit("error",L),R._parser.error=null},this._decoder=null,a.forEach(function(L){Object.defineProperty(R,"on"+L,{get:function(){return R._parser["on"+L]},set:function(K){if(!K)return R.removeAllListeners(L),R._parser["on"+L]=K,K;R.on(L,K)},enumerable:!0,configurable:!1})})}c.prototype=Object.create(s.prototype,{constructor:{value:c}}),c.prototype.write=function(M){return this._parser.write(M.toString()),this.emit("data",M),!0},c.prototype.end=function(M){return M&&M.length&&this.write(M),this._parser.end(),!0},c.prototype.on=function(M,E){var R=this;return!R._parser["on"+M]&&a.indexOf(M)!==-1&&(R._parser["on"+M]=function(){var L=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);L.splice(0,0,M),R.emit.apply(R,L)}),s.prototype.on.call(R,M,E)};var u="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",p="http://www.w3.org/2000/xmlns/",m={xml:f,xmlns:p},h=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,g=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,y=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,w=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function v(M){return M===" "||M===`
`||M==="\r"||M==="	"}function x(M){return M==='"'||M==="'"}function b(M){return M===">"||v(M)}function _(M,E){return M.test(E)}function T(M,E){return!_(M,E)}var S=0;t.STATE={BEGIN:S++,BEGIN_WHITESPACE:S++,TEXT:S++,TEXT_ENTITY:S++,OPEN_WAKA:S++,SGML_DECL:S++,SGML_DECL_QUOTED:S++,DOCTYPE:S++,DOCTYPE_QUOTED:S++,DOCTYPE_DTD:S++,DOCTYPE_DTD_QUOTED:S++,COMMENT_STARTING:S++,COMMENT:S++,COMMENT_ENDING:S++,COMMENT_ENDED:S++,CDATA:S++,CDATA_ENDING:S++,CDATA_ENDING_2:S++,PROC_INST:S++,PROC_INST_BODY:S++,PROC_INST_ENDING:S++,OPEN_TAG:S++,OPEN_TAG_SLASH:S++,ATTRIB:S++,ATTRIB_NAME:S++,ATTRIB_NAME_SAW_WHITE:S++,ATTRIB_VALUE:S++,ATTRIB_VALUE_QUOTED:S++,ATTRIB_VALUE_CLOSED:S++,ATTRIB_VALUE_UNQUOTED:S++,ATTRIB_VALUE_ENTITY_Q:S++,ATTRIB_VALUE_ENTITY_U:S++,CLOSE_TAG:S++,CLOSE_TAG_SAW_WHITE:S++,SCRIPT:S++,SCRIPT_ENDING:S++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(M){var E=t.ENTITIES[M],R=typeof E=="number"?String.fromCharCode(E):E;t.ENTITIES[M]=R});for(var P in t.STATE)t.STATE[t.STATE[P]]=P;S=t.STATE;function A(M,E,R){M[E]&&M[E](R)}function O(M,E,R){M.textNode&&D(M),A(M,E,R)}function D(M){M.textNode=$(M.opt,M.textNode),M.textNode&&A(M,"ontext",M.textNode),M.textNode=""}function $(M,E){return M.trim&&(E=E.trim()),M.normalize&&(E=E.replace(/\s+/g," ")),E}function B(M,E){return D(M),M.trackPosition&&(E+=`
Line: `+M.line+`
Column: `+M.column+`
Char: `+M.c),E=new Error(E),M.error=E,A(M,"onerror",E),M}function W(M){return M.sawRoot&&!M.closedRoot&&F(M,"Unclosed root tag"),M.state!==S.BEGIN&&M.state!==S.BEGIN_WHITESPACE&&M.state!==S.TEXT&&B(M,"Unexpected end"),D(M),M.c="",M.closed=!0,A(M,"onend"),n.call(M,M.strict,M.opt),M}function F(M,E){if(typeof M!="object"||!(M instanceof n))throw new Error("bad call to strictFail");M.strict&&B(M,E)}function Z(M){M.strict||(M.tagName=M.tagName[M.looseCase]());var E=M.tags[M.tags.length-1]||M,R=M.tag={name:M.tagName,attributes:{}};M.opt.xmlns&&(R.ns=E.ns),M.attribList.length=0,O(M,"onopentagstart",R)}function V(M,E){var R=M.indexOf(":")<0?["",M]:M.split(":"),L=R[0],K=R[1];return E&&M==="xmlns"&&(L="xmlns",K=""),{prefix:L,local:K}}function H(M){if(M.strict||(M.attribName=M.attribName[M.looseCase]()),M.attribList.indexOf(M.attribName)!==-1||M.tag.attributes.hasOwnProperty(M.attribName)){M.attribName=M.attribValue="";return}if(M.opt.xmlns){var E=V(M.attribName,!0),R=E.prefix,L=E.local;if(R==="xmlns")if(L==="xml"&&M.attribValue!==f)F(M,"xml: prefix must be bound to "+f+`
Actual: `+M.attribValue);else if(L==="xmlns"&&M.attribValue!==p)F(M,"xmlns: prefix must be bound to "+p+`
Actual: `+M.attribValue);else{var K=M.tag,Y=M.tags[M.tags.length-1]||M;K.ns===Y.ns&&(K.ns=Object.create(Y.ns)),K.ns[L]=M.attribValue}M.attribList.push([M.attribName,M.attribValue])}else M.tag.attributes[M.attribName]=M.attribValue,O(M,"onattribute",{name:M.attribName,value:M.attribValue});M.attribName=M.attribValue=""}function te(M,E){if(M.opt.xmlns){var R=M.tag,L=V(M.tagName);R.prefix=L.prefix,R.local=L.local,R.uri=R.ns[L.prefix]||"",R.prefix&&!R.uri&&(F(M,"Unbound namespace prefix: "+JSON.stringify(M.tagName)),R.uri=L.prefix);var K=M.tags[M.tags.length-1]||M;R.ns&&K.ns!==R.ns&&Object.keys(R.ns).forEach(function(Ln){O(M,"onopennamespace",{prefix:Ln,uri:R.ns[Ln]})});for(var Y=0,re=M.attribList.length;Y<re;Y++){var ae=M.attribList[Y],ve=ae[0],Te=ae[1],Ee=V(ve,!0),nt=Ee.prefix,rt=Ee.local,Jt=nt===""?"":R.ns[nt]||"",ke={name:ve,value:Te,prefix:nt,local:rt,uri:Jt};nt&&nt!=="xmlns"&&!Jt&&(F(M,"Unbound namespace prefix: "+JSON.stringify(nt)),ke.uri=nt),M.tag.attributes[ve]=ke,O(M,"onattribute",ke)}M.attribList.length=0}M.tag.isSelfClosing=!!E,M.sawRoot=!0,M.tags.push(M.tag),O(M,"onopentag",M.tag),E||(!M.noscript&&M.tagName.toLowerCase()==="script"?M.state=S.SCRIPT:M.state=S.TEXT,M.tag=null,M.tagName=""),M.attribName=M.attribValue="",M.attribList.length=0}function fe(M){if(!M.tagName){F(M,"Weird empty close tag."),M.textNode+="</>",M.state=S.TEXT;return}if(M.script){if(M.tagName!=="script"){M.script+="</"+M.tagName+">",M.tagName="",M.state=S.SCRIPT;return}O(M,"onscript",M.script),M.script=""}var E=M.tags.length,R=M.tagName;M.strict||(R=R[M.looseCase]());for(var L=R;E--&&M.tags[E].name!==L;)F(M,"Unexpected close tag");if(E<0){F(M,"Unmatched closing tag: "+M.tagName),M.textNode+="</"+M.tagName+">",M.state=S.TEXT;return}M.tagName=R;for(var K=M.tags.length;K-- >E;){var Y=M.tag=M.tags.pop();M.tagName=M.tag.name,O(M,"onclosetag",M.tagName);var re={};for(var ae in Y.ns)re[ae]=Y.ns[ae];var ve=M.tags[M.tags.length-1]||M;M.opt.xmlns&&Y.ns!==ve.ns&&Object.keys(Y.ns).forEach(function(Te){var Ee=Y.ns[Te];O(M,"onclosenamespace",{prefix:Te,uri:Ee})})}E===0&&(M.closedRoot=!0),M.tagName=M.attribValue=M.attribName="",M.attribList.length=0,M.state=S.TEXT}function me(M){var E=M.entity,R=E.toLowerCase(),L,K="";return M.ENTITIES[E]?M.ENTITIES[E]:M.ENTITIES[R]?M.ENTITIES[R]:(E=R,E.charAt(0)==="#"&&(E.charAt(1)==="x"?(E=E.slice(2),L=parseInt(E,16),K=L.toString(16)):(E=E.slice(1),L=parseInt(E,10),K=L.toString(10))),E=E.replace(/^0+/,""),isNaN(L)||K.toLowerCase()!==E?(F(M,"Invalid character entity"),"&"+M.entity+";"):String.fromCodePoint(L))}function j(M,E){E==="<"?(M.state=S.OPEN_WAKA,M.startTagPosition=M.position):v(E)||(F(M,"Non-whitespace before first tag."),M.textNode=E,M.state=S.TEXT)}function G(M,E){var R="";return E<M.length&&(R=M.charAt(E)),R}function J(M){var E=this;if(this.error)throw this.error;if(E.closed)return B(E,"Cannot write after close. Assign an onready handler.");if(M===null)return W(E);typeof M=="object"&&(M=M.toString());for(var R=0,L="";L=G(M,R++),E.c=L,!!L;)switch(E.trackPosition&&(E.position++,L===`
`?(E.line++,E.column=0):E.column++),E.state){case S.BEGIN:if(E.state=S.BEGIN_WHITESPACE,L==="\uFEFF")continue;j(E,L);continue;case S.BEGIN_WHITESPACE:j(E,L);continue;case S.TEXT:if(E.sawRoot&&!E.closedRoot){for(var K=R-1;L&&L!=="<"&&L!=="&";)L=G(M,R++),L&&E.trackPosition&&(E.position++,L===`
`?(E.line++,E.column=0):E.column++);E.textNode+=M.substring(K,R-1)}L==="<"&&!(E.sawRoot&&E.closedRoot&&!E.strict)?(E.state=S.OPEN_WAKA,E.startTagPosition=E.position):(!v(L)&&(!E.sawRoot||E.closedRoot)&&F(E,"Text data outside of root node."),L==="&"?E.state=S.TEXT_ENTITY:E.textNode+=L);continue;case S.SCRIPT:L==="<"?E.state=S.SCRIPT_ENDING:E.script+=L;continue;case S.SCRIPT_ENDING:L==="/"?E.state=S.CLOSE_TAG:(E.script+="<"+L,E.state=S.SCRIPT);continue;case S.OPEN_WAKA:if(L==="!")E.state=S.SGML_DECL,E.sgmlDecl="";else if(!v(L))if(_(h,L))E.state=S.OPEN_TAG,E.tagName=L;else if(L==="/")E.state=S.CLOSE_TAG,E.tagName="";else if(L==="?")E.state=S.PROC_INST,E.procInstName=E.procInstBody="";else{if(F(E,"Unencoded <"),E.startTagPosition+1<E.position){var Y=E.position-E.startTagPosition;L=new Array(Y).join(" ")+L}E.textNode+="<"+L,E.state=S.TEXT}continue;case S.SGML_DECL:(E.sgmlDecl+L).toUpperCase()===u?(O(E,"onopencdata"),E.state=S.CDATA,E.sgmlDecl="",E.cdata=""):E.sgmlDecl+L==="--"?(E.state=S.COMMENT,E.comment="",E.sgmlDecl=""):(E.sgmlDecl+L).toUpperCase()===d?(E.state=S.DOCTYPE,(E.doctype||E.sawRoot)&&F(E,"Inappropriately located doctype declaration"),E.doctype="",E.sgmlDecl=""):L===">"?(O(E,"onsgmldeclaration",E.sgmlDecl),E.sgmlDecl="",E.state=S.TEXT):(x(L)&&(E.state=S.SGML_DECL_QUOTED),E.sgmlDecl+=L);continue;case S.SGML_DECL_QUOTED:L===E.q&&(E.state=S.SGML_DECL,E.q=""),E.sgmlDecl+=L;continue;case S.DOCTYPE:L===">"?(E.state=S.TEXT,O(E,"ondoctype",E.doctype),E.doctype=!0):(E.doctype+=L,L==="["?E.state=S.DOCTYPE_DTD:x(L)&&(E.state=S.DOCTYPE_QUOTED,E.q=L));continue;case S.DOCTYPE_QUOTED:E.doctype+=L,L===E.q&&(E.q="",E.state=S.DOCTYPE);continue;case S.DOCTYPE_DTD:E.doctype+=L,L==="]"?E.state=S.DOCTYPE:x(L)&&(E.state=S.DOCTYPE_DTD_QUOTED,E.q=L);continue;case S.DOCTYPE_DTD_QUOTED:E.doctype+=L,L===E.q&&(E.state=S.DOCTYPE_DTD,E.q="");continue;case S.COMMENT:L==="-"?E.state=S.COMMENT_ENDING:E.comment+=L;continue;case S.COMMENT_ENDING:L==="-"?(E.state=S.COMMENT_ENDED,E.comment=$(E.opt,E.comment),E.comment&&O(E,"oncomment",E.comment),E.comment=""):(E.comment+="-"+L,E.state=S.COMMENT);continue;case S.COMMENT_ENDED:L!==">"?(F(E,"Malformed comment"),E.comment+="--"+L,E.state=S.COMMENT):E.state=S.TEXT;continue;case S.CDATA:L==="]"?E.state=S.CDATA_ENDING:E.cdata+=L;continue;case S.CDATA_ENDING:L==="]"?E.state=S.CDATA_ENDING_2:(E.cdata+="]"+L,E.state=S.CDATA);continue;case S.CDATA_ENDING_2:L===">"?(E.cdata&&O(E,"oncdata",E.cdata),O(E,"onclosecdata"),E.cdata="",E.state=S.TEXT):L==="]"?E.cdata+="]":(E.cdata+="]]"+L,E.state=S.CDATA);continue;case S.PROC_INST:L==="?"?E.state=S.PROC_INST_ENDING:v(L)?E.state=S.PROC_INST_BODY:E.procInstName+=L;continue;case S.PROC_INST_BODY:if(!E.procInstBody&&v(L))continue;L==="?"?E.state=S.PROC_INST_ENDING:E.procInstBody+=L;continue;case S.PROC_INST_ENDING:L===">"?(O(E,"onprocessinginstruction",{name:E.procInstName,body:E.procInstBody}),E.procInstName=E.procInstBody="",E.state=S.TEXT):(E.procInstBody+="?"+L,E.state=S.PROC_INST_BODY);continue;case S.OPEN_TAG:_(g,L)?E.tagName+=L:(Z(E),L===">"?te(E):L==="/"?E.state=S.OPEN_TAG_SLASH:(v(L)||F(E,"Invalid character in tag name"),E.state=S.ATTRIB));continue;case S.OPEN_TAG_SLASH:L===">"?(te(E,!0),fe(E)):(F(E,"Forward-slash in opening tag not followed by >"),E.state=S.ATTRIB);continue;case S.ATTRIB:if(v(L))continue;L===">"?te(E):L==="/"?E.state=S.OPEN_TAG_SLASH:_(h,L)?(E.attribName=L,E.attribValue="",E.state=S.ATTRIB_NAME):F(E,"Invalid attribute name");continue;case S.ATTRIB_NAME:L==="="?E.state=S.ATTRIB_VALUE:L===">"?(F(E,"Attribute without value"),E.attribValue=E.attribName,H(E),te(E)):v(L)?E.state=S.ATTRIB_NAME_SAW_WHITE:_(g,L)?E.attribName+=L:F(E,"Invalid attribute name");continue;case S.ATTRIB_NAME_SAW_WHITE:if(L==="=")E.state=S.ATTRIB_VALUE;else{if(v(L))continue;F(E,"Attribute without value"),E.tag.attributes[E.attribName]="",E.attribValue="",O(E,"onattribute",{name:E.attribName,value:""}),E.attribName="",L===">"?te(E):_(h,L)?(E.attribName=L,E.state=S.ATTRIB_NAME):(F(E,"Invalid attribute name"),E.state=S.ATTRIB)}continue;case S.ATTRIB_VALUE:if(v(L))continue;x(L)?(E.q=L,E.state=S.ATTRIB_VALUE_QUOTED):(F(E,"Unquoted attribute value"),E.state=S.ATTRIB_VALUE_UNQUOTED,E.attribValue=L);continue;case S.ATTRIB_VALUE_QUOTED:if(L!==E.q){L==="&"?E.state=S.ATTRIB_VALUE_ENTITY_Q:E.attribValue+=L;continue}H(E),E.q="",E.state=S.ATTRIB_VALUE_CLOSED;continue;case S.ATTRIB_VALUE_CLOSED:v(L)?E.state=S.ATTRIB:L===">"?te(E):L==="/"?E.state=S.OPEN_TAG_SLASH:_(h,L)?(F(E,"No whitespace between attributes"),E.attribName=L,E.attribValue="",E.state=S.ATTRIB_NAME):F(E,"Invalid attribute name");continue;case S.ATTRIB_VALUE_UNQUOTED:if(!b(L)){L==="&"?E.state=S.ATTRIB_VALUE_ENTITY_U:E.attribValue+=L;continue}H(E),L===">"?te(E):E.state=S.ATTRIB;continue;case S.CLOSE_TAG:if(E.tagName)L===">"?fe(E):_(g,L)?E.tagName+=L:E.script?(E.script+="</"+E.tagName,E.tagName="",E.state=S.SCRIPT):(v(L)||F(E,"Invalid tagname in closing tag"),E.state=S.CLOSE_TAG_SAW_WHITE);else{if(v(L))continue;T(h,L)?E.script?(E.script+="</"+L,E.state=S.SCRIPT):F(E,"Invalid tagname in closing tag."):E.tagName=L}continue;case S.CLOSE_TAG_SAW_WHITE:if(v(L))continue;L===">"?fe(E):F(E,"Invalid characters in closing tag");continue;case S.TEXT_ENTITY:case S.ATTRIB_VALUE_ENTITY_Q:case S.ATTRIB_VALUE_ENTITY_U:var re,ae;switch(E.state){case S.TEXT_ENTITY:re=S.TEXT,ae="textNode";break;case S.ATTRIB_VALUE_ENTITY_Q:re=S.ATTRIB_VALUE_QUOTED,ae="attribValue";break;case S.ATTRIB_VALUE_ENTITY_U:re=S.ATTRIB_VALUE_UNQUOTED,ae="attribValue";break}if(L===";")if(E.opt.unparsedEntities){var ve=me(E);E.entity="",E.state=re,E.write(ve)}else E[ae]+=me(E),E.entity="",E.state=re;else _(E.entity.length?w:y,L)?E.entity+=L:(F(E,"Invalid character in entity name"),E[ae]+="&"+E.entity+L,E.entity="",E.state=re);continue;default:throw new Error(E,"Unknown state: "+E.state)}return E.position>=E.bufferCheckPosition&&r(E),E}return String.fromCodePoint||function(){var M=String.fromCharCode,E=Math.floor,R=function(){var L=16384,K=[],Y,re,ae=-1,ve=arguments.length;if(!ve)return"";for(var Te="";++ae<ve;){var Ee=Number(arguments[ae]);if(!isFinite(Ee)||Ee<0||Ee>1114111||E(Ee)!==Ee)throw RangeError("Invalid code point: "+Ee);Ee<=65535?K.push(Ee):(Ee-=65536,Y=(Ee>>10)+55296,re=Ee%1024+56320,K.push(Y,re)),(ae+1===ve||K.length>L)&&(Te+=M.apply(null,K),K.length=0)}return Te};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:R,configurable:!0,writable:!0}):String.fromCodePoint=R}(),t},kOt=AOt()});var N4e=C(()=>{Z2();Yb();lde();M4e()});var Uw=C(()=>{$n();Wk();hI();Yb();E4e();A4e();k4e();oU();ude();dde();N4e()});var fde,O4e=C(()=>{Bd();Uw();fde=class extends aM{constructor(e){super(e);I(this,"lc_namespace",["langchain","google_genai","output_parsers"]);I(this,"returnId",!1);I(this,"keyName");I(this,"returnSingle",!1);I(this,"zodSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}async _validateResult(e){if(this.zodSchema===void 0)return e;let n=await kT(this.zodSchema,e);if(n.success)return n.data;throw new lc(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(e){let n=e.flatMap(o=>{let{message:i}=o;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(n[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");let[r]=n;return await this._validateResult(r.args)}}});function LOt(t){let e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${ROt}/${OOt}`),e.join(" ")}async function DOt(t){var e;let n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",LOt(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let r=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(r){if(!(r instanceof Headers))try{r=new Headers(r)}catch(o){throw new Lg(`unable to convert customHeaders value ${JSON.stringify(r)} to Headers: ${o.message}`)}for(let[o,i]of r.entries()){if(o==="x-goog-api-key")throw new Lg(`Cannot set reserved header name ${o}`);if(o==="x-goog-api-client")throw new Lg(`Header name ${o} can only be set using the apiClient field`);n.append(o,i)}}return n}async function $Ot(t,e,n,r,o,i){let s=new pde(t,e,n,r,i);return{url:s.toString(),fetchOptions:Object.assign(Object.assign({},zOt(i)),{method:"POST",headers:await DOt(s),body:o})}}async function lU(t,e,n,r,o,i={},s=fetch){let{url:a,fetchOptions:l}=await $Ot(t,e,n,r,o,i);return FOt(a,l,s)}async function FOt(t,e,n=fetch){let r;try{r=await n(t,e)}catch(o){UOt(o,t)}return r.ok||await BOt(r,t),r}function UOt(t,e){let n=t;throw n.name==="AbortError"?(n=new d5(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof u5||t instanceof Lg||(n=new Da(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function BOt(t,e){let n="",r;try{let o=await t.json();n=o.error.message,o.error.details&&(n+=` ${JSON.stringify(o.error.details)}`,r=o.error.details)}catch{}throw new u5(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,r)}function zOt(t){let e={};if(t?.signal!==void 0||t?.timeout>=0){let n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function hde(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),c5(t.candidates[0]))throw new Zb(`${Jb(t)}`,t);return jOt(t)}else if(t.promptFeedback)throw new Zb(`Text not available. ${Jb(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),c5(t.candidates[0]))throw new Zb(`${Jb(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),W4e(t)[0]}else if(t.promptFeedback)throw new Zb(`Function call not available. ${Jb(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),c5(t.candidates[0]))throw new Zb(`${Jb(t)}`,t);return W4e(t)}else if(t.promptFeedback)throw new Zb(`Function call not available. ${Jb(t)}`,t)},t}function jOt(t){var e,n,r,o;let i=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(let s of(o=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||o===void 0?void 0:o.parts)s.text&&i.push(s.text),s.executableCode&&i.push("\n```"+s.executableCode.language+`
`+s.executableCode.code+"\n```\n"),s.codeExecutionResult&&i.push("\n```\n"+s.codeExecutionResult.output+"\n```\n");return i.length>0?i.join(""):""}function W4e(t){var e,n,r,o;let i=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(let s of(o=(r=t.candidates)===null||r===void 0?void 0:r[0].content)===null||o===void 0?void 0:o.parts)s.functionCall&&i.push(s.functionCall);if(i.length>0)return i}function c5(t){return!!t.finishReason&&VOt.includes(t.finishReason)}function Jb(t){var e,n,r;let o="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)o+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(o+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(o+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((r=t.candidates)===null||r===void 0)&&r[0]){let i=t.candidates[0];c5(i)&&(o+=`Candidate was blocked due to ${i.finishReason}`,i.finishMessage&&(o+=`: ${i.finishMessage}`))}return o}function sU(t){return this instanceof sU?(this.v=t,this):new sU(t)}function WOt(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,i=[];return o={},s("next"),s("throw"),s("return"),o[Symbol.asyncIterator]=function(){return this},o;function s(f){r[f]&&(o[f]=function(p){return new Promise(function(m,h){i.push([f,p,m,h])>1||a(f,p)})})}function a(f,p){try{l(r[f](p))}catch(m){d(i[0][3],m)}}function l(f){f.value instanceof sU?Promise.resolve(f.value.v).then(c,u):d(i[0][2],f)}function c(f){a("next",f)}function u(f){a("throw",f)}function d(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function HOt(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=GOt(e),[r,o]=n.tee();return{stream:qOt(r),response:KOt(o)}}async function KOt(t){let e=[],n=t.getReader();for(;;){let{done:r,value:o}=await n.read();if(r)return hde(YOt(e));e.push(o)}}function qOt(t){return WOt(this,arguments,function*(){let n=t.getReader();for(;;){let{value:r,done:o}=yield sU(n.read());if(o)break;yield yield sU(hde(r))}})}function GOt(t){let e=t.getReader();return new ReadableStream({start(r){let o="";return i();function i(){return e.read().then(({value:s,done:a})=>{if(a){if(o.trim()){r.error(new Da("Failed to parse stream"));return}r.close();return}o+=s;let l=o.match(H4e),c;for(;l;){try{c=JSON.parse(l[1])}catch{r.error(new Da(`Error parsing JSON response: "${l[1]}"`));return}r.enqueue(c),o=o.substring(l[0].length),l=o.match(H4e)}return i()}).catch(s=>{let a=s;throw a.stack=s.stack,a.name==="AbortError"?a=new d5("Request aborted when reading from the stream"):a=new Da("Error reading from the stream"),a})}}})}function YOt(t){let e=t[t.length-1],n={promptFeedback:e?.promptFeedback};for(let r of t){if(r.candidates){let o=0;for(let i of r.candidates)if(n.candidates||(n.candidates=[]),n.candidates[o]||(n.candidates[o]={index:o}),n.candidates[o].citationMetadata=i.citationMetadata,n.candidates[o].groundingMetadata=i.groundingMetadata,n.candidates[o].finishReason=i.finishReason,n.candidates[o].finishMessage=i.finishMessage,n.candidates[o].safetyRatings=i.safetyRatings,i.content&&i.content.parts){n.candidates[o].content||(n.candidates[o].content={role:i.content.role||"user",parts:[]});let s={};for(let a of i.content.parts)a.text&&(s.text=a.text),a.functionCall&&(s.functionCall=a.functionCall),a.executableCode&&(s.executableCode=a.executableCode),a.codeExecutionResult&&(s.codeExecutionResult=a.codeExecutionResult),Object.keys(s).length===0&&(s.text=""),n.candidates[o].content.parts.push(s)}o++}r.usageMetadata&&(n.usageMetadata=r.usageMetadata)}return n}async function Z4e(t,e,n,r){let o=await lU(e,yI.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),r);return HOt(o)}async function J4e(t,e,n,r){let i=await(await lU(e,yI.GENERATE_CONTENT,t,!1,JSON.stringify(n),r)).json();return{response:hde(i)}}function X4e(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function aU(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(let n of t)typeof n=="string"?e.push({text:n}):e.push(n);return ZOt(e)}function ZOt(t){let e={role:"user",parts:[]},n={role:"function",parts:[]},r=!1,o=!1;for(let i of t)"functionResponse"in i?(n.parts.push(i),o=!0):(e.parts.push(i),r=!0);if(r&&o)throw new Da("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!r&&!o)throw new Da("No content is provided for sending chat message.");return r?e:n}function JOt(t,e){var n;let r={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(n=e?.cachedContent)===null||n===void 0?void 0:n.name,contents:[]},o=t.generateContentRequest!=null;if(t.contents){if(o)throw new Lg("CountTokensRequest must have one of contents or generateContentRequest, not both.");r.contents=t.contents}else if(o)r=Object.assign(Object.assign({},r),t.generateContentRequest);else{let i=aU(t);r.contents=[i]}return{generateContentRequest:r}}function K4e(t){let e;return t.contents?e=t:e={contents:[aU(t)]},t.systemInstruction&&(e.systemInstruction=X4e(t.systemInstruction)),e}function XOt(t){return typeof t=="string"||Array.isArray(t)?{content:aU(t)}:t}function eRt(t){let e=!1;for(let n of t){let{role:r,parts:o}=n;if(!e&&r!=="user")throw new Da(`First content should be with role 'user', got ${r}`);if(!$4e.includes(r))throw new Da(`Each item should include role field. Got ${r} but valid roles are: ${JSON.stringify($4e)}`);if(!Array.isArray(o))throw new Da("Content should have 'parts' property with an array of Parts");if(o.length===0)throw new Da("Each Content should have at least one part");let i={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let a of o)for(let l of q4e)l in a&&(i[l]+=1);let s=QOt[r];for(let a of q4e)if(!s.includes(a)&&i[a]>0)throw new Da(`Content with role '${r}' can't contain '${a}' part`);e=!0}}function G4e(t){var e;if(t.candidates===void 0||t.candidates.length===0)return!1;let n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(let r of n.parts)if(r===void 0||Object.keys(r).length===0||r.text!==void 0&&r.text==="")return!1;return!0}async function tRt(t,e,n,r){return(await lU(e,yI.COUNT_TOKENS,t,!1,JSON.stringify(n),r)).json()}async function nRt(t,e,n,r){return(await lU(e,yI.EMBED_CONTENT,t,!1,JSON.stringify(n),r)).json()}async function rRt(t,e,n,r){let o=n.requests.map(s=>Object.assign(Object.assign({},s),{model:e}));return(await lU(e,yI.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:o}),r)).json()}var R4e,L4e,D4e,$4e,F4e,U4e,B4e,z4e,iU,j4e,gI,V4e,Da,Zb,u5,Lg,d5,MOt,NOt,OOt,ROt,yI,pde,VOt,H4e,q4e,QOt,Y4e,mde,f5,wI,p5=C(()=>{(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(R4e||(R4e={}));(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(L4e||(L4e={}));(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(D4e||(D4e={}));$4e=["user","model","function","system"];(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(F4e||(F4e={}));(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(U4e||(U4e={}));(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(B4e||(B4e={}));(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(z4e||(z4e={}));(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(iU||(iU={}));(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(j4e||(j4e={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(gI||(gI={}));(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(V4e||(V4e={}));Da=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},Zb=class extends Da{constructor(e,n){super(e),this.response=n}},u5=class extends Da{constructor(e,n,r,o){super(e),this.status=n,this.statusText=r,this.errorDetails=o}},Lg=class extends Da{},d5=class extends Da{};MOt="https://generativelanguage.googleapis.com",NOt="v1beta",OOt="0.24.1",ROt="genai-js";(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(yI||(yI={}));pde=class{constructor(e,n,r,o,i){this.model=e,this.task=n,this.apiKey=r,this.stream=o,this.requestOptions=i}toString(){var e,n;let r=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||NOt,i=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||MOt}/${r}/${this.model}:${this.task}`;return this.stream&&(i+="?alt=sse"),i}};VOt=[iU.RECITATION,iU.SAFETY,iU.LANGUAGE];H4e=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;q4e=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],QOt={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};Y4e="SILENT_ERROR",mde=class{constructor(e,n,r,o={}){this.model=n,this.params=r,this._requestOptions=o,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,r?.history&&(eRt(r.history),this._history=r.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,n={}){var r,o,i,s,a,l;await this._sendPromise;let c=aU(e),u={safetySettings:(r=this.params)===null||r===void 0?void 0:r.safetySettings,generationConfig:(o=this.params)===null||o===void 0?void 0:o.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(s=this.params)===null||s===void 0?void 0:s.toolConfig,systemInstruction:(a=this.params)===null||a===void 0?void 0:a.systemInstruction,cachedContent:(l=this.params)===null||l===void 0?void 0:l.cachedContent,contents:[...this._history,c]},d=Object.assign(Object.assign({},this._requestOptions),n),f;return this._sendPromise=this._sendPromise.then(()=>J4e(this._apiKey,this.model,u,d)).then(p=>{var m;if(G4e(p.response)){this._history.push(c);let h=Object.assign({parts:[],role:"model"},(m=p.response.candidates)===null||m===void 0?void 0:m[0].content);this._history.push(h)}else{let h=Jb(p.response);h&&console.warn(`sendMessage() was unsuccessful. ${h}. Inspect response object for details.`)}f=p}).catch(p=>{throw this._sendPromise=Promise.resolve(),p}),await this._sendPromise,f}async sendMessageStream(e,n={}){var r,o,i,s,a,l;await this._sendPromise;let c=aU(e),u={safetySettings:(r=this.params)===null||r===void 0?void 0:r.safetySettings,generationConfig:(o=this.params)===null||o===void 0?void 0:o.generationConfig,tools:(i=this.params)===null||i===void 0?void 0:i.tools,toolConfig:(s=this.params)===null||s===void 0?void 0:s.toolConfig,systemInstruction:(a=this.params)===null||a===void 0?void 0:a.systemInstruction,cachedContent:(l=this.params)===null||l===void 0?void 0:l.cachedContent,contents:[...this._history,c]},d=Object.assign(Object.assign({},this._requestOptions),n),f=Z4e(this._apiKey,this.model,u,d);return this._sendPromise=this._sendPromise.then(()=>f).catch(p=>{throw new Error(Y4e)}).then(p=>p.response).then(p=>{if(G4e(p)){this._history.push(c);let m=Object.assign({},p.candidates[0].content);m.role||(m.role="model"),this._history.push(m)}else{let m=Jb(p);m&&console.warn(`sendMessageStream() was unsuccessful. ${m}. Inspect response object for details.`)}}).catch(p=>{p.message!==Y4e&&console.error(p)}),f}};f5=class{constructor(e,n,r={}){this.apiKey=e,this._requestOptions=r,n.model.includes("/")?this.model=n.model:this.model=`models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=X4e(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(e,n={}){var r;let o=K4e(e),i=Object.assign(Object.assign({},this._requestOptions),n);return J4e(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},o),i)}async generateContentStream(e,n={}){var r;let o=K4e(e),i=Object.assign(Object.assign({},this._requestOptions),n);return Z4e(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},o),i)}startChat(e){var n;return new mde(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},e),this._requestOptions)}async countTokens(e,n={}){let r=JOt(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),o=Object.assign(Object.assign({},this._requestOptions),n);return tRt(this.apiKey,this.model,r,o)}async embedContent(e,n={}){let r=XOt(e),o=Object.assign(Object.assign({},this._requestOptions),n);return nRt(this.apiKey,this.model,r,o)}async batchEmbedContents(e,n={}){let r=Object.assign(Object.assign({},this._requestOptions),n);return rRt(this.apiKey,this.model,e,r)}};wI=class{constructor(e){this.apiKey=e}getGenerativeModel(e,n){if(!e.model)throw new Da("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new f5(this.apiKey,e,n)}getGenerativeModelFromCachedContent(e,n,r){if(!e.name)throw new Lg("Cached content must contain a `name` field.");if(!e.model)throw new Lg("Cached content must contain a `model` field.");let o=["model","systemInstruction"];for(let s of o)if(n?.[s]&&e[s]&&n?.[s]!==e[s]){if(s==="model"){let a=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,l=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(a===l)continue}throw new Lg(`Different value for "${s}" specified in modelParams (${n[s]}) and cachedContent (${e[s]})`)}let i=Object.assign(Object.assign({},n),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new f5(this.apiKey,i,r)}}});function gde(t,e){let n=oRt(t);return{tools:n,toolConfig:sRt(n,e)}}function oRt(t){let e=[],n=[];return t.forEach(r=>{if(cp(r)){let[o]=S4e([r]);o.functionDeclarations&&e.push(...o.functionDeclarations)}else if(Rg(r)){let{functionDeclarations:o}=iRt(r);if(o)e.push(...o);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(r)}),n.find(r=>"functionDeclarations"in r)?n.map(r=>{if(e?.length>0&&"functionDeclarations"in r){let o={functionDeclarations:[...r.functionDeclarations||[],...e]};return e=[],o}return r}):[...n,...e.length>0?[{functionDeclarations:e}]:[]]}function iRt(t){return{functionDeclarations:[{name:t.function.name,description:t.function.description,parameters:Aw(t.function.parameters)}]}}function sRt(t,e){if(!t.length||!e)return;let{toolChoice:n,allowedFunctionNames:r}=e,o={any:gI.ANY,auto:gI.AUTO,none:gI.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:o[n]??"MODE_UNSPECIFIED",allowedFunctionNames:r}};if(typeof n=="string"||r)return{functionCallingConfig:{mode:gI.ANY,allowedFunctionNames:[...r??[],...n&&typeof n=="string"?[n]:[]]}}}var Q4e=C(()=>{E3();ade();p5();pI();qd()});var eVe,tVe=C(()=>{eVe={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-flash-preview":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-pro-preview":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}}});function m5(t){let e=t.constructor;return new e({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var nVe,rVe=C(()=>{nVe=t=>t()});function Xb(t,e){if(t.function===void 0)return;let n;if(e?.partial)try{n=Vk(t.function.arguments??"{}")}catch{return}else try{n=JSON.parse(t.function.arguments)}catch(o){throw new lc([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${o.message}`].join(`
`))}let r={name:t.function.name,args:n,type:"tool_call"};return e?.returnId&&(r.id=t.id),r}function cU(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function Bw(t,e){return{name:t.function?.name,args:t.function?.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var oVe,up,yde=C(()=>{Wk();Wu();vg();hI();Yb();oU();oVe=class extends lM{constructor(e){super(e);I(this,"returnId",!1);I(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);I(this,"lc_serializable",!0);this.returnId=e?.returnId??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,n=!0){let r=e[0].message,o;if(rp(r)&&r.tool_calls?.length?o=r.tool_calls.map(s=>{let{id:a,...l}=s;return this.returnId?{id:a,...l}:l}):r.additional_kwargs.tool_calls!==void 0&&(o=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(s=>Xb(s,{returnId:this.returnId,partial:n}))),!o)return[];let i=[];for(let s of o)if(s!==void 0){let a={type:s.name,args:s.args,id:s.id};i.push(a)}return i}},up=class extends oVe{constructor(e){super(e);I(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);I(this,"lc_serializable",!0);I(this,"returnId",!1);I(this,"keyName");I(this,"returnSingle",!1);I(this,"zodSchema");I(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,"zodSchema"in e&&(this.zodSchema=e.zodSchema),"serializableSchema"in e&&(this.serializableSchema=e.serializableSchema)}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){if(this.serializableSchema!==void 0){let r=await this.serializableSchema["~standard"].validate(e);if(r.issues)throw new lc(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.issues)}`,JSON.stringify(e,null,2));return r.value}if(this.zodSchema===void 0)return e;let n=await kT(this.zodSchema,e);if(n.success)return n.data;throw new lc(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(n.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){let n=(await super.parsePartialResult(e)).filter(o=>o.type===this.keyName),r=n;if(n.length)return this.returnId||(r=n.map(o=>o.args)),this.returnSingle?r[0]:r}async parseResult(e){let n=(await super.parsePartialResult(e,!1)).filter(o=>o.type===this.keyName),r=n;if(n.length)return this.returnId||(r=n.map(o=>o.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(o=>this._validateResult(o)))}}});function iVe(t){return jr(t)?Vm.fromZodSchema(t):Ob(t)?cde.fromSerializableSchema(t):new Gd}function sVe(t,e,n){let r=n??up;return jr(t)?new r({returnSingle:!0,keyName:e,zodSchema:t}):Ob(t)?new r({returnSingle:!0,keyName:e,serializableSchema:t}):new r({returnSingle:!0,keyName:e})}function h5(t,e,n,r){if(!n){let l=t.pipe(e);return r?l.withConfig({runName:r}):l}let o=xl.assign({parsed:(l,c)=>e.invoke(l.raw,c)}),i=xl.assign({parsed:()=>null}),s=o.withFallbacks({fallbacks:[i]}),a=Kc.from([{raw:t},s]);return r?a.withConfig({runName:r}):a}var wde=C(()=>{$n();vg();y2();Ra();l5();jm();oU();ude();dde();Uw();yde();Bd()});function lRt(t,e){switch(e.type){case"text-delta":return t.type==="text"?{...t,text:(t.text??"")+e.text}:t;case"reasoning-delta":return t.type==="thinking"?{...t,thinking:(t.thinking??"")+e.reasoning}:t.type==="reasoning"?{...t,reasoning:(t.reasoning??"")+e.reasoning}:t;case"data-delta":return{...t,data:(t.data??"")+e.data};case"block-delta":return{...t,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function uU(t){if(t.event!=="content-block-delta")return;if("delta"in t&&t.delta)return t.delta;let e=t.content;if(e==null||typeof e!="object")return;let n=e;if(n.type==="text"&&typeof n.text=="string")return{type:"text-delta",text:n.text};if(n.type==="reasoning"&&typeof n.reasoning=="string")return{type:"reasoning-delta",reasoning:n.reasoning};if(n.type==="thinking"&&typeof n.thinking=="string")return{type:"reasoning-delta",reasoning:n.thinking};if(typeof n.data=="string")return{type:"data-delta",data:n.data,encoding:"base64"};if(typeof n.type=="string")return{type:"block-delta",fields:{...n,type:n.type}}}function aVe(t){if(t==null||typeof t!="object")return;let e=t;if(e.type==="reasoning"&&typeof e.reasoning=="string")return e.reasoning;if(e.type==="thinking"&&typeof e.thinking=="string")return e.thinking}function g5(t){if(t==null||typeof t!="object")return!1;let e=t.type;return e==="reasoning"||e==="thinking"}function cM(t){if(t)return{...t,input_tokens:t.input_tokens??0,output_tokens:t.output_tokens??0,total_tokens:t.total_tokens??0}}function cRt(t){if(t!=null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string"||t.length===0)return{};try{let e=JSON.parse(t);return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function uRt(t){let e=t;if(t.type==="tool_call"||t.type!=="tool_call_chunk"&&t.type!=="tool_use"&&t.type!=="input_json_delta")return t;let n=typeof e.name=="string"?e.name:void 0;if(n==null)return t;let r=e.args??e.input;return{...e,type:"tool_call",name:n,args:cRt(r)}}var aRt,dRt,fRt,pRt,mRt,vde,lVe=C(()=>{$n();Wu();aRt=class{constructor(){I(this,"events",[]);I(this,"finished",!1);I(this,"waiters",[]);I(this,"error",null)}push(t){this.events.push(t);let e=this.waiters.splice(0);for(let n of e)n()}finish(){this.finished=!0;let t=this.waiters.splice(0);for(let e of t)e()}setError(t){this.error=t,this.finished=!0;let e=this.waiters.splice(0);for(let n of e)n()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let t=0;for(;;){for(;t<this.events.length;)yield this.events[t],t++;if(this.finished){if(this.error)throw this.error;return}await new Promise(e=>{if(t<this.events.length||this.finished){e();return}this.waiters.push(e)})}}};dRt=class{constructor(t){I(this,"_buffer");this._buffer=t}get full(){let t=this._buffer;return{async*[Symbol.asyncIterator](){let e="";for await(let n of t.iterate()){let r=uU(n);r?.type==="text-delta"&&(e+=r.text,yield e)}}}}[Symbol.asyncIterator](){let t=this._buffer;async function*e(){for await(let n of t.iterate()){let r=uU(n);r?.type==="text-delta"&&(yield r.text)}}return e()}then(t,e){return(async()=>{let n="";for await(let r of this)n+=r;return n})().then(t,e)}},fRt=class{constructor(t){I(this,"_buffer");this._buffer=t}get full(){let t=this._buffer;return{async*[Symbol.asyncIterator](){let e=[];for await(let n of t.iterate())n.event==="content-block-finish"&&n.content.type==="tool_call"&&(e.push(n.content),yield[...e])}}}[Symbol.asyncIterator](){let t=this._buffer;async function*e(){for await(let n of t.iterate())n.event==="content-block-finish"&&n.content.type==="tool_call"&&(yield n.content)}return e()}then(t,e){return(async()=>{let n=[];for await(let r of this)n.push(r);return n})().then(t,e)}},pRt=class{constructor(t){I(this,"_buffer");this._buffer=t}get full(){let t=this._buffer;return{async*[Symbol.asyncIterator](){let e="",n=!1;for await(let r of t.iterate())if(r.event==="content-block-start"){if(!g5(r.content)){if(n)return;continue}n=!0;let o=aVe(r.content);if(o==null||o.length===0)continue;e+=o,yield e}else if(r.event==="content-block-delta"){let o=uU(r);if(o?.type!=="reasoning-delta")continue;n=!0;let i=o.reasoning;if(i==null||i.length===0)continue;e+=i,yield e}else{if(r.event==="content-block-finish"&&g5(r.content))return;if(r.event==="message-finish")return}}}}[Symbol.asyncIterator](){let t=this._buffer;async function*e(){let n=!1;for await(let r of t.iterate())if(r.event==="content-block-start"){if(!g5(r.content)){if(n)return;continue}n=!0;let o=aVe(r.content);o!=null&&o.length>0&&(yield o)}else if(r.event==="content-block-delta"){let o=uU(r);if(o?.type!=="reasoning-delta")continue;n=!0;let i=o.reasoning;i!=null&&i.length>0&&(yield i)}else{if(r.event==="content-block-finish"&&g5(r.content))return;if(r.event==="message-finish")return}}return e()}then(t,e){return(async()=>{let n="";for await(let r of this)n+=r;return n})().then(t,e)}},mRt=class{constructor(t){I(this,"_buffer");this._buffer=t}[Symbol.asyncIterator](){let t=this._buffer;async function*e(){for await(let n of t.iterate())if(n.event==="usage"){let r=cM(n.usage);r&&(yield r)}else if(n.event==="message-start"&&n.usage){let r=cM(n.usage);r&&(yield r)}else if(n.event==="message-finish"&&n.usage){let r=cM(n.usage);r&&(yield r)}}return e()}then(t,e){return(async()=>{let n;for await(let r of this)n=r;return n})().then(t,e)}},vde=class{constructor(t){I(this,"_buffer");this._buffer=new aRt,this._consume(t)}async _consume(t){try{for await(let e of t)this._buffer.push(e);this._buffer.finish()}catch(e){this._buffer.setError(e instanceof Error?e:new Error(String(e)))}}[Symbol.asyncIterator](){return this._buffer.iterate()}get text(){return new dRt(this._buffer)}get toolCalls(){return new fRt(this._buffer)}get reasoning(){return new pRt(this._buffer)}get usage(){return new mRt(this._buffer)}get output(){return this._assembleMessage()}then(t,e){return this._assembleMessage().then(t,e)}async _assembleMessage(){let t=[],e,n,r={},o;for await(let s of this._buffer.iterate())switch(s.event){case"message-start":e=s.id??e,s.usage&&(n=cM(s.usage));break;case"content-block-start":t[s.index]=s.content;break;case"content-block-delta":{let a=t[s.index],l=uU(s);a&&l&&(t[s.index]=lRt(a,l));break}case"content-block-finish":t[s.index]=s.content;break;case"usage":n=cM(s.usage);break;case"message-finish":o=s.reason,s.usage&&(n=cM(s.usage)),s.responseMetadata&&(r={...r,...s.responseMetadata});break;default:break}let i=t.filter(s=>s!=null).map(uRt);return new kn({id:e,content:i,usage_metadata:n,response_metadata:{...r,...o?{finish_reason:o}:{},output_version:"v1"}})}}});function cVe(t){let e=0;for(let n of t.keys())n>=e&&(e=n+1);return e}function uVe(t){let e=t.additional_kwargs;return e!=null&&typeof e=="object"?e:{}}function yRt(t){let e=uVe(t).tool_outputs;if(!Array.isArray(e))return[];let n=[];for(let r of e){if(r==null||typeof r!="object")continue;let o=r;if(o.type!=="image_generation_call")continue;let i=typeof o.result=="string"?o.result:void 0,s=typeof o.url=="string"?o.url:void 0;if(i==null&&s==null)continue;let a=typeof o.output_format=="string"?o.output_format.toLowerCase():void 0,l=(a!=null?gRt[a]:void 0)??"image/png";n.push({type:"image",...typeof o.id=="string"?{id:o.id}:{},...s!=null?{url:s}:{},...i!=null?{data:i}:{},mimeType:l})}return n}function wRt(t){let e=uVe(t).audio;if(e==null||typeof e!="object")return;let n=e,r=typeof n.data=="string"?n.data:void 0,o=typeof n.url=="string"?n.url:void 0,i=typeof n.transcript=="string"?n.transcript:void 0;if(r==null&&o==null&&i==null)return;let s=typeof n.mime_type=="string"?n.mime_type:typeof n.mimeType=="string"?n.mimeType:void 0,a=typeof n.format=="string"?n.format.toLowerCase():void 0,l=s??(a!=null?hRt[a]:void 0)??(r!=null?"audio/wav":"audio/pcm");return{...typeof n.id=="string"?{id:n.id}:{},...r!=null?{data:r}:{},...o!=null?{url:o}:{},...i!=null?{transcript:i}:{},mimeType:l}}async function*dVe(t,e){let n=new Map,r=!1,o,i,s=new Set;for await(let a of t){e?.signal?.throwIfAborted();let l=a.message,c=!1;if(!r){r=!0;let f={event:"message-start",id:l.id??void 0};Yt.isInstance(l)&&l.usage_metadata&&(f.usage=l.usage_metadata,o={...l.usage_metadata},c=!0),yield f}let u=l.content;if(typeof u=="string"){if(u!==""){if(!n.has(0)){let m={type:"text",text:""};n.set(0,{type:"text",accumulated:m}),yield{event:"content-block-start",index:0,content:m}}let p=n.get(0);p.accumulated={...p.accumulated,text:(p.accumulated.text??"")+u},yield{event:"content-block-delta",index:0,delta:{type:"text-delta",text:u}}}}else if(Array.isArray(u))for(let f of u){let p=typeof f.index=="number"?f.index:n.size;if(!n.has(p))n.set(p,{type:f.type,accumulated:{...f}}),yield{event:"content-block-start",index:p,content:{...f}};else{let m=n.get(p),h=xRt(f);m.accumulated=vRt(m.accumulated,h),yield{event:"content-block-delta",index:p,delta:h}}}if(Yt.isInstance(l)&&l.tool_call_chunks&&l.tool_call_chunks.length>0)for(let f of l.tool_call_chunks){let p=typeof f.index=="number"?f.index:n.size;if(!n.has(p)){let h={type:"tool_call_chunk",id:f.id,name:f.name,args:"",index:p};n.set(p,{type:"tool_call_chunk",accumulated:h}),yield{event:"content-block-start",index:p,content:h}}let m=n.get(p).accumulated;f.id!=null&&(m.id=f.id),f.name!=null&&(m.name=f.name),m.args=(m.args??"")+(f.args??""),yield{event:"content-block-delta",index:p,delta:{type:"block-delta",fields:{type:"tool_call_chunk",..."id"in m&&m.id!=null?{id:m.id}:{},..."name"in m&&m.name!=null?{name:m.name}:{},args:m.args}}}}let d=wRt(l);if(d!=null){if(i==null){let p=cVe(n);i={index:p,id:d.id,mimeType:d.mimeType,transcript:""};let m={type:"audio",...d.id!=null?{id:d.id}:{},...d.url!=null?{url:d.url}:{},data:"",mimeType:d.mimeType};n.set(p,{type:"audio",accumulated:m}),yield{event:"content-block-start",index:p,content:m}}let f=n.get(i.index);if(f!=null){let p=f.accumulated;d.id!=null&&i.id==null&&(i.id=d.id,p.id=d.id),d.transcript!=null&&(i.transcript+=d.transcript,p.transcript=i.transcript,yield{event:"content-block-delta",index:i.index,delta:{type:"block-delta",fields:{type:"audio",transcript:i.transcript}}}),d.data!=null&&d.data.length>0&&(p.data=(p.data??"")+d.data,yield{event:"content-block-delta",index:i.index,delta:{type:"data-delta",data:d.data,encoding:"base64"}})}}for(let f of yRt(l)){let p=f,m=p.id??p.url??(p.data!=null?`${p.data.length}:${p.data.slice(0,32)}`:void 0);if(m!=null&&s.has(m))continue;m!=null&&s.add(m);let h=cVe(n);n.set(h,{type:"image",accumulated:f}),yield{event:"content-block-start",index:h,content:f}}if(!c&&Yt.isInstance(l)&&l.usage_metadata){let f=l.usage_metadata;o?o={input_tokens:o.input_tokens+f.input_tokens,output_tokens:o.output_tokens+f.output_tokens,total_tokens:o.total_tokens+f.total_tokens}:o={...f},yield{event:"usage",usage:{...o}}}}for(let[a,l]of n)yield{event:"content-block-finish",index:a,content:bRt(l.accumulated)};yield{event:"message-finish",reason:"stop",...o?{usage:o}:{}}}function vRt(t,e){switch(e.type){case"text-delta":return t.type==="text"?{...t,text:(t.text??"")+e.text}:t;case"reasoning-delta":return t.type==="thinking"?{...t,thinking:(t.thinking??"")+e.reasoning}:t.type==="reasoning"?{...t,reasoning:(t.reasoning??"")+e.reasoning}:t;case"data-delta":return{...t,data:(t.data??"")+e.data};case"block-delta":return{...t,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function xRt(t){if(t.type==="text")return{type:"text-delta",text:t.text};if(t.type==="reasoning")return{type:"reasoning-delta",reasoning:t.reasoning};if(t.type==="thinking"&&typeof t.thinking=="string")return{type:"reasoning-delta",reasoning:t.thinking};if(typeof t.data=="string")return{type:"data-delta",data:t.data,encoding:"base64"};if(typeof t.type=="string")return{type:"block-delta",fields:{...t}};throw new Error(`Unsupported content block delta: ${JSON.stringify(t)}`)}function bRt(t){if(t.type==="tool_call_chunk"){let e=t,n;try{n=JSON.parse(e.args??"{}")}catch{return{type:"invalid_tool_call",id:e.id,name:e.name,args:e.args,error:"Failed to parse tool call arguments as JSON"}}return{type:"tool_call",id:e.id,name:e.name,args:n}}return t}var hRt,gRt,fVe=C(()=>{$n();Wu();hRt={wav:"audio/wav",mp3:"audio/mpeg",flac:"audio/flac",opus:"audio/opus",aac:"audio/aac",pcm16:"audio/pcm"},gRt={png:"image/png",jpeg:"image/jpeg",jpg:"image/jpeg",webp:"image/webp",gif:"image/gif"}});function xde(t){let e=[];for(let n of t){let r=n;if(Array.isArray(n.content))for(let o=0;o<n.content.length;o++){let i=n.content[o];(x2(i)||b2(i))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,o),mle(i),...n.content.slice(o+1)]}))}e.push(r)}return e}var dp,vI=C(()=>{$n();JT();C2();nc();Wu();Dm();Jo();k2();Hb();Og();ac();vg();y2();Bu();Ra();Kr();qd();rVe();wde();lVe();fVe();dp=class Dg extends mI{constructor(n){super(n);I(this,"lc_namespace",["langchain","chat_models",this._llmType()]);I(this,"disableStreaming",!1);I(this,"outputVersion");this.outputVersion=nVe(()=>{let r=n.outputVersion??In("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}get callKeys(){return[...super.callKeys,"outputVersion"]}_separateRunnableConfigFromCallOptionsCompat(n){let[r,o]=super._separateRunnableConfigFromCallOptions(n);return o.signal=r.signal,[r,o]}async invoke(n,r){let o=Dg._convertInputToPromptValue(n);return(await this.generatePrompt([o],r,r?.callbacks)).generations[0][0].message}async*_streamResponseChunks(n,r,o){throw new Error("Not implemented.")}async*_streamChatModelEvents(n,r,o){yield*dVe(this._streamResponseChunks(n,r,o),{signal:r.signal})}streamV2(n,r){let o=Dg._convertInputToPromptValue(n).toChatMessages(),[,i]=this._separateRunnableConfigFromCallOptionsCompat(r);return new vde(this._streamChatModelEvents(o,i))}async*_streamIterator(n,r){if(this._streamResponseChunks===Dg.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(n,r);else{let o=Dg._convertInputToPromptValue(n).toChatMessages(),[i,s]=this._separateRunnableConfigFromCallOptionsCompat(r),a={...i.metadata,...this.getLsParamsWithDefaults(s)},l=this.invocationParams(s),c=await Ws.configure(i.callbacks,this.callbacks,i.tags,this.tags,a,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(l)}),u={options:s,invocation_params:l,batch_size:1},d=s.outputVersion??this.outputVersion,f=await c?.handleChatModelStart(this.toJSON(),[xde(o)],i.runId,void 0,u,void 0,void 0,i.runName),p,m;try{for await(let h of this._streamResponseChunks(o,s,f?.[0])){if(s.signal?.throwIfAborted(),h.message.id==null){let g=f?.at(0)?.runId;g!=null&&h.message._updateId(`run-${g}`)}h.message.response_metadata={...h.generationInfo,...h.message.response_metadata},d==="v1"?yield m5(h.message):yield h.message,p?p=p.concat(h):p=h,z3(h.message)&&h.message.usage_metadata!==void 0&&(m={tokenUsage:{promptTokens:h.message.usage_metadata.input_tokens,completionTokens:h.message.usage_metadata.output_tokens,totalTokens:h.message.usage_metadata.total_tokens}})}s.signal?.throwIfAborted()}catch(h){throw await Promise.all((f??[]).map(g=>g?.handleLLMError(h))),h}await Promise.all((f??[]).map(h=>h?.handleLLMEnd({generations:[[p]],llmOutput:m})))}}getLsParams(n){let r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:n.stop,ls_provider:r}}getLsParamsWithDefaults(n){return{...this.getLsParams(n),ls_integration:"langchain_chat_model"}}async _generateUncached(n,r,o,i){let s=n.map(m=>m.map(Lm)),a;if(i!==void 0&&i.length===s.length)a=i;else{let m={...o.metadata,...this.getLsParamsWithDefaults(r)},h=this.invocationParams(r),g=await Ws.configure(o.callbacks,this.callbacks,o.tags,this.tags,m,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(h)}),y={options:r,invocation_params:h,batch_size:1};a=await g?.handleChatModelStart(this.toJSON(),s.map(xde),o.runId,void 0,y,void 0,void 0,o.runName)}let l=r.outputVersion??this.outputVersion,c=[],u=[],d=!!a?.[0].handlers.find(d2e),f=!!a?.[0].handlers.find(Kle);if(d&&!this.disableStreaming&&s.length===1&&(this._streamChatModelEvents!==Dg.prototype._streamChatModelEvents||this._streamResponseChunks!==Dg.prototype._streamResponseChunks))try{let m=!1,h=a?.[0],g=this._streamChatModelEvents(s[0],r),y=await new vde({async*[Symbol.asyncIterator](){for await(let x of g){r.signal?.throwIfAborted(),m=!0;let b=x.event==="message-start"&&x.id==null&&h?.runId!=null?{...x,id:`run-${h.runId}`}:x;await h?.handleChatModelStreamEvent(b),yield b}}});if(r.signal?.throwIfAborted(),!m)throw new Error("Received empty response from chat model call.");if(y.id==null){let x=a?.at(0)?.runId;x!=null&&y._updateId(`run-${x}`)}let w={text:y.text,message:y};c.push([w]);let v=y.usage_metadata!==void 0?{tokenUsage:{promptTokens:y.usage_metadata.input_tokens,completionTokens:y.usage_metadata.output_tokens,totalTokens:y.usage_metadata.total_tokens}}:void 0;await a?.[0].handleLLMEnd({generations:c,llmOutput:v})}catch(m){throw await a?.[0].handleLLMError(m),m}else if(f&&!this.disableStreaming&&s.length===1&&this._streamResponseChunks!==Dg.prototype._streamResponseChunks)try{let m=await this._streamResponseChunks(s[0],r,a?.[0]),h,g;for await(let y of m){if(r.signal?.aborted){let w=h?.message;throw new Ole("Model invocation was aborted.",w)}if(y.message.id==null){let w=a?.at(0)?.runId;w!=null&&y.message._updateId(`run-${w}`)}h===void 0?h=y:h=Um(h,y),z3(y.message)&&y.message.usage_metadata!==void 0&&(g={tokenUsage:{promptTokens:y.message.usage_metadata.input_tokens,completionTokens:y.message.usage_metadata.output_tokens,totalTokens:y.message.usage_metadata.total_tokens}})}if(r.signal?.aborted){let y=h?.message;throw new Ole("Model invocation was aborted.",y)}if(h===void 0)throw new Error("Received empty response from chat model call.");c.push([h]),await a?.[0].handleLLMEnd({generations:c,llmOutput:g})}catch(m){throw await a?.[0].handleLLMError(m),m}else{let m=await Promise.allSettled(s.map(async(h,g)=>{let y=await this._generate(h,{...r,promptIndex:g},a?.[g]);if(l==="v1")for(let w of y.generations)w.message=m5(w.message);return y}));await Promise.all(m.map(async(h,g)=>{if(h.status==="fulfilled"){let y=h.value;for(let w of y.generations){if(w.message.id==null){let v=a?.at(0)?.runId;v!=null&&w.message._updateId(`run-${v}`)}w.message.response_metadata={...w.generationInfo,...w.message.response_metadata}}return y.generations.length===1&&(y.generations[0].message.response_metadata={...y.llmOutput,...y.generations[0].message.response_metadata}),c[g]=y.generations,u[g]=y.llmOutput,a?.[g]?.handleLLMEnd({generations:[y.generations],llmOutput:y.llmOutput})}else return await a?.[g]?.handleLLMError(h.reason),Promise.reject(h.reason)}))}let p={generations:c,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(p,iM,{value:a?{runIds:a?.map(m=>m.runId)}:void 0,configurable:!0}),p}async _generateCached({messages:n,cache:r,llmStringKey:o,parsedOptions:i,handledOptions:s}){let a=n.map(w=>w.map(Lm)),l={...s.metadata,...this.getLsParamsWithDefaults(i)},c=this.invocationParams(i),u=await Ws.configure(s.callbacks,this.callbacks,s.tags,this.tags,l,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(c)}),d={options:i,invocation_params:c,batch_size:1},f=await u?.handleChatModelStart(this.toJSON(),a.map(xde),s.runId,void 0,d,void 0,void 0,s.runName),p=[],m=(await Promise.allSettled(a.map(async(w,v)=>{let x=Dg._convertInputToPromptValue(w).toString(),b=await r.lookup(x,o);return b==null&&p.push(v),b}))).map((w,v)=>({result:w,runManager:f?.[v]})).filter(({result:w})=>w.status==="fulfilled"&&w.value!=null||w.status==="rejected"),h=i.outputVersion??this.outputVersion,g=[];await Promise.all(m.map(async({result:w,runManager:v},x)=>{if(w.status==="fulfilled"){let b=w.value;return g[x]=b.map(_=>("message"in _&&np(_.message)&&rp(_.message)&&(_.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},h==="v1"&&(_.message=m5(_.message))),_.generationInfo={..._.generationInfo,tokenUsage:{}},_)),b.length&&await v?.handleLLMNewToken(b[0].text),v?.handleLLMEnd({generations:[b]},void 0,void 0,void 0,{cached:!0})}else return await v?.handleLLMError(w.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(w.reason)}));let y={generations:g,missingPromptIndices:p,startedRunManagers:f};return Object.defineProperty(y,iM,{value:f?{runIds:f?.map(w=>w.runId)}:void 0,configurable:!0}),y}async generate(n,r,o){let i;Array.isArray(r)?i={stop:r}:i=r;let s=n.map(h=>h.map(Lm)),[a,l]=this._separateRunnableConfigFromCallOptionsCompat(i);if(a.callbacks=a.callbacks??o,!this.cache)return this._generateUncached(s,l,a);let{cache:c}=this,u=this._getSerializedCacheKeyParametersForCall(l),{generations:d,missingPromptIndices:f,startedRunManagers:p}=await this._generateCached({messages:s,cache:c,llmStringKey:u,parsedOptions:l,handledOptions:a}),m={};if(f.length>0){let h=await this._generateUncached(f.map(g=>s[g]),l,a,p!==void 0?f.map(g=>p?.[g]):void 0);await Promise.all(h.generations.map(async(g,y)=>{let w=f[y];d[w]=g;let v=Dg._convertInputToPromptValue(s[w]).toString();return c.update(v,u,g)})),m=h.llmOutput??{}}return{generations:d,llmOutput:m}}invocationParams(n){return{}}_modelType(){return"base_chat_model"}async generatePrompt(n,r,o){let i=n.map(s=>s.toChatMessages());return this.generate(i,r,o)}withStructuredOutput(n,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r?.strict)throw new Error('"strict" mode is not supported for this model by default.');let o=n,i=r?.name,s=NT(o)??"A function available to call.",a=r?.method,l=r?.includeRaw;if(a==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let c=i??"extract";!jr(o)&&!Ob(o)&&"name"in o&&(c=o.name);let u=jr(o)||Ob(o)?Hr(o):o,d=[{type:"function",function:{name:c,description:s,parameters:u}}];return h5(this.bindTools(d),$w.from(f=>{if(!Yt.isInstance(f))throw new Error("Input is not an AIMessageChunk.");if(!f.tool_calls||f.tool_calls.length===0)throw new Error("No tool calls found in the response.");let p=f.tool_calls.find(m=>m.name===c);if(!p)throw new Error(`No tool call found with name ${c}.`);return p.args}),l,l?"StructuredOutputRunnable":"StructuredOutput")}}});var bde,pVe=C(()=>{E3();ade();O4e();Q4e();tVe();p5();Jo();vI();jm();Bd();Uw();bde=class extends dp{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e;super(r);I(this,"lc_serializable",!0);I(this,"lc_namespace",["langchain","chat_models","google_genai"]);I(this,"model");I(this,"temperature");I(this,"maxOutputTokens");I(this,"topP");I(this,"topK");I(this,"stopSequences",[]);I(this,"safetySettings");I(this,"apiKey");I(this,"streaming",!1);I(this,"json");I(this,"streamUsage",!0);I(this,"convertSystemMessageToHumanContent");I(this,"thinkingConfig");I(this,"client");if(this._addVersion("@langchain/google-genai","2.1.23"),this.model=r.model.replace(/^models\//,""),this.maxOutputTokens=r.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=r.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=r.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=r.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=r.stopSequences??this.stopSequences,this.apiKey=r.apiKey??In("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=r.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(o=>o.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=r.streaming??this.streaming,this.json=r.json,this.thinkingConfig=r.thinkingConfig??this.thinkingConfig,this.client=new wI(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:r.apiVersion,baseUrl:r.baseUrl,customHeaders:r.customHeaders}),this.streamUsage=r.streamUsage??this.streamUsage}static lc_name(){return"ChatGoogleGenerativeAI"}get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}get lc_aliases(){return{apiKey:"google_api_key"}}get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")||this.model.startsWith("gemini-3")}useCachedContent(e,n,r){this.apiKey&&(this.client=new wI(this.apiKey).getGenerativeModelFromCachedContent(e,n,r))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(e){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:e.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(e,n){return this.withConfig({tools:gde(e)?.tools,...n})}invocationParams(e){let n=e?.tools?.length?gde(e.tools,{toolChoice:e.tool_choice,allowedFunctionNames:e.allowedFunctionNames}):void 0;return e?.responseSchema?(this.client.generationConfig.responseSchema=e.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...n?.tools?{tools:n.tools}:{},...n?.toolConfig?{toolConfig:n.toolConfig}:{}}}async _generate(e,n,r){n.signal?.throwIfAborted();let o=ide(e,this._isMultimodalModel,this.useSystemInstruction,this.model),i=o;if(o[0].role==="system"){let[u]=o;this.client.systemInstruction=u,i=o.slice(1)}let s=this.invocationParams(n);if(this.streaming){let u={},d=this._streamResponseChunks(e,n,r),f=[];for await(let p of d){let m=p.generationInfo?.completion??0;f[m]===void 0?f[m]=p:f[m]=f[m].concat(p)}return{generations:f.filter(p=>p!==void 0),llmOutput:{estimatedTokenUsage:u}}}let a=await this.completionWithRetry({...s,contents:i}),l;"usageMetadata"in a.response&&(l=sde(a.response.usageMetadata,this.model));let c=C4e(a.response,{usageMetadata:l});return c.generations?.length>0&&await r?.handleLLMNewToken(c.generations[0]?.text??""),c}async*_streamResponseChunks(e,n,r){let o=ide(e,this._isMultimodalModel,this.useSystemInstruction,this.model),i=o;if(o[0].role==="system"){let[p]=o;this.client.systemInstruction=p,i=o.slice(1)}let s={...this.invocationParams(n),contents:i},a=await this.caller.callWithOptions({signal:n?.signal},async()=>{let{stream:p}=await this.client.generateContentStream(s,{signal:n?.signal});return p}),l,c=0,u=0,d=0,f=0;for await(let p of a){if(n.signal?.aborted)return;if("usageMetadata"in p&&p.usageMetadata!==void 0&&this.streamUsage!==!1&&n.streamUsage!==!1){l=sde(p.usageMetadata,this.model);let h=p.usageMetadata.promptTokenCount??0;l.input_tokens=Math.max(0,h-c),c=h;let g=p.usageMetadata.candidatesTokenCount??0;l.output_tokens=Math.max(0,g-u),u=g;let y=p.usageMetadata.totalTokenCount??0;l.total_tokens=Math.max(0,y-d),d=y}let m=_4e(p,{usageMetadata:l,index:f});f+=1,m&&(yield m,await r?.handleLLMNewToken(m.text??""))}}async completionWithRetry(e,n){return this.caller.callWithOptions({signal:n?.signal},async()=>{try{return await this.client.generateContent(e,{signal:n?.signal})}catch(r){throw r.message?.includes("400 Bad Request")&&(r.status=400),r}})}get profile(){return eVe[this.model]??{}}withStructuredOutput(e,n){let r=e,o=n?.name,i=n?.method,s=n?.includeRaw;if(i==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,l;if(i==="functionCalling"){let f=o??"extract",p;if(jr(r)){let m=v2(r);p=[{functionDeclarations:[{name:f,description:m.description??"A function available to call.",parameters:m}]}],l=new fde({returnSingle:!0,keyName:f,zodSchema:r})}else{let m;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(m=r,m.parameters=Aw(r.parameters),f=r.name):m={name:f,description:r.description??"",parameters:Aw(r)},p=[{functionDeclarations:[m]}],l=new fde({returnSingle:!0,keyName:f})}a=this.bindTools(p).withConfig({allowedFunctionNames:[f]})}else{let f=v2(r);a=this.withConfig({responseSchema:f}),l=new Gd}if(!s)return a.pipe(l).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});let c=xl.assign({parsed:(f,p)=>l.invoke(f.raw,p)}),u=xl.assign({parsed:()=>null}),d=c.withFallbacks({fallbacks:[u]});return Kc.from([{raw:a},d]).withConfig({runName:"StructuredOutputRunnable"})}}});var Qb,dU=C(()=>{$n();X2();Qb=class{constructor(t){I(this,"caller");this.caller=new qb(t??{})}}});var xI,fU=C(()=>{$n();xI=(t,e)=>t.reduce((n,r,o)=>{let i=Math.floor(o/e);return n[i]=(n[i]||[]).concat([r]),n},[])});var Cde,mVe=C(()=>{p5();Jo();dU();fU();Cde=class extends Qb{constructor(e){super(e??{});I(this,"apiKey");I(this,"modelName","embedding-001");I(this,"model","embedding-001");I(this,"taskType");I(this,"title");I(this,"stripNewLines",!0);I(this,"maxBatchSize",100);I(this,"client");if(this.modelName=e?.model?.replace(/^models\//,"")??e?.modelName?.replace(/^models\//,"")??this.modelName,this.model=this.modelName,this.taskType=e?.taskType??this.taskType,this.title=e?.title??this.title,this.title&&this.taskType!=="RETRIEVAL_DOCUMENT")throw new Error("title can only be sepcified with TaskType.RETRIEVAL_DOCUMENT");if(this.apiKey=e?.apiKey??In("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environmentb variable GOOGLE_API_KEY or in the `apiKey` field of the GoogleGenerativeAIEmbeddings constructor");this.client=new wI(this.apiKey).getGenerativeModel({model:this.model},{baseUrl:e?.baseUrl})}_convertToContent(e){return{content:{role:"user",parts:[{text:this.stripNewLines?e.replace(/\n/g," "):e}]},taskType:this.taskType,title:this.title}}async _embedQueryContent(e){let n=this._convertToContent(e);return(await this.client.embedContent(n)).embedding.values??[]}async _embedDocumentsContent(e){let n=xI(e,this.maxBatchSize),r=n.map(o=>({requests:o.map(i=>this._convertToContent(i))}));return(await Promise.allSettled(r.map(o=>this.client.batchEmbedContents(o)))).flatMap((o,i)=>o.status==="fulfilled"?o.value.embeddings.map(s=>s.values||[]):Array(n[i].length).fill([]))}embedQuery(e){return this.caller.call(this._embedQueryContent.bind(this),e)}embedDocuments(e){return this.caller.call(this._embedDocumentsContent.bind(this),e)}}});var _de=C(()=>{pVe();mVe()});function hVe(t,e=0){return(bl[t[e+0]]+bl[t[e+1]]+bl[t[e+2]]+bl[t[e+3]]+"-"+bl[t[e+4]]+bl[t[e+5]]+"-"+bl[t[e+6]]+bl[t[e+7]]+"-"+bl[t[e+8]]+bl[t[e+9]]+"-"+bl[t[e+10]]+bl[t[e+11]]+bl[t[e+12]]+bl[t[e+13]]+bl[t[e+14]]+bl[t[e+15]]).toLowerCase()}var bl,y5,gVe=C(()=>{bl=[];for(y5=0;y5<256;++y5)bl.push((y5+256).toString(16).slice(1))});function Sde(){if(!w5&&(w5=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!w5))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return w5(CRt)}var w5,CRt,yVe=C(()=>{CRt=new Uint8Array(16)});var _Rt,Tde,wVe=C(()=>{_Rt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Tde={randomUUID:_Rt}});function SRt(t,e,n){if(Tde.randomUUID&&!e&&!t)return Tde.randomUUID();t=t||{};var r=t.random||(t.rng||Sde)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){n=n||0;for(var o=0;o<16;++o)e[n+o]=r[o];return e}return hVe(r)}var Ide,vVe=C(()=>{wVe();yVe();gVe();Ide=SRt});var xVe=C(()=>{vVe()});function CVe(t,e){return new Yt({content:t.content??"",additional_kwargs:t.thinking&&t.thinking!==""?{reasoning_content:t.thinking}:{},tool_call_chunks:t.tool_calls?.map(n=>({name:n.function.name,args:JSON.stringify(n.function.arguments),type:"tool_call_chunk",index:0,id:Ide()})),response_metadata:{...e?.responseMetadata,model_provider:"ollama"},usage_metadata:e?.usageMetadata})}function bVe(t){let e=t.match(/^data:.*?;base64,(.*)$/);return e?e[1]:""}function TRt(t){if(typeof t.content=="string")return[{role:"assistant",content:t.content}];let n=t.content.filter(o=>o.type==="text"&&typeof o.text=="string").map(o=>({role:"assistant",content:o.text})),r;if(t.content.find(o=>o.type==="tool_use")&&t.tool_calls?.length){let o=t.tool_calls?.map(i=>({id:i.id,type:"function",function:{name:i.name,arguments:i.args}}));o&&(r={role:"assistant",tool_calls:o,content:""})}else if(t.content.find(o=>o.type==="tool_use")&&!t.tool_calls?.length)throw new Error("'tool_use' content type is not supported without tool calls.");return[...n,...r?[r]:[]]}function IRt(t){return typeof t.content=="string"?[{role:"user",content:t.content}]:t.content.map(e=>{if(e.type==="text")return{role:"user",content:e.text};if(e.type==="image_url"){if(typeof e.image_url=="string")return{role:"user",content:"",images:[bVe(e.image_url)]};if(e.image_url.url&&typeof e.image_url.url=="string")return{role:"user",content:"",images:[bVe(e.image_url.url)]}}throw new Error(`Unsupported content type: ${e.type}`)})}function PRt(t){if(typeof t.content=="string")return[{role:"system",content:t.content}];if(t.content.every(e=>e.type==="text"&&typeof e.text=="string"))return t.content.map(e=>({role:"system",content:e.text}));throw new Error(`Unsupported content type(s): ${t.content.map(e=>e.type).join(", ")}`)}function ERt(t){if(typeof t.content!="string")throw new Error("Non string tool message content is not supported");return[{role:"tool",content:t.content}]}function _Ve(t){return t.flatMap(e=>{if(["human","generic"].includes(e._getType()))return IRt(e);if(e._getType()==="ai")return TRt(e);if(e._getType()==="system")return PRt(e);if(e._getType()==="tool")return ERt(e);throw new Error(`Unsupported message type: ${e._getType()}`)})}var SVe=C(()=>{Kr();xVe()});function ARt(t){return t&&DataView.prototype.isPrototypeOf(t)}function uM(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||t==="")throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function Ede(t){return typeof t!="string"&&(t=String(t)),t}function Ade(t){var e={next:function(){var n=t.shift();return{done:n===void 0,value:n}}};return qc.iterable&&(e[Symbol.iterator]=function(){return e}),e}function Ks(t){this.map={},t instanceof Ks?t.forEach(function(e,n){this.append(n,e)},this):Array.isArray(t)?t.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function Pde(t){if(!t._noBody){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}}function EVe(t){return new Promise(function(e,n){t.onload=function(){e(t.result)},t.onerror=function(){n(t.error)}})}function kRt(t){var e=new FileReader,n=EVe(e);return e.readAsArrayBuffer(t),n}function MRt(t){var e=new FileReader,n=EVe(e),r=/charset=([A-Za-z0-9_-]+)/.exec(t.type),o=r?r[1]:"utf-8";return e.readAsText(t,o),n}function NRt(t){for(var e=new Uint8Array(t),n=new Array(e.length),r=0;r<e.length;r++)n[r]=String.fromCharCode(e[r]);return n.join("")}function IVe(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function AVe(){return this.bodyUsed=!1,this._initBody=function(t){this.bodyUsed=this.bodyUsed,this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:qc.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:qc.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:qc.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():qc.arrayBuffer&&qc.blob&&ARt(t)?(this._bodyArrayBuffer=IVe(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):qc.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||PVe(t))?this._bodyArrayBuffer=IVe(t):this._bodyText=t=Object.prototype.toString.call(t):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof t=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):qc.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},qc.blob&&(this.blob=function(){var t=Pde(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var t=Pde(this);return t||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(qc.blob)return this.blob().then(kRt);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var t=Pde(this);if(t)return t;if(this._bodyBlob)return MRt(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(NRt(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},qc.formData&&(this.formData=function(){return this.text().then(LRt)}),this.json=function(){return this.text().then(JSON.parse)},this}function RRt(t){var e=t.toUpperCase();return ORt.indexOf(e)>-1?e:t}function CI(t,e){if(!(this instanceof CI))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var n=e.body;if(t instanceof CI){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new Ks(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!n&&t._bodyInit!=null&&(n=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new Ks(e.headers)),this.method=RRt(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in Cl){var i=new AbortController;return i.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&n)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(n),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var r=/([?&])_=[^&]*/;if(r.test(this.url))this.url=this.url.replace(r,"$1_="+new Date().getTime());else{var o=/\?/;this.url+=(o.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}function LRt(t){var e=new FormData;return t.trim().split("&").forEach(function(n){if(n){var r=n.split("="),o=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");e.append(decodeURIComponent(o),decodeURIComponent(i))}}),e}function DRt(t){var e=new Ks,n=t.replace(/\r?\n[\t ]+/g," ");return n.split("\r").map(function(r){return r.indexOf(`
`)===0?r.substr(1,r.length):r}).forEach(function(r){var o=r.split(":"),i=o.shift().trim();if(i){var s=o.join(":").trim();try{e.append(i,s)}catch(a){console.warn("Response "+a.message)}}}),e}function $g(t,e){if(!(this instanceof $g))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new Ks(e.headers),this.url=e.url||"",this._initBody(t)}function kVe(t,e){return new Promise(function(n,r){var o=new CI(t,e);if(o.signal&&o.signal.aborted)return r(new bI("Aborted","AbortError"));var i=new XMLHttpRequest;function s(){i.abort()}i.onload=function(){var c={statusText:i.statusText,headers:DRt(i.getAllResponseHeaders()||"")};o.url.indexOf("file://")===0&&(i.status<200||i.status>599)?c.status=200:c.status=i.status,c.url="responseURL"in i?i.responseURL:c.headers.get("X-Request-URL");var u="response"in i?i.response:i.responseText;setTimeout(function(){n(new $g(u,c))},0)},i.onerror=function(){setTimeout(function(){r(new TypeError("Network request failed"))},0)},i.ontimeout=function(){setTimeout(function(){r(new TypeError("Network request timed out"))},0)},i.onabort=function(){setTimeout(function(){r(new bI("Aborted","AbortError"))},0)};function a(c){try{return c===""&&Cl.location.href?Cl.location.href:c}catch{return c}}if(i.open(o.method,a(o.url),!0),o.credentials==="include"?i.withCredentials=!0:o.credentials==="omit"&&(i.withCredentials=!1),"responseType"in i&&(qc.blob?i.responseType="blob":qc.arrayBuffer&&(i.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof Ks||Cl.Headers&&e.headers instanceof Cl.Headers)){var l=[];Object.getOwnPropertyNames(e.headers).forEach(function(c){l.push(uM(c)),i.setRequestHeader(c,Ede(e.headers[c]))}),o.headers.forEach(function(c,u){l.indexOf(u)===-1&&i.setRequestHeader(u,c)})}else o.headers.forEach(function(c,u){i.setRequestHeader(u,c)});o.signal&&(o.signal.addEventListener("abort",s),i.onreadystatechange=function(){i.readyState===4&&o.signal.removeEventListener("abort",s)}),i.send(typeof o._bodyInit>"u"?null:o._bodyInit)})}var Cl,qc,TVe,PVe,ORt,$Rt,bI,MVe=C(()=>{Cl=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof window<"u"&&window||{},qc={searchParams:"URLSearchParams"in Cl,iterable:"Symbol"in Cl&&"iterator"in Symbol,blob:"FileReader"in Cl&&"Blob"in Cl&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in Cl,arrayBuffer:"ArrayBuffer"in Cl};qc.arrayBuffer&&(TVe=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],PVe=ArrayBuffer.isView||function(t){return t&&TVe.indexOf(Object.prototype.toString.call(t))>-1});Ks.prototype.append=function(t,e){t=uM(t),e=Ede(e);var n=this.map[t];this.map[t]=n?n+", "+e:e};Ks.prototype.delete=function(t){delete this.map[uM(t)]};Ks.prototype.get=function(t){return t=uM(t),this.has(t)?this.map[t]:null};Ks.prototype.has=function(t){return this.map.hasOwnProperty(uM(t))};Ks.prototype.set=function(t,e){this.map[uM(t)]=Ede(e)};Ks.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)};Ks.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),Ade(t)};Ks.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),Ade(t)};Ks.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),Ade(t)};qc.iterable&&(Ks.prototype[Symbol.iterator]=Ks.prototype.entries);ORt=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];CI.prototype.clone=function(){return new CI(this,{body:this._bodyInit})};AVe.call(CI.prototype);AVe.call($g.prototype);$g.prototype.clone=function(){return new $g(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new Ks(this.headers),url:this.url})};$g.error=function(){var t=new $g(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};$Rt=[301,302,303,307,308];$g.redirect=function(t,e){if($Rt.indexOf(e)===-1)throw new RangeError("Invalid status code");return new $g(null,{status:e,headers:{location:t}})};bI=Cl.DOMException;try{new bI}catch{bI=function(e,n){this.message=e,this.name=n;var r=Error(e);this.stack=r.stack},bI.prototype=Object.create(Error.prototype),bI.prototype.constructor=bI}kVe.polyfill=!0;Cl.fetch||(Cl.fetch=kVe,Cl.Headers=Ks,Cl.Request=CI,Cl.Response=$g)});function zRt(){if(typeof window<"u"&&window.navigator){let t=navigator;return"userAgentData"in t&&t.userAgentData?.platform?`${t.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process<"u")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function jRt(t){if(t instanceof Headers){let e={};return t.forEach((n,r)=>{e[r]=n}),e}else return Array.isArray(t)?Object.fromEntries(t):t||{}}var NVe,OVe,FRt,URt,BRt,kde,Ode,Rde,Lde,VRt,Dde,Mde,eC,WRt,HRt,KRt,qRt,GRt,Nde,dM,FRn,v5=C(()=>{MVe();NVe="11434",OVe=`http://127.0.0.1:${NVe}`,FRt="0.6.3",URt=Object.defineProperty,BRt=(t,e,n)=>e in t?URt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kde=(t,e,n)=>(BRt(t,typeof e!="symbol"?e+"":e,n),n),Ode=class t extends Error{constructor(e,n){super(e),this.error=e,this.status_code=n,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,t)}},Rde=class{constructor(e,n,r){kde(this,"abortController"),kde(this,"itr"),kde(this,"doneCallback"),this.abortController=e,this.itr=n,this.doneCallback=r}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||e.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}},Lde=async t=>{if(t.ok)return;let e=`Error ${t.status}: ${t.statusText}`,n=null;if(t.headers.get("content-type")?.includes("application/json"))try{n=await t.json(),e=n.error||e}catch{console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await t.text()||e}catch{console.log("Failed to get text from error response")}throw new Ode(e,t.status)};VRt=(t,e)=>t[e],Dde=async(t,e,n={})=>{let r={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${FRt} (${zRt()})`};n.headers=jRt(n.headers);try{let i=new URL(e);if(i.protocol==="https:"&&i.hostname==="ollama.com"){let s=typeof process=="object"&&process!==null&&typeof process.env=="object"&&process.env!==null?VRt(process.env,"OLLAMA_API_KEY"):void 0;!(n.headers.authorization||n.headers.Authorization)&&s&&(n.headers.Authorization=`Bearer ${s}`)}}catch(i){console.error("error parsing url",i)}let o=Object.fromEntries(Object.entries(n.headers).filter(([i])=>!Object.keys(r).some(s=>s.toLowerCase()===i.toLowerCase())));return n.headers={...r,...o},t(e,n)},Mde=async(t,e,n)=>{let r=await Dde(t,e,{headers:n?.headers});return await Lde(r),r},eC=async(t,e,n,r)=>{let i=(a=>a!==null&&typeof a=="object"&&!Array.isArray(a))(n)?JSON.stringify(n):n,s=await Dde(t,e,{method:"POST",body:i,signal:r?.signal,headers:r?.headers});return await Lde(s),s},WRt=async(t,e,n,r)=>{let o=await Dde(t,e,{method:"DELETE",body:JSON.stringify(n),headers:r?.headers});return await Lde(o),o},HRt=async function*(t){let e=new TextDecoder("utf-8"),n="",r=t.getReader();for(;;){let{done:o,value:i}=await r.read();if(o)break;n+=e.decode(i,{stream:!0});let s=n.split(`
`);n=s.pop()??"";for(let a of s)try{yield JSON.parse(a)}catch{console.warn("invalid json: ",a)}}n+=e.decode();for(let o of n.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch{console.warn("invalid json: ",o)}},KRt=t=>{if(!t)return OVe;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let n=new URL(t),r=n.port;r||(e?r=n.protocol==="https:"?"443":"80":r=NVe);let o="";n.username&&(o=n.username,n.password&&(o+=`:${n.password}`),o+="@");let i=`${n.protocol}//${o}${n.hostname}:${r}${n.pathname}`;return i.endsWith("/")&&(i=i.slice(0,-1)),i},qRt=Object.defineProperty,GRt=(t,e,n)=>e in t?qRt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Nde=(t,e,n)=>(GRt(t,typeof e!="symbol"?e+"":e,n),n),dM=class{constructor(e){Nde(this,"config"),Nde(this,"fetch"),Nde(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e?.headers},e?.proxy||(this.config.host=KRt(e?.host??OVe)),this.fetch=e?.fetch??fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,n){n.stream=n.stream??!1;let r=`${this.config.host}/api/${e}`;if(n.stream){let i=new AbortController,s=await eC(this.fetch,r,n,{signal:i.signal,headers:this.config.headers});if(!s.body)throw new Error("Missing body");let a=HRt(s.body),l=new Rde(i,a,()=>{let c=this.ongoingStreamedRequests.indexOf(l);c>-1&&this.ongoingStreamedRequests.splice(c,1)});return this.ongoingStreamedRequests.push(l),l}return await(await eC(this.fetch,r,n,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let n=new Uint8Array(e),r="",o=n.byteLength;for(let i=0;i<o;i++)r+=String.fromCharCode(n[i]);return btoa(r)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let n of e.messages)n.images&&(n.images=await Promise.all(n.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await WRt(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await eC(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Mde(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await eC(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await eC(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await eC(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Mde(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}async version(){return await(await Mde(this.fetch,`${this.config.host}/api/version`,{headers:this.config.headers})).json()}async webSearch(e){if(!e.query||e.query.length===0)throw new Error("Query is required");return await(await eC(this.fetch,"https://ollama.com/api/web_search",{...e},{headers:this.config.headers})).json()}async webFetch(e){if(!e.url||e.url.length===0)throw new Error("URL is required");return await(await eC(this.fetch,"https://ollama.com/api/web_fetch",{...e},{headers:this.config.headers})).json()}},FRn=new dM});var fM=C(()=>{$n();yde()});var $de,RVe=C(()=>{SVe();Kr();vI();v5();ac();jm();pI();Og();Uw();fM();Jo();Bd();Bu();$de=class extends dp{constructor(e){super(e??{});I(this,"model","llama3");I(this,"numa");I(this,"numCtx");I(this,"numBatch");I(this,"numGpu");I(this,"mainGpu");I(this,"lowVram");I(this,"f16Kv");I(this,"logitsAll");I(this,"vocabOnly");I(this,"useMmap");I(this,"useMlock");I(this,"embeddingOnly");I(this,"numThread");I(this,"numKeep");I(this,"seed");I(this,"numPredict");I(this,"topK");I(this,"topP");I(this,"tfsZ");I(this,"typicalP");I(this,"repeatLastN");I(this,"temperature");I(this,"repeatPenalty");I(this,"presencePenalty");I(this,"frequencyPenalty");I(this,"mirostat");I(this,"mirostatTau");I(this,"mirostatEta");I(this,"penalizeNewline");I(this,"streaming");I(this,"format");I(this,"keepAlive");I(this,"client");I(this,"checkOrPullModel",!1);I(this,"baseUrl","http://127.0.0.1:11434");I(this,"think");this.baseUrl=e?.baseUrl??In("OLLAMA_BASE_URL")??this.baseUrl,this.client=new dM({fetch:e?.fetch,host:this.baseUrl,headers:e?.headers}),this.model=e?.model??this.model,this.numa=e?.numa,this.numCtx=e?.numCtx,this.numBatch=e?.numBatch,this.numGpu=e?.numGpu,this.mainGpu=e?.mainGpu,this.lowVram=e?.lowVram,this.f16Kv=e?.f16Kv,this.logitsAll=e?.logitsAll,this.vocabOnly=e?.vocabOnly,this.useMmap=e?.useMmap,this.useMlock=e?.useMlock,this.embeddingOnly=e?.embeddingOnly,this.numThread=e?.numThread,this.numKeep=e?.numKeep,this.seed=e?.seed,this.numPredict=e?.numPredict,this.topK=e?.topK,this.topP=e?.topP,this.tfsZ=e?.tfsZ,this.typicalP=e?.typicalP,this.repeatLastN=e?.repeatLastN,this.temperature=e?.temperature,this.repeatPenalty=e?.repeatPenalty,this.presencePenalty=e?.presencePenalty,this.frequencyPenalty=e?.frequencyPenalty,this.mirostat=e?.mirostat,this.mirostatTau=e?.mirostatTau,this.mirostatEta=e?.mirostatEta,this.penalizeNewline=e?.penalizeNewline,this.streaming=e?.streaming,this.format=e?.format,this.keepAlive=e?.keepAlive,this.think=e?.think,this.checkOrPullModel=e?.checkOrPullModel??this.checkOrPullModel}static lc_name(){return"ChatOllama"}_llmType(){return"ollama"}async pull(e,n){let{stream:r,insecure:o,logProgress:i}={stream:!0,...n};if(r)for await(let s of await this.client.pull({model:e,insecure:o,stream:r}))i&&console.log(s);else{let s=await this.client.pull({model:e,insecure:o});i&&console.log(s)}}bindTools(e,n){return this.withConfig({tools:e.map(r=>Gb(r)),...n})}getLsParams(e){let n=this.invocationParams(e);return{ls_provider:"ollama",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.options?.temperature??void 0,ls_max_tokens:n.options?.num_predict??void 0,ls_stop:e.stop}}invocationParams(e){return{model:this.model,format:e?.format??this.format,keep_alive:this.keepAlive,think:this.think,options:{numa:this.numa,num_ctx:this.numCtx,num_batch:this.numBatch,num_gpu:this.numGpu,main_gpu:this.mainGpu,low_vram:this.lowVram,f16_kv:this.f16Kv,logits_all:this.logitsAll,vocab_only:this.vocabOnly,use_mmap:this.useMmap,use_mlock:this.useMlock,embedding_only:this.embeddingOnly,num_thread:this.numThread,num_keep:this.numKeep,seed:this.seed,num_predict:this.numPredict,top_k:this.topK,top_p:this.topP,tfs_z:this.tfsZ,typical_p:this.typicalP,repeat_last_n:this.repeatLastN,temperature:this.temperature,repeat_penalty:this.repeatPenalty,presence_penalty:this.presencePenalty,frequency_penalty:this.frequencyPenalty,mirostat:this.mirostat,mirostat_tau:this.mirostatTau,mirostat_eta:this.mirostatEta,penalize_newline:this.penalizeNewline,stop:e?.stop},tools:e?.tools?.length?e.tools.map(n=>Gb(n)):void 0}}async checkModelExistsOnMachine(e){let{models:n}=await this.client.list();return!!n.find(r=>r.name===e||r.name===`${e}:latest`)}async _generate(e,n,r){n.signal?.throwIfAborted(),this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let o;for await(let s of this._streamResponseChunks(e,n,r))o?o=Um(o,s.message):o=s.message;let i=new kn({id:o?.id,content:o?.content??"",additional_kwargs:o?.additional_kwargs,tool_calls:o?.tool_calls,response_metadata:o?.response_metadata,usage_metadata:o?.usage_metadata});return{generations:[{text:typeof i.content=="string"?i.content:"",message:i}]}}async*_streamResponseChunks(e,n,r){this.checkOrPullModel&&(await this.checkModelExistsOnMachine(this.model)||await this.pull(this.model,{logProgress:!0}));let o=this.invocationParams(n),i=_Ve(e),s={input_tokens:0,output_tokens:0,total_tokens:0},a=await this.client.chat({...o,messages:i,stream:!0}),l;for await(let c of a){if(n.signal?.aborted){this.client.abort();return}let{message:u,...d}=c;s.input_tokens+=d.prompt_eval_count??0,s.output_tokens+=d.eval_count??0,s.total_tokens=s.input_tokens+s.output_tokens,l=d;let f=this.think?u.thinking??u.content??"":u.content??"",p=new Jr({text:f,message:CVe(u)});yield p,await r?.handleLLMNewToken(f,void 0,void 0,void 0,void 0,{chunk:p})}yield new Jr({text:"",message:new Yt({content:"",response_metadata:{...l,model_provider:"ollama"},usage_metadata:s})})}withStructuredOutput(e,n){let r,o,{schema:i,name:s,includeRaw:a}={...n,schema:e},l=n?.method??"jsonSchema";if(l==="functionCalling"){let f=s??"extract";if(jr(i)){let p=Hr(i);r=this.bindTools([{type:"function",function:{name:f,description:p.description,parameters:p}}]).withConfig({ls_structured_output_format:{kwargs:{method:l},schema:p}}),o=new up({returnSingle:!0,keyName:f,zodSchema:i})}else{let p;typeof i.name=="string"&&typeof i.parameters=="object"&&i.parameters!=null?(p=i,f=i.name):p={name:f,description:i.description??"",parameters:i},r=this.bindTools([{type:"function",function:p}]).withConfig({ls_structured_output_format:{kwargs:{method:l},schema:i}}),o=new up({returnSingle:!0,keyName:f})}}else if(l==="jsonMode"){o=jr(i)?Vm.fromZodSchema(i):new Gd;let f=Hr(i);r=this.withConfig({format:"json",ls_structured_output_format:{kwargs:{method:l},schema:f}})}else if(l==="jsonSchema"){o=jr(i)?Vm.fromZodSchema(i):new Gd;let f=Hr(i);r=this.withConfig({format:f,ls_structured_output_format:{kwargs:{method:l},schema:f}})}else throw new TypeError(`Unrecognized structured output method '${l}'. Expected one of 'functionCalling', 'jsonMode', or 'jsonSchema'`);if(!a)return r.pipe(o).withConfig({runName:"ChatOllamaStructuredOutput"});let c=xl.assign({parsed:(f,p)=>o.invoke(f.raw,p)}),u=xl.assign({parsed:()=>null}),d=c.withFallbacks({fallbacks:[u]});return Kc.from([{raw:r},d]).withConfig({runName:"StructuredOutputRunnable"})}}});var Fde,LVe=C(()=>{v5();Jo();dU();Fde=class extends Qb{constructor(e){super({maxConcurrency:1,...e});I(this,"model","mxbai-embed-large");I(this,"baseUrl","http://localhost:11434");I(this,"dimensions");I(this,"keepAlive");I(this,"requestOptions");I(this,"client");I(this,"truncate",!1);this.baseUrl=e?.baseUrl??In("OLLAMA_BASE_URL")??this.baseUrl,this.client=new dM({fetch:e?.fetch,host:this.baseUrl,headers:e?.headers?new Headers(e.headers):void 0}),this.model=e?.model??this.model,this.dimensions=e?.dimensions,this.keepAlive=e?.keepAlive,this.truncate=e?.truncate??this.truncate,this.requestOptions=e?.requestOptions?this._convertOptions(e?.requestOptions):void 0}_convertOptions(e){let n={},r={embeddingOnly:"embedding_only",frequencyPenalty:"frequency_penalty",keepAlive:"keep_alive",logitsAll:"logits_all",lowVram:"low_vram",mainGpu:"main_gpu",mirostat:"mirostat",mirostatEta:"mirostat_eta",mirostatTau:"mirostat_tau",numBatch:"num_batch",numCtx:"num_ctx",numGpu:"num_gpu",numKeep:"num_keep",numPredict:"num_predict",numThread:"num_thread",penalizeNewline:"penalize_newline",presencePenalty:"presence_penalty",repeatLastN:"repeat_last_n",repeatPenalty:"repeat_penalty",temperature:"temperature",stop:"stop",tfsZ:"tfs_z",topK:"top_k",topP:"top_p",typicalP:"typical_p",useMlock:"use_mlock",useMmap:"use_mmap",vocabOnly:"vocab_only",f16Kv:"f16_kv",numa:"numa",seed:"seed"};for(let[o,i]of Object.entries(e)){let s=r[o];s?n[s]=i:n[o]=i}return n}async embedDocuments(e){return this.embeddingWithRetry(e)}async embedQuery(e){return(await this.embeddingWithRetry([e]))[0]}async embeddingWithRetry(e){return(await this.caller.call(()=>this.client.embed({model:this.model,input:e,dimensions:this.dimensions,keep_alive:this.keepAlive,options:this.requestOptions,truncate:this.truncate}))).embeddings}}});var Ude=C(()=>{$n();k2();Hb();Og();ac();qd()});var DVe=C(()=>{v5();ac();Jo();Ude()});var Bde=C(()=>{RVe();LVe();DVe()});function pU(t,e){return t.lc_error_code=e,t.message=`${t.message}

Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}var $Ve=C(()=>{});function Zt(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n}function de(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}var fp=C(()=>{});var zde,jde=C(()=>{zde=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return zde=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))}});function mU(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var hU,x5=C(()=>{hU=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var st,Bi,zi,tC,Fg,pM,mM,hM,gM,yM,wM,vM,xM,bM,CM,Ug,_I,gU,pp=C(()=>{x5();st=class extends Error{},Bi=class t extends st{constructor(e,n,r,o){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=n;let i=n;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new tC({message:r,cause:hU(n)});let i=n?.error;return e===400?new pM(e,i,r,o):e===401?new mM(e,i,r,o):e===403?new hM(e,i,r,o):e===404?new gM(e,i,r,o):e===409?new yM(e,i,r,o):e===422?new wM(e,i,r,o):e===429?new vM(e,i,r,o):e>=500?new xM(e,i,r,o):new t(e,i,r,o)}},zi=class extends Bi{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},tC=class extends Bi{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},Fg=class extends tC{constructor({message:e}={}){super({message:e??"Request timed out."})}},pM=class extends Bi{},mM=class extends Bi{},hM=class extends Bi{},gM=class extends Bi{},yM=class extends Bi{},wM=class extends Bi{},vM=class extends Bi{},xM=class extends Bi{},bM=class extends st{constructor(){super("Could not parse response content as the length limit was reached")}},CM=class extends st{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ug=class extends Error{constructor(e){super(e)}},_I=class extends Bi{constructor(e,n,r){let o="OAuth2 authentication error",i;if(n&&typeof n=="object"){let s=n;i=s.error;let a=s.error_description;a&&typeof a=="string"?o=a:i&&(o=i)}super(e,n,o,r),this.error_code=i}},gU=class extends st{constructor(e,n,r){super(e),this.provider=n,this.cause=r}}});function b5(t){return typeof t!="object"?{}:t??{}}function Wde(t){if(!t)return!0;for(let e in t)return!1;return!0}function UVe(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function _M(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var ZRt,FVe,cc,Vde,BVe,zVe,zw=C(()=>{pp();ZRt=/^[a-z][a-z0-9+.-]*:/i,FVe=t=>ZRt.test(t),cc=t=>(cc=Array.isArray,cc(t)),Vde=cc;BVe=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new st(`${t} must be an integer`);if(e<0)throw new st(`${t} must be a positive integer`);return e},zVe=t=>{try{return JSON.parse(t)}catch{return}}});var Bg,SM=C(()=>{Bg=t=>new Promise(e=>setTimeout(e,t))});var nC,Hde=C(()=>{nC="6.37.0"});function JRt(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function QRt(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}var HVe,XRt,jVe,VVe,WVe,KVe,Kde=C(()=>{Hde();HVe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";XRt=()=>{let t=JRt();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nC,"X-Stainless-OS":VVe(Deno.build.os),"X-Stainless-Arch":jVe(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nC,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nC,"X-Stainless-OS":VVe(globalThis.process.platform??"unknown"),"X-Stainless-Arch":jVe(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=QRt();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nC,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nC,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};jVe=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",VVe=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),KVe=()=>WVe??(WVe=XRt())});function C5(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function qde(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function _5(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return qde({start(){},async pull(n){let{done:r,value:o}=await e.next();r?n.close():n.enqueue(o)},async cancel(){await e.return?.()}})}function Gde(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Yde(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}var TM=C(()=>{});var GVe,YVe=C(()=>{GVe=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});var Zde,Jde,Xde,ZVe,Qde=C(()=>{Zde="RFC3986",Jde=t=>String(t),Xde={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Jde},ZVe="RFC1738"});function XVe(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function tfe(t,e){if(cc(t)){let n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}var S5,zg,efe,JVe,QVe=C(()=>{Qde();zw();S5=(t,e)=>(S5=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),S5(t,e)),zg=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),efe=1024,JVe=(t,e,n,r,o)=>{if(t.length===0)return t;let i=t;if(typeof t=="symbol"?i=Symbol.prototype.toString.call(t):typeof t!="string"&&(i=String(t)),n==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let s="";for(let a=0;a<i.length;a+=efe){let l=i.length>=efe?i.slice(a,a+efe):i,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||o===ZVe&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=zg[d];continue}if(d<2048){c[c.length]=zg[192|d>>6]+zg[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=zg[224|d>>12]+zg[128|d>>6&63]+zg[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=zg[240|d>>18]+zg[128|d>>12&63]+zg[128|d>>6&63]+zg[128|d&63]}s+=c.join("")}return s}});function tLt(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}function rWe(t,e,n,r,o,i,s,a,l,c,u,d,f,p,m,h,g,y){let w=t,v=y,x=0,b=!1;for(;(v=v.get(nfe))!==void 0&&!b;){let A=v.get(t);if(x+=1,typeof A<"u"){if(A===x)throw new RangeError("Cyclic object value");b=!0}typeof v.get(nfe)>"u"&&(x=0)}if(typeof c=="function"?w=c(e,w):w instanceof Date?w=f?.(w):n==="comma"&&cc(w)&&(w=tfe(w,function(A){return A instanceof Date?f?.(A):A})),w===null){if(i)return l&&!h?l(e,qs.encoder,g,"key",p):e;w=""}if(tLt(w)||XVe(w)){if(l){let A=h?e:l(e,qs.encoder,g,"key",p);return[m?.(A)+"="+m?.(l(w,qs.encoder,g,"value",p))]}return[m?.(e)+"="+m?.(String(w))]}let _=[];if(typeof w>"u")return _;let T;if(n==="comma"&&cc(w))h&&l&&(w=tfe(w,l)),T=[{value:w.length>0?w.join(",")||null:void 0}];else if(cc(c))T=c;else{let A=Object.keys(w);T=u?A.sort(u):A}let S=a?String(e).replace(/\./g,"%2E"):String(e),P=r&&cc(w)&&w.length===1?S+"[]":S;if(o&&cc(w)&&w.length===0)return P+"[]";for(let A=0;A<T.length;++A){let O=T[A],D=typeof O=="object"&&typeof O.value<"u"?O.value:w[O];if(s&&D===null)continue;let $=d&&a?O.replace(/\./g,"%2E"):O,B=cc(w)?typeof n=="function"?n(P,$):P:P+(d?"."+$:"["+$+"]");y.set(t,x);let W=new WeakMap;W.set(nfe,y),nWe(_,rWe(D,B,n,r,o,i,s,a,n==="comma"&&h&&cc(w)?null:l,c,u,d,f,p,m,h,g,W))}return _}function nLt(t=qs){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||qs.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=Zde;if(typeof t.format<"u"){if(!S5(Xde,t.format))throw new TypeError("Unknown format option provided.");n=t.format}let r=Xde[n],o=qs.filter;(typeof t.filter=="function"||cc(t.filter))&&(o=t.filter);let i;if(t.arrayFormat&&t.arrayFormat in tWe?i=t.arrayFormat:"indices"in t?i=t.indices?"indices":"repeat":i=qs.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:qs.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:qs.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:qs.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:qs.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?qs.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:qs.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:qs.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:qs.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:qs.encodeValuesOnly,filter:o,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:qs.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:qs.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:qs.strictNullHandling}}function oWe(t,e={}){let n=t,r=nLt(e),o,i;typeof r.filter=="function"?(i=r.filter,n=i("",n)):cc(r.filter)&&(i=r.filter,o=i);let s=[];if(typeof n!="object"||n===null)return"";let a=tWe[r.arrayFormat],l=a==="comma"&&r.commaRoundTrip;o||(o=Object.keys(n)),r.sort&&o.sort(r.sort);let c=new WeakMap;for(let f=0;f<o.length;++f){let p=o[f];r.skipNulls&&n[p]===null||nWe(s,rWe(n[p],p,a,l,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,c))}let u=s.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}var tWe,nWe,eWe,qs,nfe,iWe=C(()=>{QVe();Qde();zw();tWe={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},nWe=function(t,e){Array.prototype.push.apply(t,cc(e)?e:[e])},qs={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:JVe,encodeValuesOnly:!1,format:Zde,formatter:Jde,indices:!1,serializeDate(t){return(eWe??(eWe=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};nfe={}});function sWe(t){return oWe(t,{arrayFormat:"brackets"})}var rfe=C(()=>{iWe()});function cWe(t){let e=0;for(let o of t)e+=o.length;let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n}function IM(t){let e;return(aWe??(e=new globalThis.TextEncoder,aWe=e.encode.bind(e)))(t)}function ofe(t){let e;return(lWe??(e=new globalThis.TextDecoder,lWe=e.decode.bind(e)))(t)}var aWe,lWe,T5=C(()=>{});function oLt(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function uWe(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}var Yd,Zd,SI,dWe=C(()=>{fp();T5();SI=class{constructor(){Yd.set(this,void 0),Zd.set(this,void 0),Zt(this,Yd,new Uint8Array,"f"),Zt(this,Zd,null,"f")}decode(e){if(e==null)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?IM(e):e;Zt(this,Yd,cWe([de(this,Yd,"f"),n]),"f");let r=[],o;for(;(o=oLt(de(this,Yd,"f"),de(this,Zd,"f")))!=null;){if(o.carriage&&de(this,Zd,"f")==null){Zt(this,Zd,o.index,"f");continue}if(de(this,Zd,"f")!=null&&(o.index!==de(this,Zd,"f")+1||o.carriage)){r.push(ofe(de(this,Yd,"f").subarray(0,de(this,Zd,"f")-1))),Zt(this,Yd,de(this,Yd,"f").subarray(de(this,Zd,"f")),"f"),Zt(this,Zd,null,"f");continue}let i=de(this,Zd,"f")!==null?o.preceding-1:o.preceding,s=ofe(de(this,Yd,"f").subarray(0,i));r.push(s),Zt(this,Yd,de(this,Yd,"f").subarray(o.index),"f"),Zt(this,Zd,null,"f")}return r}flush(){return de(this,Yd,"f").length?this.decode(`
`):[]}};Yd=new WeakMap,Zd=new WeakMap;SI.NEWLINE_CHARS=new Set([`
`,"\r"]);SI.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function yU(){}function I5(t,e,n){return!e||P5[t]>P5[n]?yU:e[t].bind(e)}function os(t){let e=t.logger,n=t.logLevel??"off";if(!e)return iLt;let r=fWe.get(e);if(r&&r[0]===n)return r[1];let o={error:I5("error",e,n),warn:I5("warn",e,n),info:I5("info",e,n),debug:I5("debug",e,n)};return fWe.set(e,[n,o]),o}var P5,ife,iLt,fWe,jw,wU=C(()=>{zw();P5={off:0,error:200,warn:300,info:400,debug:500},ife=(t,e,n)=>{if(t){if(UVe(P5,t))return t;os(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(P5))}`)}};iLt={error:yU,warn:yU,info:yU,debug:yU},fWe=new WeakMap;jw=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*sLt(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new st("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new st("Attempted to iterate over a response with no body");let n=new sfe,r=new SI,o=Gde(t.body);for await(let i of aLt(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*aLt(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?IM(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=uWe(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function lLt(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var vU,jg,sfe,afe=C(()=>{fp();pp();TM();dWe();TM();x5();T5();wU();pp();jg=class t{constructor(e,n,r){this.iterator=e,vU.set(this,void 0),this.controller=n,Zt(this,vU,r,"f")}static fromSSEResponse(e,n,r,o){let i=!1,s=r?os(r):console;async function*a(){if(i)throw new st("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let l=!1;try{for await(let c of sLt(e,n))if(!l){if(c.data.startsWith("[DONE]")){l=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let u;try{u=JSON.parse(c.data)}catch(d){throw s.error("Could not parse message into JSON:",c.data),s.error("From chunk:",c.raw),d}if(u&&u.error)throw new Bi(void 0,u.error,void 0,e.headers);yield o?{event:c.event,data:u}:u}else{let u;try{u=JSON.parse(c.data)}catch(d){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),d}if(c.event=="error")throw new Bi(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}l=!0}catch(c){if(mU(c))return;throw c}finally{l||n.abort()}}return new t(a,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new SI,l=Gde(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new st("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(mU(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}[(vU=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller,de(this,vU,"f")),new t(()=>o(n),this.controller,de(this,vU,"f"))]}toReadableStream(){let e=this,n;return qde({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:o,done:i}=await n.next();if(i)return r.close();let s=IM(JSON.stringify(o)+`
`);r.enqueue(s)}catch(o){r.error(o)}},async cancel(){await n.return?.()}})}};sfe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=lLt(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}}});async function E5(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(e.options.stream)return os(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData):jg.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let f=await n.json();return lfe(f,n)}return await n.text()})();return os(t).debug(`[${r}] response parsed`,jw({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}function lfe(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var cfe=C(()=>{afe();wU()});var xU,TI,A5=C(()=>{fp();cfe();TI=class t extends Promise{constructor(e,n,r=E5){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,xU.set(this,void 0),Zt(this,xU,e,"f")}_thenUnwrap(e){return new t(de(this,xU,"f"),this.responsePromise,async(n,r)=>lfe(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(de(this,xU,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};xU=new WeakMap});var k5,PM,bU,uc,Fn,Xr,Cs,Pn=C(()=>{fp();pp();cfe();A5();zw();PM=class{constructor(e,n,r,o){k5.set(this,void 0),Zt(this,k5,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new st("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await de(this,k5,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(k5=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},bU=class extends TI{constructor(e,n,r){super(e,n,async(o,i)=>new r(o,i.response,await E5(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},uc=class extends PM{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},Fn=class extends PM{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),n=e[e.length-1]?.id;return n?{...this.options,query:{...b5(this.options.query),after:n}}:null}},Xr=class extends PM{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...b5(this.options.query),after:e}}:null}},Cs=class extends PM{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...b5(this.options.query),after:e}}:null}}});var uLt,dLt,M5,pWe=C(()=>{TM();pp();uLt={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},dLt="urn:ietf:params:oauth:grant-type:token-exchange",M5=class{constructor(e,n){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=n??C5()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),n=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({grant_type:dLt,client_id:this.config.clientId,subject_token:e,subject_token_type:uLt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId})});if(!n.ok){let s=await n.text(),a;try{a=JSON.parse(s)}catch{}throw n.status===400||n.status===401||n.status===403?new _I(n.status,a,n.headers):Bi.generate(n.status,a,`Token exchange failed with status ${n.status}`,n.headers)}let r=await n.json(),o=r.expires_in||3600,i=Date.now()+o*1e3;return this.cachedToken={token:r.access_token,expiresAt:i},r.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}});function EM(t,e,n){return ffe(),new File(t,e??"unknown_file",n)}function CU(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}function fLt(t){let e=typeof t=="function"?t:t.fetch,n=mWe.get(e);if(n)return n;let r=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return mWe.set(e,r),r}var ffe,N5,rC,dc,mWe,hWe,gWe,pLt,ufe,dfe,mp=C(()=>{TM();ffe=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};N5=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",rC=async(t,e)=>ufe(t.body)?{...t,body:await hWe(t.body,e)}:t,dc=async(t,e)=>({...t,body:await hWe(t.body,e)}),mWe=new WeakMap;hWe=async(t,e)=>{if(!await fLt(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,o])=>dfe(n,r,o))),n},gWe=t=>t instanceof Blob&&"name"in t,pLt=t=>typeof t=="object"&&t!==null&&(t instanceof Response||N5(t)||gWe(t)),ufe=t=>{if(pLt(t))return!0;if(Array.isArray(t))return t.some(ufe);if(t&&typeof t=="object"){for(let e in t)if(ufe(t[e]))return!0}return!1},dfe=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,EM([await n.blob()],CU(n)));else if(N5(n))t.append(e,EM([await new Response(_5(n)).blob()],CU(n)));else if(gWe(n))t.append(e,n,CU(n));else if(Array.isArray(n))await Promise.all(n.map(r=>dfe(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,o])=>dfe(t,`${e}[${r}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}});async function _U(t,e,n){if(ffe(),t=await t,mLt(t))return t instanceof File?t:EM([await t.arrayBuffer()],t.name);if(hLt(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),EM(await pfe(o),e,n)}let r=await pfe(t);if(e||(e=CU(t)),!n?.type){let o=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof o=="string"&&(n={...n,type:o})}return EM(r,e,n)}async function pfe(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(yWe(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(N5(t))for await(let n of t)e.push(...await pfe(n));else{let n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${gLt(t)}`)}return e}function gLt(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}var yWe,mLt,hLt,wWe=C(()=>{mp();mp();yWe=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",mLt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&yWe(t),hLt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function"});var mfe=C(()=>{wWe()});var le,Ge=C(()=>{le=class{constructor(e){this._client=e}}});function xWe(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var vWe,wLt,Q,Qt=C(()=>{pp();vWe=Object.freeze(Object.create(null)),wLt=(t=xWe)=>function(n,...r){if(n.length===1)return n[0];let o=!1,i=[],s=n.reduce((u,d,f)=>{/[?#]/.test(d)&&(o=!0);let p=r[f],m=(o?encodeURIComponent:t)(""+p);return f!==r.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??vWe)??vWe)?.toString)&&(m=p+"",i.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),u+d+(f===r.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(i.sort((u,d)=>u.start-d.start),i.length>0){let u=0,d=i.reduce((f,p)=>{let m=" ".repeat(p.start-u),h="^".repeat(p.length);return u=p.start+p.length,f+m+h},"");throw new st(`Path parameters result in path with invalid segments:
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},Q=wLt(xWe)});var II,O5=C(()=>{Ge();Pn();Qt();II=class extends le{list(e,n={},r){return this._client.getAPIList(Q`/chat/completions/${e}/messages`,Fn,{query:n,...r,__security:{bearerAuth:!0}})}}});var Wm=C(()=>{pp()});function SU(t){return t!==void 0&&"function"in t&&t.function!==void 0}function bWe(t,e){let n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function TU(t){return t?.$brand==="auto-parseable-response-format"}function PI(t){return t?.$brand==="auto-parseable-tool"}function CWe(t,e){return!e||!hfe(e)?{...t,choices:t.choices.map(n=>(SWe(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:IU(t,e)}function IU(t,e){let n=t.choices.map(r=>{if(r.finish_reason==="length")throw new bM;if(r.finish_reason==="content_filter")throw new CM;return SWe(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(o=>CLt(e,o))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?bLt(e,r.message.content):null}}});return{...t,choices:n}}function bLt(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function CLt(t,e){let n=t.tools?.find(r=>SU(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:PI(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function _We(t,e){if(!t||!("tools"in t)||!t.tools)return!1;let n=t.tools?.find(r=>SU(r)&&r.function?.name===e.function.name);return SU(n)&&(PI(n)||n?.function.strict||!1)}function hfe(t){return TU(t.response_format)?!0:t.tools?.some(e=>PI(e)||e.type==="function"&&e.function.strict===!0)??!1}function SWe(t){for(let e of t||[])if(e.type!=="function")throw new st(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function TWe(t){for(let e of t??[]){if(e.type!=="function")throw new st(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new st(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var AM=C(()=>{Wm()});var kM,gfe,yfe=C(()=>{kM=t=>t?.role==="assistant",gfe=t=>t?.role==="tool"});var wfe,R5,L5,PU,EU,D5,AU,Vw,kU,$5,F5,MM,IWe,oC,U5=C(()=>{fp();Wm();oC=class{constructor(){wfe.add(this),this.controller=new AbortController,R5.set(this,void 0),L5.set(this,()=>{}),PU.set(this,()=>{}),EU.set(this,void 0),D5.set(this,()=>{}),AU.set(this,()=>{}),Vw.set(this,{}),kU.set(this,!1),$5.set(this,!1),F5.set(this,!1),MM.set(this,!1),Zt(this,R5,new Promise((e,n)=>{Zt(this,L5,e,"f"),Zt(this,PU,n,"f")}),"f"),Zt(this,EU,new Promise((e,n)=>{Zt(this,D5,e,"f"),Zt(this,AU,n,"f")}),"f"),de(this,R5,"f").catch(()=>{}),de(this,EU,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},de(this,wfe,"m",IWe).bind(this))},0)}_connected(){this.ended||(de(this,L5,"f").call(this),this._emit("connect"))}get ended(){return de(this,kU,"f")}get errored(){return de(this,$5,"f")}get aborted(){return de(this,F5,"f")}abort(){this.controller.abort()}on(e,n){return(de(this,Vw,"f")[e]||(de(this,Vw,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=de(this,Vw,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(de(this,Vw,"f")[e]||(de(this,Vw,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{Zt(this,MM,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){Zt(this,MM,!0,"f"),await de(this,EU,"f")}_emit(e,...n){if(de(this,kU,"f"))return;e==="end"&&(Zt(this,kU,!0,"f"),de(this,D5,"f").call(this));let r=de(this,Vw,"f")[e];if(r&&(de(this,Vw,"f")[e]=r.filter(o=>!o.once),r.forEach(({listener:o})=>o(...n))),e==="abort"){let o=n[0];!de(this,MM,"f")&&!r?.length&&Promise.reject(o),de(this,PU,"f").call(this,o),de(this,AU,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=n[0];!de(this,MM,"f")&&!r?.length&&Promise.reject(o),de(this,PU,"f").call(this,o),de(this,AU,"f").call(this,o),this._emit("end")}}_emitFinal(){}};R5=new WeakMap,L5=new WeakMap,PU=new WeakMap,EU=new WeakMap,D5=new WeakMap,AU=new WeakMap,Vw=new WeakMap,kU=new WeakMap,$5=new WeakMap,F5=new WeakMap,MM=new WeakMap,wfe=new WeakSet,IWe=function(e){if(Zt(this,$5,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new zi),e instanceof zi)return Zt(this,F5,!0,"f"),this._emit("abort",e);if(e instanceof st)return this._emit("error",e);if(e instanceof Error){let n=new st(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new st(String(e)))}});function PWe(t){return typeof t.parse=="function"}var vfe=C(()=>{});var Gc,xfe,B5,bfe,Cfe,_fe,EWe,AWe,_Lt,NM,Sfe=C(()=>{fp();Wm();AM();yfe();U5();vfe();_Lt=10,NM=class extends oC{constructor(){super(...arguments),Gc.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let n=e.choices[0]?.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),gfe(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(kM(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new st("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),de(this,Gc,"m",xfe).call(this)}async finalMessage(){return await this.done(),de(this,Gc,"m",B5).call(this)}async finalFunctionToolCall(){return await this.done(),de(this,Gc,"m",bfe).call(this)}async finalFunctionToolCallResult(){return await this.done(),de(this,Gc,"m",Cfe).call(this)}async totalUsage(){return await this.done(),de(this,Gc,"m",_fe).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let n=de(this,Gc,"m",B5).call(this);n&&this._emit("finalMessage",n);let r=de(this,Gc,"m",xfe).call(this);r&&this._emit("finalContent",r);let o=de(this,Gc,"m",bfe).call(this);o&&this._emit("finalFunctionToolCall",o);let i=de(this,Gc,"m",Cfe).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(s=>s.usage)&&this._emit("totalUsage",de(this,Gc,"m",_fe).call(this))}async _createChatCompletion(e,n,r){let o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),de(this,Gc,"m",EWe).call(this,n);let i=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(IU(i,n))}async _runChatCompletion(e,n,r){for(let o of n.messages)this._addMessage(o,!1);return await this._createChatCompletion(e,n,r)}async _runTools(e,n,r){let o="tool",{tool_choice:i="auto",stream:s,...a}=n,l=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:c=_Lt}=r||{},u=n.tools.map(p=>{if(PI(p)){if(!p.$callback)throw new st("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:p.$callback,name:p.function.name,description:p.function.description||"",parameters:p.function.parameters,parse:p.$parseRaw,strict:!0}}}return p}),d={};for(let p of u)p.type==="function"&&(d[p.function.name||p.function.function.name]=p.function);let f="tools"in n?u.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description,strict:p.function.strict}}:p):void 0;for(let p of n.messages)this._addMessage(p,!1);for(let p=0;p<c;++p){let h=(await this._createChatCompletion(e,{...a,tool_choice:i,tools:f,messages:[...this.messages]},r)).choices[0]?.message;if(!h)throw new st("missing message in ChatCompletion response");if(!h.tool_calls?.length)return;for(let g of h.tool_calls){if(g.type!=="function")continue;let y=g.id,{name:w,arguments:v}=g.function,x=d[w];if(x){if(l&&l!==w){let S=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:o,tool_call_id:y,content:S});continue}}else{let S=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(d).map(P=>JSON.stringify(P)).join(", ")}. Please try again`;this._addMessage({role:o,tool_call_id:y,content:S});continue}let b;try{b=PWe(x)?await x.parse(v):v}catch(S){let P=S instanceof Error?S.message:String(S);this._addMessage({role:o,tool_call_id:y,content:P});continue}let _=await x.function(b,this),T=de(this,Gc,"m",AWe).call(this,_);if(this._addMessage({role:o,tool_call_id:y,content:T}),l)return}}}};Gc=new WeakSet,xfe=function(){return de(this,Gc,"m",B5).call(this).content??null},B5=function(){let e=this.messages.length;for(;e-- >0;){let n=this.messages[e];if(kM(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new st("stream ended without producing a ChatCompletionMessage with role=assistant")},bfe=function(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(kM(n)&&n?.tool_calls?.length)return n.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},Cfe=function(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(gfe(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(o=>o.type==="function"&&o.id===n.tool_call_id)))return n.content}},_fe=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},EWe=function(e){if(e.n!=null&&e.n>1)throw new st("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},AWe=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)}});var MU,Tfe=C(()=>{Sfe();yfe();MU=class t extends NM{static runTools(e,n,r){let o=new t,i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,n,i)),o}_addMessage(e,n=!0){super._addMessage(e,n),kM(e)&&e.content&&this._emit("content",e.content)}}});function SLt(t,e=$a.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return TLt(t.trim(),e)}var $a,Ife,Pfe,TLt,Efe,kWe=C(()=>{$a={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Ife=class extends Error{},Pfe=class extends Error{};TLt=(t,e)=>{let n=t.length,r=0,o=f=>{throw new Ife(`${f} at position ${r}`)},i=f=>{throw new Pfe(`${f} at position ${r}`)},s=()=>(d(),r>=n&&o("Unexpected end of input"),t[r]==='"'?a():t[r]==="{"?l():t[r]==="["?c():t.substring(r,r+4)==="null"||$a.NULL&e&&n-r<4&&"null".startsWith(t.substring(r))?(r+=4,null):t.substring(r,r+4)==="true"||$a.BOOL&e&&n-r<4&&"true".startsWith(t.substring(r))?(r+=4,!0):t.substring(r,r+5)==="false"||$a.BOOL&e&&n-r<5&&"false".startsWith(t.substring(r))?(r+=5,!1):t.substring(r,r+8)==="Infinity"||$a.INFINITY&e&&n-r<8&&"Infinity".startsWith(t.substring(r))?(r+=8,1/0):t.substring(r,r+9)==="-Infinity"||$a.MINUS_INFINITY&e&&1<n-r&&n-r<9&&"-Infinity".startsWith(t.substring(r))?(r+=9,-1/0):t.substring(r,r+3)==="NaN"||$a.NAN&e&&n-r<3&&"NaN".startsWith(t.substring(r))?(r+=3,NaN):u()),a=()=>{let f=r,p=!1;for(r++;r<n&&(t[r]!=='"'||p&&t[r-1]==="\\");)p=t[r]==="\\"?!p:!1,r++;if(t.charAt(r)=='"')try{return JSON.parse(t.substring(f,++r-Number(p)))}catch(m){i(String(m))}else if($a.STR&e)try{return JSON.parse(t.substring(f,r-Number(p))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},l=()=>{r++,d();let f={};try{for(;t[r]!=="}";){if(d(),r>=n&&$a.OBJ&e)return f;let p=a();d(),r++;try{let m=s();Object.defineProperty(f,p,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if($a.OBJ&e)return f;throw m}d(),t[r]===","&&r++}}catch{if($a.OBJ&e)return f;o("Expected '}' at end of object")}return r++,f},c=()=>{r++;let f=[];try{for(;t[r]!=="]";)f.push(s()),d(),t[r]===","&&r++}catch{if($a.ARR&e)return f;o("Expected ']' at end of array")}return r++,f},u=()=>{if(r===0){t==="-"&&$a.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t)}catch(p){if($a.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}i(String(p))}}let f=r;for(t[r]==="-"&&r++;t[r]&&!",]}".includes(t[r]);)r++;r==n&&!($a.NUM&e)&&o("Unterminated number literal");try{return JSON.parse(t.substring(f,r))}catch{t.substring(f,r)==="-"&&$a.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(m){i(String(m))}}},d=()=>{for(;r<n&&` 
\r	`.includes(t[r]);)r++};return s()},Efe=t=>SLt(t,$a.ALL^$a.NUM)});var Afe=C(()=>{afe()});function ILt(t,e){let{id:n,choices:r,created:o,model:i,system_fingerprint:s,...a}=t,l={...a,id:n,choices:r.map(({message:c,finish_reason:u,index:d,logprobs:f,...p})=>{if(!u)throw new st(`missing finish_reason for choice ${d}`);let{content:m=null,function_call:h,tool_calls:g,...y}=c,w=c.role;if(!w)throw new st(`missing role for choice ${d}`);if(h){let{arguments:v,name:x}=h;if(v==null)throw new st(`missing function_call.arguments for choice ${d}`);if(!x)throw new st(`missing function_call.name for choice ${d}`);return{...p,message:{content:m,function_call:{arguments:v,name:x},role:w,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:f}}return g?{...p,index:d,finish_reason:u,logprobs:f,message:{...y,role:w,content:m,refusal:c.refusal??null,tool_calls:g.map((v,x)=>{let{function:b,type:_,id:T,...S}=v,{arguments:P,name:A,...O}=b||{};if(T==null)throw new st(`missing choices[${d}].tool_calls[${x}].id
${V5(t)}`);if(_==null)throw new st(`missing choices[${d}].tool_calls[${x}].type
${V5(t)}`);if(A==null)throw new st(`missing choices[${d}].tool_calls[${x}].function.name
${V5(t)}`);if(P==null)throw new st(`missing choices[${d}].tool_calls[${x}].function.arguments
${V5(t)}`);return{...S,id:T,type:_,function:{...O,name:A,arguments:P}}})}}:{...p,message:{...y,content:m,role:w,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:f}}),created:o,model:i,object:"chat.completion",...s?{system_fingerprint:s}:{}};return CWe(l,e)}function V5(t){return JSON.stringify(t)}var Gs,Ww,OM,iC,kfe,z5,Mfe,Nfe,Ofe,j5,Rfe,MWe,EI,W5=C(()=>{fp();kWe();Wm();AM();Afe();Sfe();EI=class t extends NM{constructor(e){super(),Gs.add(this),Ww.set(this,void 0),OM.set(this,void 0),iC.set(this,void 0),Zt(this,Ww,e,"f"),Zt(this,OM,[],"f")}get currentChatCompletionSnapshot(){return de(this,iC,"f")}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){let o=new t(n);return o._run(()=>o._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createChatCompletion(e,n,r){super._createChatCompletion;let o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),de(this,Gs,"m",kfe).call(this);let i=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let s of i)de(this,Gs,"m",Mfe).call(this,s);if(i.controller.signal?.aborted)throw new zi;return this._addChatCompletion(de(this,Gs,"m",j5).call(this))}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),de(this,Gs,"m",kfe).call(this),this._connected();let o=jg.fromReadableStream(e,this.controller),i;for await(let s of o)i&&i!==s.id&&this._addChatCompletion(de(this,Gs,"m",j5).call(this)),de(this,Gs,"m",Mfe).call(this,s),i=s.id;if(o.controller.signal?.aborted)throw new zi;return this._addChatCompletion(de(this,Gs,"m",j5).call(this))}[(Ww=new WeakMap,OM=new WeakMap,iC=new WeakMap,Gs=new WeakSet,kfe=function(){this.ended||Zt(this,iC,void 0,"f")},z5=function(n){let r=de(this,OM,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},de(this,OM,"f")[n.index]=r,r)},Mfe=function(n){if(this.ended)return;let r=de(this,Gs,"m",MWe).call(this,n);this._emit("chunk",n,r);for(let o of n.choices){let i=r.choices[o.index];o.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",o.delta.content,i.message.content),this._emit("content.delta",{delta:o.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),o.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:o.delta.refusal,snapshot:i.message.refusal}),o.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:i.logprobs?.content??[]}),o.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});let s=de(this,Gs,"m",z5).call(this,i);i.finish_reason&&(de(this,Gs,"m",Ofe).call(this,i),s.current_tool_call_index!=null&&de(this,Gs,"m",Nfe).call(this,i,s.current_tool_call_index));for(let a of o.delta.tool_calls??[])s.current_tool_call_index!==a.index&&(de(this,Gs,"m",Ofe).call(this,i),s.current_tool_call_index!=null&&de(this,Gs,"m",Nfe).call(this,i,s.current_tool_call_index)),s.current_tool_call_index=a.index;for(let a of o.delta.tool_calls??[]){let l=i.message.tool_calls?.[a.index];l?.type&&(l?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:l.function?.name,index:a.index,arguments:l.function.arguments,parsed_arguments:l.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(l?.type,void 0))}}},Nfe=function(n,r){if(de(this,Gs,"m",z5).call(this,n).done_tool_calls.has(r))return;let i=n.message.tool_calls?.[r];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let s=de(this,Ww,"f")?.tools?.find(a=>SU(a)&&a.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:r,arguments:i.function.arguments,parsed_arguments:PI(s)?s.$parseRaw(i.function.arguments):s?.function.strict?JSON.parse(i.function.arguments):null})}else i.type},Ofe=function(n){let r=de(this,Gs,"m",z5).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;let o=de(this,Gs,"m",Rfe).call(this);this._emit("content.done",{content:n.message.content,parsed:o?o.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),n.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),n.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},j5=function(){if(this.ended)throw new st("stream has ended, this shouldn't happen");let n=de(this,iC,"f");if(!n)throw new st("request ended without sending any chunks");return Zt(this,iC,void 0,"f"),Zt(this,OM,[],"f"),ILt(n,de(this,Ww,"f"))},Rfe=function(){let n=de(this,Ww,"f")?.response_format;return TU(n)?n:null},MWe=function(n){var r,o,i,s;let a=de(this,iC,"f"),{choices:l,...c}=n;a?Object.assign(a,c):a=Zt(this,iC,{...c,choices:[]},"f");for(let{delta:u,finish_reason:d,index:f,logprobs:p=null,...m}of n.choices){let h=a.choices[f];if(h||(h=a.choices[f]={finish_reason:d,index:f,message:{},logprobs:p,...m}),p)if(!h.logprobs)h.logprobs=Object.assign({},p);else{let{content:_,refusal:T,...S}=p;Object.assign(h.logprobs,S),_&&((r=h.logprobs).content??(r.content=[]),h.logprobs.content.push(..._)),T&&((o=h.logprobs).refusal??(o.refusal=[]),h.logprobs.refusal.push(...T))}if(d&&(h.finish_reason=d,de(this,Ww,"f")&&hfe(de(this,Ww,"f")))){if(d==="length")throw new bM;if(d==="content_filter")throw new CM}if(Object.assign(h,m),!u)continue;let{content:g,refusal:y,function_call:w,role:v,tool_calls:x,...b}=u;if(Object.assign(h.message,b),y&&(h.message.refusal=(h.message.refusal||"")+y),v&&(h.message.role=v),w&&(h.message.function_call?(w.name&&(h.message.function_call.name=w.name),w.arguments&&((i=h.message.function_call).arguments??(i.arguments=""),h.message.function_call.arguments+=w.arguments)):h.message.function_call=w),g&&(h.message.content=(h.message.content||"")+g,!h.message.refusal&&de(this,Gs,"m",Rfe).call(this)&&(h.message.parsed=Efe(h.message.content))),x){h.message.tool_calls||(h.message.tool_calls=[]);for(let{index:_,id:T,type:S,function:P,...A}of x){let O=(s=h.message.tool_calls)[_]??(s[_]={});Object.assign(O,A),T&&(O.id=T),S&&(O.type=S),P&&(O.function??(O.function={name:P.name??"",arguments:""})),P?.name&&(O.function.name=P.name),P?.arguments&&(O.function.arguments+=P.arguments,_We(de(this,Ww,"f"),O)&&(O.function.parsed_arguments=Efe(O.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("chunk",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new jg(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var NU,Lfe=C(()=>{W5();NU=class t extends EI{static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,r){let o=new t(n),i={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return o._run(()=>o._runTools(e,n,i)),o}}});var Hw,OU=C(()=>{Ge();O5();O5();Pn();Qt();Tfe();Lfe();W5();AM();Lfe();vfe();W5();Tfe();Hw=class extends le{constructor(){super(...arguments),this.messages=new II(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(Q`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(Q`/chat/completions/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chat/completions",Fn,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}parse(e,n){return TWe(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>IU(r,e))}runTools(e,n){return e.stream?NU.runTools(this._client,e,n):MU.runTools(this._client,e,n)}stream(e,n){return EI.createChatCompletion(this._client,e,n)}};Hw.Messages=II});var sC,Dfe=C(()=>{Ge();OU();OU();sC=class extends le{constructor(){super(...arguments),this.completions=new Hw(this._client)}};sC.Completions=Hw});var NWe=C(()=>{OU();OU();O5()});var OWe=C(()=>{Dfe();NWe()});var RWe=C(()=>{});var RM,$fe=C(()=>{Ge();Pn();Qt();RM=class extends le{create(e,n){return this._client.post("/organization/admin_api_keys",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(Q`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/admin_api_keys",Fn,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(Q`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}});var LM,Ffe=C(()=>{Ge();Pn();LM=class extends le{list(e={},n){return this._client.getAPIList("/organization/audit_logs",Xr,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}}});var DM,Ufe=C(()=>{Ge();Pn();Qt();DM=class extends le{create(e,n){return this._client.post("/organization/certificates",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(Q`/organization/certificates/${e}`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(Q`/organization/certificates/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/certificates",Xr,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(Q`/organization/certificates/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}activate(e,n){return this._client.getAPIList("/organization/certificates/activate",uc,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n){return this._client.getAPIList("/organization/certificates/deactivate",uc,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}}});var $M,Bfe=C(()=>{Ge();Pn();Qt();$M=class extends le{create(e,n){return this._client.post("/organization/invites",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(Q`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/invites",Xr,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(Q`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}});var FM,zfe=C(()=>{Ge();Pn();Qt();FM=class extends le{create(e,n){return this._client.post("/organization/roles",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(Q`/organization/roles/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/roles",Cs,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(Q`/organization/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}});var UM,jfe=C(()=>{Ge();UM=class extends le{audioSpeeches(e,n){return this._client.get("/organization/usage/audio_speeches",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,n){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,n){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}completions(e,n){return this._client.get("/organization/usage/completions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}costs(e,n){return this._client.get("/organization/costs",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}embeddings(e,n){return this._client.get("/organization/usage/embeddings",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}images(e,n){return this._client.get("/organization/usage/images",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}moderations(e,n){return this._client.get("/organization/usage/moderations",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,n){return this._client.get("/organization/usage/vector_stores",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}}});var BM,Vfe=C(()=>{Ge();Pn();Qt();BM=class extends le{create(e,n,r){return this._client.post(Q`/organization/groups/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/organization/groups/${e}/roles`,Cs,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{group_id:o}=n;return this._client.delete(Q`/organization/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var zM,Wfe=C(()=>{Ge();Pn();Qt();zM=class extends le{create(e,n,r){return this._client.post(Q`/organization/groups/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/organization/groups/${e}/users`,Cs,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{group_id:o}=n;return this._client.delete(Q`/organization/groups/${o}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var aC,Hfe=C(()=>{Ge();Vfe();Vfe();Wfe();Wfe();Pn();Qt();aC=class extends le{constructor(){super(...arguments),this.users=new zM(this._client),this.roles=new BM(this._client)}create(e,n){return this._client.post("/organization/groups",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(Q`/organization/groups/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/groups",Cs,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(Q`/organization/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};aC.Users=zM;aC.Roles=BM});var jM,Kfe=C(()=>{Ge();Pn();Qt();jM=class extends le{retrieve(e,n,r){let{project_id:o}=n;return this._client.get(Q`/organization/projects/${o}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/organization/projects/${e}/api_keys`,Xr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(Q`/organization/projects/${o}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var VM,qfe=C(()=>{Ge();Pn();Qt();VM=class extends le{list(e,n={},r){return this._client.getAPIList(Q`/organization/projects/${e}/certificates`,Xr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,n,r){return this._client.getAPIList(Q`/organization/projects/${e}/certificates/activate`,uc,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n,r){return this._client.getAPIList(Q`/organization/projects/${e}/certificates/deactivate`,uc,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}}});var WM,Gfe=C(()=>{Ge();Pn();Qt();WM=class extends le{listRateLimits(e,n={},r){return this._client.getAPIList(Q`/organization/projects/${e}/rate_limits`,Xr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,n,r){let{project_id:o,...i}=n;return this._client.post(Q`/organization/projects/${o}/rate_limits/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}}});var HM,Yfe=C(()=>{Ge();Pn();Qt();HM=class extends le{create(e,n,r){return this._client.post(Q`/projects/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:o,...i}=n;return this._client.post(Q`/projects/${o}/roles/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/projects/${e}/roles`,Cs,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(Q`/projects/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var KM,Zfe=C(()=>{Ge();Pn();Qt();KM=class extends le{create(e,n,r){return this._client.post(Q`/organization/projects/${e}/service_accounts`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:o}=n;return this._client.get(Q`/organization/projects/${o}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/organization/projects/${e}/service_accounts`,Xr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(Q`/organization/projects/${o}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var qM,Jfe=C(()=>{Ge();Pn();Qt();qM=class extends le{create(e,n,r){let{project_id:o,...i}=n;return this._client.post(Q`/projects/${o}/groups/${e}/roles`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){let{project_id:o,...i}=n;return this._client.getAPIList(Q`/projects/${o}/groups/${e}/roles`,Cs,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o,group_id:i}=n;return this._client.delete(Q`/projects/${o}/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var AI,Xfe=C(()=>{Ge();Jfe();Jfe();Pn();Qt();AI=class extends le{constructor(){super(...arguments),this.roles=new qM(this._client)}create(e,n,r){return this._client.post(Q`/organization/projects/${e}/groups`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/organization/projects/${e}/groups`,Cs,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(Q`/organization/projects/${o}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};AI.Roles=qM});var GM,Qfe=C(()=>{Ge();Pn();Qt();GM=class extends le{create(e,n,r){let{project_id:o,...i}=n;return this._client.post(Q`/projects/${o}/users/${e}/roles`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){let{project_id:o,...i}=n;return this._client.getAPIList(Q`/projects/${o}/users/${e}/roles`,Cs,{query:i,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o,user_id:i}=n;return this._client.delete(Q`/projects/${o}/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var kI,epe=C(()=>{Ge();Qfe();Qfe();Pn();Qt();kI=class extends le{constructor(){super(...arguments),this.roles=new GM(this._client)}create(e,n,r){return this._client.post(Q`/organization/projects/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){let{project_id:o}=n;return this._client.get(Q`/organization/projects/${o}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){let{project_id:o,...i}=n;return this._client.post(Q`/organization/projects/${o}/users/${e}`,{body:i,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/organization/projects/${e}/users`,Xr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{project_id:o}=n;return this._client.delete(Q`/organization/projects/${o}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};kI.Roles=GM});var Jd,tpe=C(()=>{Ge();Kfe();Kfe();qfe();qfe();Gfe();Gfe();Yfe();Yfe();Zfe();Zfe();Xfe();Xfe();epe();epe();Pn();Qt();Jd=class extends le{constructor(){super(...arguments),this.users=new kI(this._client),this.serviceAccounts=new KM(this._client),this.apiKeys=new jM(this._client),this.rateLimits=new WM(this._client),this.groups=new AI(this._client),this.roles=new HM(this._client),this.certificates=new VM(this._client)}create(e,n){return this._client.post("/organization/projects",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(Q`/organization/projects/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(Q`/organization/projects/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/projects",Xr,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}archive(e,n){return this._client.post(Q`/organization/projects/${e}/archive`,{...n,__security:{adminAPIKeyAuth:!0}})}};Jd.Users=kI;Jd.ServiceAccounts=KM;Jd.APIKeys=jM;Jd.RateLimits=WM;Jd.Groups=AI;Jd.Roles=HM;Jd.Certificates=VM});var YM,npe=C(()=>{Ge();Pn();Qt();YM=class extends le{create(e,n,r){return this._client.post(Q`/organization/users/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/organization/users/${e}/roles`,Cs,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{user_id:o}=n;return this._client.delete(Q`/organization/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var MI,rpe=C(()=>{Ge();npe();npe();Pn();Qt();MI=class extends le{constructor(){super(...arguments),this.roles=new YM(this._client)}retrieve(e,n){return this._client.get(Q`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(Q`/organization/users/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/users",Xr,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(Q`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};MI.Roles=YM});var Yc,ope=C(()=>{Ge();$fe();$fe();Ffe();Ffe();Ufe();Ufe();Bfe();Bfe();zfe();zfe();jfe();jfe();Hfe();Hfe();tpe();tpe();rpe();rpe();Yc=class extends le{constructor(){super(...arguments),this.auditLogs=new LM(this._client),this.adminAPIKeys=new RM(this._client),this.usage=new UM(this._client),this.invites=new $M(this._client),this.users=new MI(this._client),this.groups=new aC(this._client),this.roles=new FM(this._client),this.certificates=new DM(this._client),this.projects=new Jd(this._client)}};Yc.AuditLogs=LM;Yc.AdminAPIKeys=RM;Yc.Usage=UM;Yc.Invites=$M;Yc.Users=MI;Yc.Groups=aC;Yc.Roles=FM;Yc.Certificates=DM;Yc.Projects=Jd});var lC,ipe=C(()=>{Ge();ope();ope();lC=class extends le{constructor(){super(...arguments),this.organization=new Yc(this._client)}};lC.Organization=Yc});function*ZLt(t){if(!t)return;if(LWe in t){let{values:r,nulls:o}=t;yield*r.entries();for(let i of o)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Vde(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){let o=r[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let i=Vde(r[1])?r[1]:[r[1]],s=!1;for(let a of i)a!==void 0&&(e&&!s&&(s=!0,yield[o,null]),yield[o,a])}}var LWe,Fe,Fo=C(()=>{zw();LWe=Symbol("brand.privateNullableHeaders");Fe=t=>{let e=new Headers,n=new Set;for(let r of t){let o=new Set;for(let[i,s]of ZLt(r)){let a=i.toLowerCase();o.has(a)||(e.delete(i),o.add(a)),s===null?(e.delete(i),n.add(a)):(e.append(i,s),n.delete(a))}}return{[LWe]:!0,values:e,nulls:n}}});var ZM,spe=C(()=>{Ge();Fo();ZM=class extends le{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:Fe([{Accept:"application/octet-stream"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}});var JM,ape=C(()=>{Ge();mp();JM=class extends le{create(e,n){return this._client.post("/audio/transcriptions",dc({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}});var XM,lpe=C(()=>{Ge();mp();XM=class extends le{create(e,n){return this._client.post("/audio/translations",dc({body:e,...n,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}});var Vg,cpe=C(()=>{Ge();spe();spe();ape();ape();lpe();lpe();Vg=class extends le{constructor(){super(...arguments),this.transcriptions=new JM(this._client),this.translations=new XM(this._client),this.speech=new ZM(this._client)}};Vg.Transcriptions=JM;Vg.Translations=XM;Vg.Speech=ZM});var NI,upe=C(()=>{Ge();Pn();Qt();NI=class extends le{create(e,n){return this._client.post("/batches",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(Q`/batches/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/batches",Fn,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(Q`/batches/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}}});var QM,dpe=C(()=>{Ge();Pn();Fo();Qt();QM=class extends le{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(Q`/assistants/${e}`,{...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(Q`/assistants/${e}`,{body:n,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/assistants",Fn,{query:e,...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/assistants/${e}`,{...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}});var eN,fpe=C(()=>{Ge();Fo();eN=class extends le{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}});var tN,ppe=C(()=>{Ge();Fo();tN=class extends le{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}}});var cC,mpe=C(()=>{Ge();fpe();fpe();ppe();ppe();cC=class extends le{constructor(){super(...arguments),this.sessions=new eN(this._client),this.transcriptionSessions=new tN(this._client)}};cC.Sessions=eN;cC.TranscriptionSessions=tN});var nN,hpe=C(()=>{Ge();Fo();Qt();nN=class extends le{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:Fe([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(Q`/chatkit/sessions/${e}/cancel`,{...n,headers:Fe([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}}});var rN,gpe=C(()=>{Ge();Pn();Fo();Qt();rN=class extends le{retrieve(e,n){return this._client.get(Q`/chatkit/threads/${e}`,{...n,headers:Fe([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chatkit/threads",Xr,{query:e,...n,headers:Fe([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/chatkit/threads/${e}`,{...n,headers:Fe([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}listItems(e,n={},r){return this._client.getAPIList(Q`/chatkit/threads/${e}/items`,Xr,{query:n,...r,headers:Fe([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}}});var uC,ype=C(()=>{Ge();hpe();hpe();gpe();gpe();uC=class extends le{constructor(){super(...arguments),this.sessions=new nN(this._client),this.threads=new rN(this._client)}};uC.Sessions=nN;uC.Threads=rN});var oN,wpe=C(()=>{Ge();Pn();Fo();Qt();oN=class extends le{create(e,n,r){return this._client.post(Q`/threads/${e}/messages`,{body:n,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){let{thread_id:o}=n;return this._client.get(Q`/threads/${o}/messages/${e}`,{...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){let{thread_id:o,...i}=n;return this._client.post(Q`/threads/${o}/messages/${e}`,{body:i,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/threads/${e}/messages`,Fn,{query:n,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){let{thread_id:o}=n;return this._client.delete(Q`/threads/${o}/messages/${e}`,{...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}});var iN,vpe=C(()=>{Ge();Pn();Fo();Qt();iN=class extends le{retrieve(e,n,r){let{thread_id:o,run_id:i,...s}=n;return this._client.get(Q`/threads/${o}/runs/${i}/steps/${e}`,{query:s,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n,r){let{thread_id:o,...i}=n;return this._client.getAPIList(Q`/threads/${o}/runs/${e}/steps`,Fn,{query:i,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}});var DWe,$We=C(()=>{pp();T5();DWe=t=>{if(typeof Buffer<"u"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),n=e.length,r=new Uint8Array(n);for(let o=0;o<n;o++)r[o]=e.charCodeAt(o);return Array.from(new Float32Array(r.buffer))}}});var Xd,xpe=C(()=>{Xd=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0}});var RU=C(()=>{zw();$We();xpe();wU();jde();SM();rfe()});var _l,RI,bpe,Wg,H5,Hm,LI,sN,OI,G5,Qd,K5,q5,$U,LU,DU,FWe,UWe,BWe,zWe,jWe,VWe,WWe,Kw,Cpe=C(()=>{fp();Afe();Wm();U5();RU();Kw=class extends oC{constructor(){super(...arguments),_l.add(this),bpe.set(this,[]),Wg.set(this,{}),H5.set(this,{}),Hm.set(this,void 0),LI.set(this,void 0),sN.set(this,void 0),OI.set(this,void 0),G5.set(this,void 0),Qd.set(this,void 0),K5.set(this,void 0),q5.set(this,void 0),$U.set(this,void 0)}[(bpe=new WeakMap,Wg=new WeakMap,H5=new WeakMap,Hm=new WeakMap,LI=new WeakMap,sN=new WeakMap,OI=new WeakMap,G5=new WeakMap,Qd=new WeakMap,K5=new WeakMap,q5=new WeakMap,$U=new WeakMap,_l=new WeakSet,Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("event",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let n=new RI;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let o=jg.fromReadableStream(e,this.controller);for await(let i of o)de(this,_l,"m",LU).call(this,i);if(o.controller.signal?.aborted)throw new zi;return this._addRun(de(this,_l,"m",DU).call(this))}toReadableStream(){return new jg(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,r,o){let i=new RI;return i._run(()=>i._runToolAssistantStream(e,n,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,n,r,o){let i=o?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},a=await e.submitToolOutputs(n,s,{...o,signal:this.controller.signal});this._connected();for await(let l of a)de(this,_l,"m",LU).call(this,l);if(a.controller.signal?.aborted)throw new zi;return this._addRun(de(this,_l,"m",DU).call(this))}static createThreadAssistantStream(e,n,r){let o=new RI;return o._run(()=>o._threadAssistantStream(e,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}static createAssistantStream(e,n,r,o){let i=new RI;return i._run(()=>i._runAssistantStream(e,n,r,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return de(this,K5,"f")}currentRun(){return de(this,q5,"f")}currentMessageSnapshot(){return de(this,Hm,"f")}currentRunStepSnapshot(){return de(this,$U,"f")}async finalRunSteps(){return await this.done(),Object.values(de(this,Wg,"f"))}async finalMessages(){return await this.done(),Object.values(de(this,H5,"f"))}async finalRun(){if(await this.done(),!de(this,LI,"f"))throw Error("Final run was not received.");return de(this,LI,"f")}async _createThreadAssistantStream(e,n,r){let o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},s=await e.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(let a of s)de(this,_l,"m",LU).call(this,a);if(s.controller.signal?.aborted)throw new zi;return this._addRun(de(this,_l,"m",DU).call(this))}async _createAssistantStream(e,n,r,o){let i=o?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let s={...r,stream:!0},a=await e.create(n,s,{...o,signal:this.controller.signal});this._connected();for await(let l of a)de(this,_l,"m",LU).call(this,l);if(a.controller.signal?.aborted)throw new zi;return this._addRun(de(this,_l,"m",DU).call(this))}static accumulateDelta(e,n){for(let[r,o]of Object.entries(n)){if(!e.hasOwnProperty(r)){e[r]=o;continue}let i=e[r];if(i==null){e[r]=o;continue}if(r==="index"||r==="type"){e[r]=o;continue}if(typeof i=="string"&&typeof o=="string")i+=o;else if(typeof i=="number"&&typeof o=="number")i+=o;else if(_M(i)&&_M(o))i=this.accumulateDelta(i,o);else if(Array.isArray(i)&&Array.isArray(o)){if(i.every(s=>typeof s=="string"||typeof s=="number")){i.push(...o);continue}for(let s of o){if(!_M(s))throw new Error(`Expected array delta entry to be an object but got: ${s}`);let a=s.index;if(a==null)throw console.error(s),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let l=i[a];l==null?i.push(s):i[a]=this.accumulateDelta(l,s)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${o}, accValue: ${i}`);e[r]=i}return e}_addRun(e){return e}async _threadAssistantStream(e,n,r){return await this._createThreadAssistantStream(n,e,r)}async _runAssistantStream(e,n,r,o){return await this._createAssistantStream(n,e,r,o)}async _runToolAssistantStream(e,n,r,o){return await this._createToolAssistantStream(n,e,r,o)}};RI=Kw,LU=function(e){if(!this.ended)switch(Zt(this,K5,e,"f"),de(this,_l,"m",BWe).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":de(this,_l,"m",WWe).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":de(this,_l,"m",UWe).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":de(this,_l,"m",FWe).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},DU=function(){if(this.ended)throw new st("stream has ended, this shouldn't happen");if(!de(this,LI,"f"))throw Error("Final run has not been received");return de(this,LI,"f")},FWe=function(e){let[n,r]=de(this,_l,"m",jWe).call(this,e,de(this,Hm,"f"));Zt(this,Hm,n,"f"),de(this,H5,"f")[n.id]=n;for(let o of r){let i=n.content[o.index];i?.type=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(let o of e.data.delta.content){if(o.type=="text"&&o.text){let i=o.text,s=n.content[o.index];if(s&&s.type=="text")this._emit("textDelta",i,s.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(o.index!=de(this,sN,"f")){if(de(this,OI,"f"))switch(de(this,OI,"f").type){case"text":this._emit("textDone",de(this,OI,"f").text,de(this,Hm,"f"));break;case"image_file":this._emit("imageFileDone",de(this,OI,"f").image_file,de(this,Hm,"f"));break}Zt(this,sN,o.index,"f")}Zt(this,OI,n.content[o.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(de(this,sN,"f")!==void 0){let o=e.data.content[de(this,sN,"f")];if(o)switch(o.type){case"image_file":this._emit("imageFileDone",o.image_file,de(this,Hm,"f"));break;case"text":this._emit("textDone",o.text,de(this,Hm,"f"));break}}de(this,Hm,"f")&&this._emit("messageDone",e.data),Zt(this,Hm,void 0,"f")}},UWe=function(e){let n=de(this,_l,"m",zWe).call(this,e);switch(Zt(this,$U,n,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(let i of r.step_details.tool_calls)i.index==de(this,G5,"f")?this._emit("toolCallDelta",i,n.step_details.tool_calls[i.index]):(de(this,Qd,"f")&&this._emit("toolCallDone",de(this,Qd,"f")),Zt(this,G5,i.index,"f"),Zt(this,Qd,n.step_details.tool_calls[i.index],"f"),de(this,Qd,"f")&&this._emit("toolCallCreated",de(this,Qd,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Zt(this,$U,void 0,"f"),e.data.step_details.type=="tool_calls"&&de(this,Qd,"f")&&(this._emit("toolCallDone",de(this,Qd,"f")),Zt(this,Qd,void 0,"f")),this._emit("runStepDone",e.data,n);break;case"thread.run.step.in_progress":break}},BWe=function(e){de(this,bpe,"f").push(e),this._emit("event",e)},zWe=function(e){switch(e.event){case"thread.run.step.created":return de(this,Wg,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=de(this,Wg,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let o=RI.accumulateDelta(n,r.delta);de(this,Wg,"f")[e.data.id]=o}return de(this,Wg,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":de(this,Wg,"f")[e.data.id]=e.data;break}if(de(this,Wg,"f")[e.data.id])return de(this,Wg,"f")[e.data.id];throw new Error("No snapshot available")},jWe=function(e,n){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content)for(let i of o.delta.content)if(i.index in n.content){let s=n.content[i.index];n.content[i.index]=de(this,_l,"m",VWe).call(this,i,s)}else n.content[i.index]=i,r.push(i);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},VWe=function(e,n){return RI.accumulateDelta(n,e)},WWe=function(e){switch(Zt(this,q5,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":Zt(this,LI,e.data,"f"),de(this,Qd,"f")&&(this._emit("toolCallDone",de(this,Qd,"f")),Zt(this,Qd,void 0,"f"));break;case"thread.run.cancelling":break}}});var DI,_pe=C(()=>{Ge();vpe();vpe();Pn();Fo();Cpe();SM();Qt();DI=class extends le{constructor(){super(...arguments),this.steps=new iN(this._client)}create(e,n,r){let{include:o,...i}=n;return this._client.post(Q`/threads/${e}/runs`,{query:{include:o},body:i,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,n,r){let{thread_id:o}=n;return this._client.get(Q`/threads/${o}/runs/${e}`,{...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){let{thread_id:o,...i}=n;return this._client.post(Q`/threads/${o}/runs/${e}`,{body:i,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/threads/${e}/runs`,Fn,{query:n,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){let{thread_id:o}=n;return this._client.post(Q`/threads/${o}/runs/${e}/cancel`,{...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){let o=await this.create(e,n,r);return await this.poll(o.id,{thread_id:e},r)}createAndStream(e,n,r){return Kw.createAssistantStream(e,this._client.beta.threads.runs,n,r)}async poll(e,n,r){let o=Fe([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:s}=await this.retrieve(e,n,{...r,headers:{...r?.headers,...o}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let l=s.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await Bg(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,n,r){return Kw.createAssistantStream(e,this._client.beta.threads.runs,n,r)}submitToolOutputs(e,n,r){let{thread_id:o,...i}=n;return this._client.post(Q`/threads/${o}/runs/${e}/submit_tool_outputs`,{body:i,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,n,r){let o=await this.submitToolOutputs(e,n,r);return await this.poll(o.id,n,r)}submitToolOutputsStream(e,n,r){return Kw.createToolAssistantStream(e,this._client.beta.threads.runs,n,r)}};DI.Steps=iN});var dC,Spe=C(()=>{Ge();wpe();wpe();_pe();_pe();Fo();Cpe();Qt();dC=class extends le{constructor(){super(...arguments),this.runs=new DI(this._client),this.messages=new oN(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(Q`/threads/${e}`,{...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(Q`/threads/${e}`,{body:n,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/threads/${e}`,{...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,n){let r=await this.createAndRun(e,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(e,n){return Kw.createThreadAssistantStream(e,this._client.beta.threads,n)}};dC.Runs=DI;dC.Messages=oN});var Km,Tpe=C(()=>{Ge();dpe();dpe();mpe();mpe();ype();ype();Spe();Spe();Km=class extends le{constructor(){super(...arguments),this.realtime=new cC(this._client),this.chatkit=new uC(this._client),this.assistants=new QM(this._client),this.threads=new dC(this._client)}};Km.Realtime=cC;Km.ChatKit=uC;Km.Assistants=QM;Km.Threads=dC});var $I,Ipe=C(()=>{Ge();$I=class extends le{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}}});var aN,Ppe=C(()=>{Ge();Fo();Qt();aN=class extends le{retrieve(e,n,r){let{container_id:o}=n;return this._client.get(Q`/containers/${o}/files/${e}/content`,{...r,headers:Fe([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}});var FI,Epe=C(()=>{Ge();Ppe();Ppe();Pn();Fo();mp();Qt();FI=class extends le{constructor(){super(...arguments),this.content=new aN(this._client)}create(e,n,r){return this._client.post(Q`/containers/${e}/files`,rC({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){let{container_id:o}=n;return this._client.get(Q`/containers/${o}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/containers/${e}/files`,Fn,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{container_id:o}=n;return this._client.delete(Q`/containers/${o}/files/${e}`,{...r,headers:Fe([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};FI.Content=aN});var fC,Ape=C(()=>{Ge();Epe();Epe();Pn();Fo();Qt();fC=class extends le{constructor(){super(...arguments),this.files=new FI(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(Q`/containers/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/containers",Fn,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/containers/${e}`,{...n,headers:Fe([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};fC.Files=FI});var lN,kpe=C(()=>{Ge();Pn();Qt();lN=class extends le{create(e,n,r){let{include:o,...i}=n;return this._client.post(Q`/conversations/${e}/items`,{query:{include:o},body:i,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){let{conversation_id:o,...i}=n;return this._client.get(Q`/conversations/${o}/items/${e}`,{query:i,...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/conversations/${e}/items`,Xr,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{conversation_id:o}=n;return this._client.delete(Q`/conversations/${o}/items/${e}`,{...r,__security:{bearerAuth:!0}})}}});var pC,Mpe=C(()=>{Ge();kpe();kpe();Qt();pC=class extends le{constructor(){super(...arguments),this.items=new lN(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(Q`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(Q`/conversations/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}};pC.Items=lN});var UI,Npe=C(()=>{Ge();RU();UI=class extends le{create(e,n){let r=!!e.encoding_format,o=r?e.encoding_format:"base64";r&&os(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let i=this._client.post("/embeddings",{body:{...e,encoding_format:o},...n,__security:{bearerAuth:!0}});return r?i:(os(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(s=>(s&&s.data&&s.data.forEach(a=>{let l=a.embedding;a.embedding=DWe(l)}),s)))}}});var cN,Ope=C(()=>{Ge();Pn();Qt();cN=class extends le{retrieve(e,n,r){let{eval_id:o,run_id:i}=n;return this._client.get(Q`/evals/${o}/runs/${i}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n,r){let{eval_id:o,...i}=n;return this._client.getAPIList(Q`/evals/${o}/runs/${e}/output_items`,Fn,{query:i,...r,__security:{bearerAuth:!0}})}}});var BI,Rpe=C(()=>{Ge();Ope();Ope();Pn();Qt();BI=class extends le{constructor(){super(...arguments),this.outputItems=new cN(this._client)}create(e,n,r){return this._client.post(Q`/evals/${e}/runs`,{body:n,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){let{eval_id:o}=n;return this._client.get(Q`/evals/${o}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/evals/${e}/runs`,Fn,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{eval_id:o}=n;return this._client.delete(Q`/evals/${o}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,n,r){let{eval_id:o}=n;return this._client.post(Q`/evals/${o}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};BI.OutputItems=cN});var mC,Lpe=C(()=>{Ge();Rpe();Rpe();Pn();Qt();mC=class extends le{constructor(){super(...arguments),this.runs=new BI(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(Q`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(Q`/evals/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/evals",Fn,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}};mC.Runs=BI});var zI,Dpe=C(()=>{Ge();Pn();Fo();SM();Wm();mp();Qt();zI=class extends le{create(e,n){return this._client.post("/files",dc({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(Q`/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/files",Fn,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/files/${e}`,{...n,__security:{bearerAuth:!0}})}content(e,n){return this._client.get(Q`/files/${e}/content`,{...n,headers:Fe([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){let o=new Set(["processed","error","deleted"]),i=Date.now(),s=await this.retrieve(e);for(;!s.status||!o.has(s.status);)if(await Bg(n),s=await this.retrieve(e),Date.now()-i>r)throw new Fg({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return s}}});var uN,$pe=C(()=>{Ge();uN=class extends le{}});var dN,Fpe=C(()=>{Ge();dN=class extends le{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n,__security:{bearerAuth:!0}})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n,__security:{bearerAuth:!0}})}}});var jI,Upe=C(()=>{Ge();Fpe();Fpe();jI=class extends le{constructor(){super(...arguments),this.graders=new dN(this._client)}};jI.Graders=dN});var fN,Bpe=C(()=>{Ge();Pn();Qt();fN=class extends le{create(e,n,r){return this._client.getAPIList(Q`/fine_tuning/checkpoints/${e}/permissions`,uc,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(Q`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/fine_tuning/checkpoints/${e}/permissions`,Xr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){let{fine_tuned_model_checkpoint:o}=n;return this._client.delete(Q`/fine_tuning/checkpoints/${o}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}});var VI,zpe=C(()=>{Ge();Bpe();Bpe();VI=class extends le{constructor(){super(...arguments),this.permissions=new fN(this._client)}};VI.Permissions=fN});var pN,jpe=C(()=>{Ge();Pn();Qt();pN=class extends le{list(e,n={},r){return this._client.getAPIList(Q`/fine_tuning/jobs/${e}/checkpoints`,Fn,{query:n,...r,__security:{bearerAuth:!0}})}}});var WI,Vpe=C(()=>{Ge();jpe();jpe();Pn();Qt();WI=class extends le{constructor(){super(...arguments),this.checkpoints=new pN(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(Q`/fine_tuning/jobs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",Fn,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(Q`/fine_tuning/jobs/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}listEvents(e,n={},r){return this._client.getAPIList(Q`/fine_tuning/jobs/${e}/events`,Fn,{query:n,...r,__security:{bearerAuth:!0}})}pause(e,n){return this._client.post(Q`/fine_tuning/jobs/${e}/pause`,{...n,__security:{bearerAuth:!0}})}resume(e,n){return this._client.post(Q`/fine_tuning/jobs/${e}/resume`,{...n,__security:{bearerAuth:!0}})}};WI.Checkpoints=pN});var qm,Wpe=C(()=>{Ge();$pe();$pe();Upe();Upe();zpe();zpe();Vpe();Vpe();qm=class extends le{constructor(){super(...arguments),this.methods=new uN(this._client),this.jobs=new WI(this._client),this.checkpoints=new VI(this._client),this.alpha=new jI(this._client)}};qm.Methods=uN;qm.Jobs=WI;qm.Checkpoints=VI;qm.Alpha=jI});var mN,Hpe=C(()=>{Ge();mN=class extends le{}});var hC,Kpe=C(()=>{Ge();Hpe();Hpe();hC=class extends le{constructor(){super(...arguments),this.graderModels=new mN(this._client)}};hC.GraderModels=mN});var HI,qpe=C(()=>{Ge();mp();HI=class extends le{createVariation(e,n){return this._client.post("/images/variations",dc({body:e,...n,__security:{bearerAuth:!0}},this._client))}edit(e,n){return this._client.post("/images/edits",dc({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}}});var KI,Gpe=C(()=>{Ge();Pn();Qt();KI=class extends le{retrieve(e,n){return this._client.get(Q`/models/${e}`,{...n,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",uc,{...e,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/models/${e}`,{...n,__security:{bearerAuth:!0}})}}});var qI,Ype=C(()=>{Ge();qI=class extends le{create(e,n){return this._client.post("/moderations",{body:e,...n,__security:{bearerAuth:!0}})}}});var hN,Zpe=C(()=>{Ge();Fo();Qt();hN=class extends le{accept(e,n,r){return this._client.post(Q`/realtime/calls/${e}/accept`,{body:n,...r,headers:Fe([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,n){return this._client.post(Q`/realtime/calls/${e}/hangup`,{...n,headers:Fe([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}refer(e,n,r){return this._client.post(Q`/realtime/calls/${e}/refer`,{body:n,...r,headers:Fe([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,n={},r){return this._client.post(Q`/realtime/calls/${e}/reject`,{body:n,...r,headers:Fe([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}}});var gN,Jpe=C(()=>{Ge();gN=class extends le{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n,__security:{bearerAuth:!0}})}}});var qw,Xpe=C(()=>{Ge();Zpe();Zpe();Jpe();Jpe();qw=class extends le{constructor(){super(...arguments),this.clientSecrets=new gN(this._client),this.calls=new hN(this._client)}};qw.ClientSecrets=gN;qw.Calls=hN});function HWe(t,e){return!e||!P1t(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:Qpe(t,e)}function Qpe(t,e){let n=t.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:k1t(e,o)};if(o.type==="message"){let i=o.content.map(s=>s.type==="output_text"?{...s,parsed:I1t(e,s.text)}:s);return{...o,content:i}}return o}),r=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||Y5(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let o of r.output)if(o.type==="message"){for(let i of o.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),r}function I1t(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function P1t(t){return!!TU(t.text?.format)}function E1t(t){return t?.$brand==="auto-parseable-tool"}function A1t(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function k1t(t,e){let n=A1t(t.tools??[],e.name);return{...e,...e,parsed_arguments:E1t(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function Y5(t){let e=[];for(let n of t.output)if(n.type==="message")for(let r of n.content)r.type==="output_text"&&e.push(r.text);t.output_text=e.join("")}var Z5=C(()=>{Wm();AM()});function M1t(t,e){return HWe(t,e)}var yN,J5,gC,X5,KWe,qWe,GWe,YWe,Q5,ZWe=C(()=>{fp();Wm();U5();Z5();Q5=class t extends oC{constructor(e){super(),yN.add(this),J5.set(this,void 0),gC.set(this,void 0),X5.set(this,void 0),Zt(this,J5,e,"f")}static createResponse(e,n,r){let o=new t(n);return o._run(()=>o._createOrRetrieveResponse(e,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createOrRetrieveResponse(e,n,r){let o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),de(this,yN,"m",KWe).call(this);let i,s=null;"response_id"in n?(i=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),s=n.starting_after??null):i=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of i)de(this,yN,"m",qWe).call(this,a,s);if(i.controller.signal?.aborted)throw new zi;return de(this,yN,"m",GWe).call(this)}[(J5=new WeakMap,gC=new WeakMap,X5=new WeakMap,yN=new WeakSet,KWe=function(){this.ended||Zt(this,gC,void 0,"f")},qWe=function(n,r){if(this.ended)return;let o=(s,a)=>{(r==null||a.sequence_number>r)&&this._emit(s,a)},i=de(this,yN,"m",YWe).call(this,n);switch(o("event",n),n.type){case"response.output_text.delta":{let s=i.output[n.output_index];if(!s)throw new st(`missing output at index ${n.output_index}`);if(s.type==="message"){let a=s.content[n.content_index];if(!a)throw new st(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new st(`expected content to be 'output_text', got ${a.type}`);o("response.output_text.delta",{...n,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let s=i.output[n.output_index];if(!s)throw new st(`missing output at index ${n.output_index}`);s.type==="function_call"&&o("response.function_call_arguments.delta",{...n,snapshot:s.arguments});break}default:o(n.type,n);break}},GWe=function(){if(this.ended)throw new st("stream has ended, this shouldn't happen");let n=de(this,gC,"f");if(!n)throw new st("request ended without sending any events");Zt(this,gC,void 0,"f");let r=M1t(n,de(this,J5,"f"));return Zt(this,X5,r,"f"),r},YWe=function(n){let r=de(this,gC,"f");if(!r){if(n.type!=="response.created")throw new st(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=Zt(this,gC,n.response,"f"),r}switch(n.type){case"response.output_item.added":{r.output.push(n.item);break}case"response.content_part.added":{let o=r.output[n.output_index];if(!o)throw new st(`missing output at index ${n.output_index}`);let i=o.type,s=n.part;i==="message"&&s.type!=="reasoning_text"?o.content.push(s):i==="reasoning"&&s.type==="reasoning_text"&&(o.content||(o.content=[]),o.content.push(s));break}case"response.output_text.delta":{let o=r.output[n.output_index];if(!o)throw new st(`missing output at index ${n.output_index}`);if(o.type==="message"){let i=o.content[n.content_index];if(!i)throw new st(`missing content at index ${n.content_index}`);if(i.type!=="output_text")throw new st(`expected content to be 'output_text', got ${i.type}`);i.text+=n.delta}break}case"response.function_call_arguments.delta":{let o=r.output[n.output_index];if(!o)throw new st(`missing output at index ${n.output_index}`);o.type==="function_call"&&(o.arguments+=n.delta);break}case"response.reasoning_text.delta":{let o=r.output[n.output_index];if(!o)throw new st(`missing output at index ${n.output_index}`);if(o.type==="reasoning"){let i=o.content?.[n.content_index];if(!i)throw new st(`missing content at index ${n.content_index}`);if(i.type!=="reasoning_text")throw new st(`expected content to be 'reasoning_text', got ${i.type}`);i.text+=n.delta}break}case"response.completed":{Zt(this,gC,n.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("event",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=de(this,X5,"f");if(!e)throw new st("stream ended without producing a ChatCompletion");return e}}});var wN,eme=C(()=>{Ge();Pn();Qt();wN=class extends le{list(e,n={},r){return this._client.getAPIList(Q`/responses/${e}/input_items`,Fn,{query:n,...r,__security:{bearerAuth:!0}})}}});var vN,tme=C(()=>{Ge();vN=class extends le{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n,__security:{bearerAuth:!0}})}}});var Gw,nme=C(()=>{Z5();ZWe();Ge();eme();eme();tme();tme();Fo();Qt();Gw=class extends le{constructor(){super(...arguments),this.inputItems=new wN(this._client),this.inputTokens=new vN(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Y5(r),r))}retrieve(e,n={},r){return this._client.get(Q`/responses/${e}`,{query:n,...r,stream:n?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(o=>("object"in o&&o.object==="response"&&Y5(o),o))}delete(e,n){return this._client.delete(Q`/responses/${e}`,{...n,headers:Fe([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(r=>Qpe(r,e))}stream(e,n){return Q5.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(Q`/responses/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}compact(e,n){return this._client.post("/responses/compact",{body:e,...n,__security:{bearerAuth:!0}})}};Gw.InputItems=wN;Gw.InputTokens=vN});var xN,rme=C(()=>{Ge();Fo();Qt();xN=class extends le{retrieve(e,n){return this._client.get(Q`/skills/${e}/content`,{...n,headers:Fe([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}});var bN,ome=C(()=>{Ge();Fo();Qt();bN=class extends le{retrieve(e,n,r){let{skill_id:o}=n;return this._client.get(Q`/skills/${o}/versions/${e}/content`,{...r,headers:Fe([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}});var GI,ime=C(()=>{Ge();ome();ome();Pn();mp();Qt();GI=class extends le{constructor(){super(...arguments),this.content=new bN(this._client)}create(e,n={},r){return this._client.post(Q`/skills/${e}/versions`,rC({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){let{skill_id:o}=n;return this._client.get(Q`/skills/${o}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/skills/${e}/versions`,Fn,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){let{skill_id:o}=n;return this._client.delete(Q`/skills/${o}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};GI.Content=bN});var Yw,sme=C(()=>{Ge();rme();rme();ime();ime();Pn();mp();Qt();Yw=class extends le{constructor(){super(...arguments),this.content=new xN(this._client),this.versions=new GI(this._client)}create(e={},n){return this._client.post("/skills",rC({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(Q`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(Q`/skills/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/skills",Fn,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}};Yw.Content=xN;Yw.Versions=GI});var CN,ame=C(()=>{Ge();mp();Qt();CN=class extends le{create(e,n,r){return this._client.post(Q`/uploads/${e}/parts`,dc({body:n,...r,__security:{bearerAuth:!0}},this._client))}}});var yC,lme=C(()=>{Ge();ame();ame();Qt();yC=class extends le{constructor(){super(...arguments),this.parts=new CN(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(Q`/uploads/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}complete(e,n,r){return this._client.post(Q`/uploads/${e}/complete`,{body:n,...r,__security:{bearerAuth:!0}})}};yC.Parts=CN});var JWe,XWe=C(()=>{JWe=async t=>{let e=await Promise.allSettled(t),n=e.filter(o=>o.status==="rejected");if(n.length){for(let o of n)console.error(o.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let o of e)o.status==="fulfilled"&&r.push(o.value);return r}});var _N,cme=C(()=>{Ge();Pn();Fo();SM();XWe();Qt();_N=class extends le{create(e,n,r){return this._client.post(Q`/vector_stores/${e}/file_batches`,{body:n,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){let{vector_store_id:o}=n;return this._client.get(Q`/vector_stores/${o}/file_batches/${e}`,{...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){let{vector_store_id:o}=n;return this._client.post(Q`/vector_stores/${o}/file_batches/${e}/cancel`,{...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){let o=await this.create(e,n);return await this.poll(e,o.id,r)}listFiles(e,n,r){let{vector_store_id:o,...i}=n;return this._client.getAPIList(Q`/vector_stores/${o}/file_batches/${e}/files`,Fn,{query:i,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,n,r){let o=Fe([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:s}=await this.retrieve(n,{vector_store_id:e},{...r,headers:o}).withResponse();switch(i.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let l=s.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await Bg(a);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:n,fileIds:r=[]},o){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=o?.maxConcurrency??5,s=Math.min(i,n.length),a=this._client,l=n.values(),c=[...r];async function u(f){for(let p of f){let m=await a.files.create({file:p,purpose:"assistants"},o);c.push(m.id)}}let d=Array(s).fill(l).map(u);return await JWe(d),await this.createAndPoll(e,{file_ids:c})}}});var SN,ume=C(()=>{Ge();Pn();Fo();RU();Qt();SN=class extends le{create(e,n,r){return this._client.post(Q`/vector_stores/${e}/files`,{body:n,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){let{vector_store_id:o}=n;return this._client.get(Q`/vector_stores/${o}/files/${e}`,{...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){let{vector_store_id:o,...i}=n;return this._client.post(Q`/vector_stores/${o}/files/${e}`,{body:i,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(Q`/vector_stores/${e}/files`,Fn,{query:n,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){let{vector_store_id:o}=n;return this._client.delete(Q`/vector_stores/${o}/files/${e}`,{...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){let o=await this.create(e,n,r);return await this.poll(e,o.id,r)}async poll(e,n,r){let o=Fe([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(n,{vector_store_id:e},{...r,headers:o}).withResponse(),s=i.data;switch(s.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let l=i.response.headers.get("openai-poll-after-ms");if(l){let c=parseInt(l);isNaN(c)||(a=c)}}await Bg(a);break;case"failed":case"completed":return s}}}async upload(e,n,r){let o=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(e,{file_id:o.id},r)}async uploadAndPoll(e,n,r){let o=await this.upload(e,n,r);return await this.poll(e,o.id,r)}content(e,n,r){let{vector_store_id:o}=n;return this._client.getAPIList(Q`/vector_stores/${o}/files/${e}/content`,uc,{...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}}});var Zw,dme=C(()=>{Ge();cme();cme();ume();ume();Pn();Fo();Qt();Zw=class extends le{constructor(){super(...arguments),this.files=new SN(this._client),this.fileBatches=new _N(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(Q`/vector_stores/${e}`,{...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(Q`/vector_stores/${e}`,{body:n,...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/vector_stores",Fn,{query:e,...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/vector_stores/${e}`,{...n,headers:Fe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}search(e,n,r){return this._client.getAPIList(Q`/vector_stores/${e}/search`,uc,{body:n,method:"post",...r,headers:Fe([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};Zw.Files=SN;Zw.FileBatches=_N});var YI,fme=C(()=>{Ge();Pn();Fo();mp();Qt();YI=class extends le{create(e,n){return this._client.post("/videos",dc({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(Q`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/videos",Xr,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(Q`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}createCharacter(e,n){return this._client.post("/videos/characters",dc({body:e,...n,__security:{bearerAuth:!0}},this._client))}downloadContent(e,n={},r){return this._client.get(Q`/videos/${e}/content`,{query:n,...r,headers:Fe([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,n){return this._client.post("/videos/edits",dc({body:e,...n,__security:{bearerAuth:!0}},this._client))}extend(e,n){return this._client.post("/videos/extensions",dc({body:e,...n,__security:{bearerAuth:!0}},this._client))}getCharacter(e,n){return this._client.get(Q`/videos/characters/${e}`,{...n,__security:{bearerAuth:!0}})}remix(e,n,r){return this._client.post(Q`/videos/${e}/remix`,rC({body:n,...r,__security:{bearerAuth:!0}},this._client))}}});var TN,QWe,eq,ZI,pme=C(()=>{fp();Wm();Ge();Fo();ZI=class extends le{constructor(){super(...arguments),TN.add(this)}async unwrap(e,n,r=this._client.webhookSecret,o=300){return await this.verifySignature(e,n,r,o),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");de(this,TN,"m",QWe).call(this,r);let i=Fe([n]).values,s=de(this,TN,"m",eq).call(this,i,"webhook-signature"),a=de(this,TN,"m",eq).call(this,i,"webhook-timestamp"),l=de(this,TN,"m",eq).call(this,i,"webhook-id"),c=parseInt(a,10);if(isNaN(c))throw new Ug("Invalid webhook timestamp format");let u=Math.floor(Date.now()/1e3);if(u-c>o)throw new Ug("Webhook timestamp is too old");if(c>u+o)throw new Ug("Webhook timestamp is too new");let d=s.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),p=l?`${l}.${a}.${e}`:`${a}.${e}`,m=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of d)try{let g=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,g,new TextEncoder().encode(p)))return}catch{continue}throw new Ug("The given webhook signature does not match the expected signature")}};TN=new WeakSet,QWe=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},eq=function(e,n){if(!e)throw new Error("Headers are required");let r=e.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r}});var eHe=C(()=>{pme()});var tHe=C(()=>{eHe()});var nHe=C(()=>{OWe();RWe();ipe();cpe();upe();Tpe();Ipe();Ape();Mpe();Npe();Lpe();Dpe();Wpe();Kpe();qpe();Gpe();Ype();Xpe();nme();sme();lme();dme();fme();tHe()});var mme,hme,tq,rHe,z1t,en,nq=C(()=>{fp();jde();zw();SM();x5();Kde();TM();YVe();rfe();Hde();pp();Pn();pWe();pp();mfe();nHe();A5();upe();Ipe();Npe();Dpe();qpe();Gpe();Ype();fme();ipe();cpe();Tpe();Dfe();Ape();Mpe();Lpe();Wpe();Kpe();Xpe();nme();sme();lme();dme();pme();Kde();Fo();xpe();wU();zw();z1t="workload-identity-auth",en=class{constructor({baseURL:e=Xd("OPENAI_BASE_URL"),apiKey:n=Xd("OPENAI_API_KEY")??null,adminAPIKey:r=Xd("OPENAI_ADMIN_KEY")??null,organization:o=Xd("OPENAI_ORG_ID")??null,project:i=Xd("OPENAI_PROJECT_ID")??null,webhookSecret:s=Xd("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:a,...l}={}){mme.add(this),tq.set(this,void 0),this.completions=new $I(this),this.chat=new sC(this),this.embeddings=new UI(this),this.files=new zI(this),this.images=new HI(this),this.audio=new Vg(this),this.moderations=new qI(this),this.models=new KI(this),this.fineTuning=new qm(this),this.graders=new hC(this),this.vectorStores=new Zw(this),this.webhooks=new ZI(this),this.beta=new Km(this),this.batches=new NI(this),this.uploads=new yC(this),this.admin=new lC(this),this.responses=new Gw(this),this.realtime=new qw(this),this.conversations=new pC(this),this.evals=new mC(this),this.containers=new fC(this),this.skills=new Yw(this),this.videos=new YI(this);let c={apiKey:n,adminAPIKey:r,organization:o,project:i,webhookSecret:s,workloadIdentity:a,...l,baseURL:e||"https://api.openai.com/v1"};if(n&&a)throw new st("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!n&&!r&&!a)throw new st("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!c.dangerouslyAllowBrowser&&HVe())throw new st(`It looks like you're running in a browser-like environment.

This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,

new OpenAI({ apiKey, dangerouslyAllowBrowser: true });

https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);this.baseURL=c.baseURL,this.timeout=c.timeout??hme.DEFAULT_TIMEOUT,this.logger=c.logger??console;let u="warn";this.logLevel=u,this.logLevel=ife(c.logLevel,"ClientOptions.logLevel",this)??ife(Xd("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??C5(),Zt(this,tq,GVe,"f");let d=Xd("OPENAI_CUSTOM_HEADERS");if(d){let f={};for(let p of d.split(`
`)){let m=p.indexOf(":");m>=0&&(f[p.substring(0,m).trim()]=p.substring(m+1).trim())}c.defaultHeaders=Fe([f,c.defaultHeaders])}this._options=c,a&&(this._workloadIdentityAuth=new M5(a,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=r,this.organization=o,this.project=i,this.webhookSecret=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(n.has("authorization")||n.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,n={bearerAuth:!0,adminAPIKeyAuth:!0}){return Fe([n.bearerAuth?await this.bearerAuth(e):null,n.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return Fe([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return Fe([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return Fe([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return sWe(e)}getUserAgent(){return`${this.constructor.name}/JS ${nC}`}defaultIdempotencyKey(){return`stainless-node-retry-${zde()}`}makeStatusError(e,n,r,o){return Bi.generate(e,n,r,o)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(r){throw r instanceof st?r:new st(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new st(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,r){let o=!de(this,mme,"m",rHe).call(this)&&r||this.baseURL,i=FVe(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!Wde(s)||!Wde(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new TI(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n});await this.prepareRequest(s,{url:a,options:o});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(os(this).debug(`[${c}] sending request`,jw({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new zi;let f=o.__security??{bearerAuth:!0},p=new AbortController,m=await this.fetchWithAuth(a,s,l,p,f).catch(hU),h=Date.now();if(m instanceof globalThis.Error){let w=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new zi;let v=mU(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(n)return os(this).info(`[${c}] connection ${v?"timed out":"failed"} - ${w}`),os(this).debug(`[${c}] connection ${v?"timed out":"failed"} (${w})`,jw({retryOfRequestLogID:r,url:a,durationMs:h-d,message:m.message})),this.retryRequest(o,n,r??c);throw os(this).info(`[${c}] connection ${v?"timed out":"failed"} - error; no more retries left`),os(this).debug(`[${c}] connection ${v?"timed out":"failed"} (error; no more retries left)`,jw({retryOfRequestLogID:r,url:a,durationMs:h-d,message:m.message})),m instanceof _I||m instanceof gU?m:v?new Fg:new tC({cause:m})}let g=[...m.headers.entries()].filter(([w])=>w==="x-request-id").map(([w,v])=>", "+w+": "+JSON.stringify(v)).join(""),y=`[${c}${u}${g}] ${s.method} ${a} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${h-d}ms`;if(!m.ok){if(m.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!o.__metadata?.hasStreamingBody&&!o.__metadata?.workloadIdentityTokenRefreshed)return await Yde(m.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}},n,r??c);let w=await this.shouldRetry(m);if(n&&w){let S=`retrying, ${n} attempts remaining`;return await Yde(m.body),os(this).info(`${y} - ${S}`),os(this).debug(`[${c}] response error (${S})`,jw({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:h-d})),this.retryRequest(o,n,r??c,m.headers)}let v=w?"error; no more retries left":"error; not retryable";os(this).info(`${y} - ${v}`);let x=await m.text().catch(S=>hU(S).message),b=zVe(x),_=b?void 0:x;throw os(this).debug(`[${c}] response error (${v})`,jw({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:_,durationMs:Date.now()-d})),this.makeStatusError(m.status,b,_,m.headers)}return os(this).info(y),os(this).debug(`[${c}] response start`,jw({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:h-d})),{response:m,options:o,controller:p,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...r})}requestAPIList(e,n){let r=this.makeRequest(n,null,void 0);return new bU(this,r,e)}async fetchWithAuth(e,n,r,o,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let a=n.headers,l=a.get("Authorization");if(!l||l===`Bearer ${z1t}`){let c=await this._workloadIdentityAuth.getToken();a.set("Authorization",`Bearer ${c}`)}}return await this.fetchWithTimeout(e,n,r,o)}async fetchWithTimeout(e,n,r,o){let{signal:i,method:s,...a}=n||{},l=this._makeAbort(o);i&&i.addEventListener("abort",l,{once:!0});let c=setTimeout(l,r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(c)}}async shouldRetry(e){let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,o){let i,s=o?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(i=l)}let a=o?.get("retry-after");if(a&&!i){let l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(i===void 0){let l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await Bg(i),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){let i=n-e,s=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return s*a*1e3}async buildRequest(e,{retryCount:n=0}={}){let r={...e},{method:o,path:i,query:s,defaultBaseURL:a}=r,l=this.buildURL(i,s,a);"timeout"in r&&BVe("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:c,body:u,isStreamingBody:d}=this.buildBody({options:r});d&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:o,bodyHeaders:c,retryCount:n});return{req:{method:o,headers:f,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:o}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=Fe([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...KVe(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s,e.__security??{bearerAuth:!0}),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=Fe([n]),o=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,i=!o&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||o?{bodyHeaders:void 0,body:e,isStreamingBody:!i}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:_5(e),isStreamingBody:!0}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...de(this,tq,"f").call(this,{body:e,headers:r}),isStreamingBody:!1}}};hme=en,tq=new WeakMap,mme=new WeakSet,rHe=function(){return this.baseURL!=="https://api.openai.com/v1"};en.OpenAI=hme;en.DEFAULT_TIMEOUT=6e5;en.OpenAIError=st;en.APIError=Bi;en.APIConnectionError=tC;en.APIConnectionTimeoutError=Fg;en.APIUserAbortError=zi;en.NotFoundError=gM;en.ConflictError=yM;en.RateLimitError=vM;en.BadRequestError=pM;en.AuthenticationError=mM;en.InternalServerError=xM;en.PermissionDeniedError=hM;en.UnprocessableEntityError=wM;en.InvalidWebhookSignatureError=Ug;en.toFile=_U;en.Completions=$I;en.Chat=sC;en.Embeddings=UI;en.Files=zI;en.Images=HI;en.Audio=Vg;en.Moderations=qI;en.Models=KI;en.FineTuning=qm;en.Graders=hC;en.VectorStores=Zw;en.Webhooks=ZI;en.Beta=Km;en.Batches=NI;en.Uploads=yC;en.Admin=lC;en.Responses=Gw;en.Realtime=qw;en.Conversations=pC;en.Evals=mC;en.Containers=fC;en.Skills=Yw;en.Videos=YI});var JI,j1t,oHe=C(()=>{Fo();Wm();RU();nq();JI=class extends en{constructor({baseURL:e=Xd("OPENAI_BASE_URL"),apiKey:n=Xd("AZURE_OPENAI_API_KEY"),apiVersion:r=Xd("OPENAI_API_VERSION"),endpoint:o,deployment:i,azureADTokenProvider:s,dangerouslyAllowBrowser:a,...l}={}){if(!r)throw new st("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof s=="function"&&(a=!0),!s&&!n)throw new st("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(s&&n)throw new st("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(l.defaultQuery={...l.defaultQuery,"api-version":r},e){if(o)throw new st("baseURL and endpoint are mutually exclusive")}else{if(o||(o=process.env.AZURE_OPENAI_ENDPOINT),!o)throw new st("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${o}/openai`}super({apiKey:s??n,baseURL:e,...l,...a!==void 0?{dangerouslyAllowBrowser:a}:{}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=i}async buildRequest(e,n={}){if(j1t.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!_M(e.body))throw new Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;r!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${r}${e.path}`)}return super.buildRequest(e,n)}async authHeaders(e,n){let r=n??{bearerAuth:!0,adminAPIKeyAuth:!0};return r.bearerAuth&&typeof this._options.apiKey=="string"?Fe([{"api-key":this.apiKey}]):super.authHeaders(e,r)}},j1t=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"])});var Gm=C(()=>{nq();mfe();A5();nq();Pn();pp();oHe()});function hp(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===Fg.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===zi.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=pU(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=pU(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=pU(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=pU(t,"MODEL_NOT_FOUND"):e=t,e}var wC=C(()=>{$Ve();Gm()});function Xw(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function V1t(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function IN(t){let e=t.metadata?.filename??t.metadata?.name??t.metadata?.title;if(!e)throw new Error("a filename or name or title is needed via meta-data for OpenAI when working with multimodal blocks");return e}function Qw(t){let e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!rc.isInstance(t))throw new Error("Invalid generic chat message");return V1t(t);default:throw new Error(`Unknown message type: ${e}`)}}function iHe(t){return t.includes("gpt-5.2-pro")}var Jw,vC=C(()=>{Kr();Jw=t=>t()});function Hg(t){let{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:o,baseURL:i,azureADTokenProvider:s,azureOpenAIEndpoint:a}=t;if((r||s)&&o&&e)return`${o}/${e}`;if((r||s)&&a&&e)return`${a}/openai/deployments/${e}`;if(r||s){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return i}function gme(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function sHe(t){let e=Jw(()=>{if(gme(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&gme(t.values))return t.values;if(typeof t=="object"&&t!==null){let n=Object.entries(t).filter(([,r])=>typeof r=="string").map(([r,o])=>[r,o]);return new Headers(n)}return new Headers});return Object.fromEntries(e.entries())}function aHe(){let t=Hle();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function Kg(t,e=!1,n="1.0.0"){let r=sHe(t),o=aHe(),i=`langchainjs${e?"-azure":""}-openai`;return{...r,"User-Agent":r["User-Agent"]?`${i}/${n} (${o})${r["User-Agent"]}`:`${i}/${n} (${o})`}}var xC=C(()=>{vC();Jo()});function lHe(t,e){let n;return cp(t)?n=Gb(t):n=t,e?.strict!==void 0&&(n.function.strict=e.strict),n}function W1t(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function cHe(t){let e=["namespace functions {",""];for(let n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push(uHe(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
`)}function uHe(t,e){let n=[];for(let[r,o]of Object.entries(t.properties??{}))o.description&&e<2&&n.push(`// ${o.description}`),t.required?.includes(r)?n.push(`${r}: ${rq(o,e)},`):n.push(`${r}?: ${rq(o,e)},`);return n.map(r=>" ".repeat(e)+r).join(`
`)}function rq(t,e){if(W1t(t))return t.anyOf.map(n=>rq(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",uHe(t,e+2),"}"].join(`
`);case"array":return t.items?`${rq(t.items,e)}[]`:"any[]";default:return""}}function oq(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function PN(t){return"type"in t&&t.type!=="function"}function dHe(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function fHe(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function XI(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function iq(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function pHe(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function mHe(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function hHe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function gHe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isCustomTool"in t&&t.isCustomTool===!0}function yHe(t){let e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function wHe(t){let e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}var EN=C(()=>{pI();Bd();Bu()});var yme=C(()=>{Ql()});var uq={};zn(uq,{ZodISODate:()=>aq,ZodISODateTime:()=>sq,ZodISODuration:()=>cq,ZodISOTime:()=>lq,date:()=>vme,datetime:()=>wme,duration:()=>bme,time:()=>xme});function wme(t){return $se(sq,t)}function vme(t){return Fse(aq,t)}function xme(t){return Use(lq,t)}function bme(t){return Bse(cq,t)}var sq,aq,lq,cq,dq=C(()=>{Ql();fq();sq=ce("ZodISODateTime",(t,e)=>{Bie.init(t,e),Uo.init(t,e)});aq=ce("ZodISODate",(t,e)=>{zie.init(t,e),Uo.init(t,e)});lq=ce("ZodISOTime",(t,e)=>{jie.init(t,e),Uo.init(t,e)});cq=ce("ZodISODuration",(t,e)=>{Vie.init(t,e),Uo.init(t,e)})});var xHe,K1t,AN,Cme=C(()=>{Ql();Ql();xHe=(t,e)=>{DF.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>FF(t,n)},flatten:{value:n=>$F(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},K1t=ce("ZodError",xHe),AN=ce("ZodError",xHe,{Parent:Error})});var _me,Sme,Tme,Ime,Pme=C(()=>{Ql();Cme();_me=C6(AN),Sme=_6(AN),Tme=S6(AN),Ime=T6(AN)});function Eme(t){return Rse(UU,t)}function G1t(t){return B6(Mme,t)}function Y1t(t){return qF(pq,t)}function Z1t(t){return z6(ev,t)}function J1t(t){return j6(ev,t)}function X1t(t){return V6(ev,t)}function Q1t(t){return W6(ev,t)}function eDt(t){return H6(Nme,t)}function tDt(t){return K6(Ome,t)}function nDt(t){return q6(Rme,t)}function rDt(t){return G6(Lme,t)}function oDt(t){return Y6(Dme,t)}function iDt(t){return Z6($me,t)}function sDt(t){return J6(Fme,t)}function aDt(t){return X6(Ume,t)}function lDt(t){return Q6(Bme,t)}function cDt(t){return e3(zme,t)}function uDt(t){return t3(jme,t)}function dDt(t){return n3(Vme,t)}function fDt(t){return r3(Wme,t)}function pDt(t){return o3(Hme,t)}function mDt(t){return i3(Kme,t)}function hDt(t){return s3(qme,t)}function gDt(t,e,n={}){return wae(bHe,t,e,n)}function CHe(t){return zse(BU,t)}function Ame(t){return Vse(kN,t)}function yDt(t){return Wse(kN,t)}function wDt(t){return Hse(kN,t)}function vDt(t){return Kse(kN,t)}function xDt(t){return qse(kN,t)}function yq(t){return Gse(zU,t)}function bDt(t){return Zse(jU,t)}function CDt(t){return Xse(Gme,t)}function _Dt(t){return Qse(Gme,t)}function SDt(t){return eae(_He,t)}function TDt(t){return tae(SHe,t)}function IHe(t){return nae(THe,t)}function IDt(){return rae(PHe)}function QI(){return TT(EHe)}function wq(t){return GF(AHe,t)}function PDt(t){return oae(kHe,t)}function EDt(t){return iae(vq,t)}function MN(t,e){return a2(MHe,t,e)}function ADt(t){let e=t._zod.def.shape;return zHe(Object.keys(e))}function Yme(t,e){let n={type:"object",get shape(){return Qe.assignProp(this,"shape",{...t}),this.shape},...Qe.normalizeParams(e)};return new xq(n)}function kDt(t,e){return new xq({type:"object",get shape(){return Qe.assignProp(this,"shape",{...t}),this.shape},catchall:wq(),...Qe.normalizeParams(e)})}function MDt(t,e){return new xq({type:"object",get shape(){return Qe.assignProp(this,"shape",{...t}),this.shape},catchall:QI(),...Qe.normalizeParams(e)})}function bq(t,e){return new Zme({type:"union",options:t,...Qe.normalizeParams(e)})}function NDt(t,e,n){return new NHe({type:"union",options:e,discriminator:t,...Qe.normalizeParams(n)})}function RHe(t,e){return new OHe({type:"intersection",left:t,right:e})}function ODt(t,e,n){let r=e instanceof jn,o=r?n:e,i=r?e:null;return new LHe({type:"tuple",items:t,rest:i,...Qe.normalizeParams(o)})}function DHe(t,e,n){return new Jme({type:"record",keyType:t,valueType:e,...Qe.normalizeParams(n)})}function RDt(t,e,n){return new Jme({type:"record",keyType:bq([t,wq()]),valueType:e,...Qe.normalizeParams(n)})}function LDt(t,e,n){return new $He({type:"map",keyType:t,valueType:e,...Qe.normalizeParams(n)})}function DDt(t,e){return new FHe({type:"set",valueType:t,...Qe.normalizeParams(e)})}function UHe(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new FU({type:"enum",entries:n,...Qe.normalizeParams(e)})}function $Dt(t,e){return new FU({type:"enum",entries:t,...Qe.normalizeParams(e)})}function zHe(t,e){return new BHe({type:"literal",values:Array.isArray(t)?t:[t],...Qe.normalizeParams(e)})}function FDt(t){return mae(jHe,t)}function Qme(t){return new Xme({type:"transform",transform:t})}function mq(t){return new ehe({type:"optional",innerType:t})}function hq(t){return new VHe({type:"nullable",innerType:t})}function UDt(t){return mq(hq(t))}function HHe(t,e){return new WHe({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function qHe(t,e){return new KHe({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function GHe(t,e){return new the({type:"nonoptional",innerType:t,...Qe.normalizeParams(e)})}function BDt(t){return new YHe({type:"success",innerType:t})}function JHe(t,e){return new ZHe({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function zDt(t){return aae(XHe,t)}function gq(t,e){return new nhe({type:"pipe",in:t,out:e})}function e6e(t){return new QHe({type:"readonly",innerType:t})}function jDt(t,e){return new t6e({type:"template_literal",parts:t,...Qe.normalizeParams(e)})}function r6e(t){return new n6e({type:"lazy",getter:t})}function VDt(t){return new o6e({type:"promise",innerType:t})}function i6e(t){let e=new Ti({check:"custom"});return e._zod.check=t,e}function rhe(t,e){return hae(Cq,t??(()=>!0),e)}function s6e(t,e={}){return gae(Cq,t,e)}function a6e(t){let e=i6e(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Qe.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(Qe.issue(o))}},t(n.value,n)));return e}function WDt(t,e={error:`Input not instance of ${t.name}`}){let n=new Cq({type:"custom",check:"custom",fn:r=>r instanceof t,abort:!0,...Qe.normalizeParams(e)});return n._zod.bag.Class=t,n}function KDt(t){let e=r6e(()=>bq([Eme(t),CHe(),yq(),IHe(),MN(e),DHe(Eme(),e)]));return e}function qDt(t,e){return gq(Qme(t),e)}var pr,kme,UU,Uo,Mme,pq,ev,Nme,Ome,Rme,Lme,Dme,$me,Fme,Ume,Bme,zme,jme,Vme,Wme,Hme,Kme,qme,bHe,BU,kN,zU,jU,Gme,_He,SHe,THe,PHe,EHe,AHe,kHe,vq,MHe,xq,Zme,NHe,OHe,LHe,Jme,$He,FHe,FU,BHe,jHe,Xme,ehe,VHe,WHe,KHe,the,YHe,ZHe,XHe,nhe,QHe,t6e,n6e,o6e,Cq,HDt,fq=C(()=>{Ql();Ql();yme();dq();Pme();pr=ce("ZodType",(t,e)=>(jn.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>xs(t,n,r),t.brand=()=>t,t.register=(n,r)=>(n.add(t,r),t),t.parse=(n,r)=>_me(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Tme(t,n,r),t.parseAsync=async(n,r)=>Sme(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Ime(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(s6e(n,r)),t.superRefine=n=>t.check(a6e(n)),t.overwrite=n=>t.check(bw(n)),t.optional=()=>mq(t),t.nullable=()=>hq(t),t.nullish=()=>mq(hq(t)),t.nonoptional=n=>GHe(t,n),t.array=()=>MN(t),t.or=n=>bq([t,n]),t.and=n=>RHe(t,n),t.transform=n=>gq(t,Qme(n)),t.default=n=>HHe(t,n),t.prefault=n=>qHe(t,n),t.catch=n=>JHe(t,n),t.pipe=n=>gq(t,n),t.readonly=()=>e6e(t),t.describe=n=>{let r=t.clone();return Oa.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Oa.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Oa.get(t);let r=t.clone();return Oa.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),kme=ce("_ZodString",(t,e)=>{CT.init(t,e),pr.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(ZF(...r)),t.includes=(...r)=>t.check(QF(...r)),t.startsWith=(...r)=>t.check(e2(...r)),t.endsWith=(...r)=>t.check(t2(...r)),t.min=(...r)=>t.check(Ib(...r)),t.max=(...r)=>t.check(kk(...r)),t.length=(...r)=>t.check(Mk(...r)),t.nonempty=(...r)=>t.check(Ib(1,...r)),t.lowercase=r=>t.check(JF(r)),t.uppercase=r=>t.check(XF(r)),t.trim=()=>t.check(o2()),t.normalize=(...r)=>t.check(r2(...r)),t.toLowerCase=()=>t.check(i2()),t.toUpperCase=()=>t.check(s2())}),UU=ce("ZodString",(t,e)=>{CT.init(t,e),kme.init(t,e),t.email=n=>t.check(B6(Mme,n)),t.url=n=>t.check(H6(Nme,n)),t.jwt=n=>t.check(s3(qme,n)),t.emoji=n=>t.check(K6(Ome,n)),t.guid=n=>t.check(qF(pq,n)),t.uuid=n=>t.check(z6(ev,n)),t.uuidv4=n=>t.check(j6(ev,n)),t.uuidv6=n=>t.check(V6(ev,n)),t.uuidv7=n=>t.check(W6(ev,n)),t.nanoid=n=>t.check(q6(Rme,n)),t.guid=n=>t.check(qF(pq,n)),t.cuid=n=>t.check(G6(Lme,n)),t.cuid2=n=>t.check(Y6(Dme,n)),t.ulid=n=>t.check(Z6($me,n)),t.base64=n=>t.check(r3(Wme,n)),t.base64url=n=>t.check(o3(Hme,n)),t.xid=n=>t.check(J6(Fme,n)),t.ksuid=n=>t.check(X6(Ume,n)),t.ipv4=n=>t.check(Q6(Bme,n)),t.ipv6=n=>t.check(e3(zme,n)),t.cidrv4=n=>t.check(t3(jme,n)),t.cidrv6=n=>t.check(n3(Vme,n)),t.e164=n=>t.check(i3(Kme,n)),t.datetime=n=>t.check(wme(n)),t.date=n=>t.check(vme(n)),t.time=n=>t.check(xme(n)),t.duration=n=>t.check(bme(n))});Uo=ce("ZodStringFormat",(t,e)=>{_o.init(t,e),kme.init(t,e)}),Mme=ce("ZodEmail",(t,e)=>{Mie.init(t,e),Uo.init(t,e)});pq=ce("ZodGUID",(t,e)=>{Aie.init(t,e),Uo.init(t,e)});ev=ce("ZodUUID",(t,e)=>{kie.init(t,e),Uo.init(t,e)});Nme=ce("ZodURL",(t,e)=>{Nie.init(t,e),Uo.init(t,e)});Ome=ce("ZodEmoji",(t,e)=>{Oie.init(t,e),Uo.init(t,e)});Rme=ce("ZodNanoID",(t,e)=>{Rie.init(t,e),Uo.init(t,e)});Lme=ce("ZodCUID",(t,e)=>{Lie.init(t,e),Uo.init(t,e)});Dme=ce("ZodCUID2",(t,e)=>{Die.init(t,e),Uo.init(t,e)});$me=ce("ZodULID",(t,e)=>{$ie.init(t,e),Uo.init(t,e)});Fme=ce("ZodXID",(t,e)=>{Fie.init(t,e),Uo.init(t,e)});Ume=ce("ZodKSUID",(t,e)=>{Uie.init(t,e),Uo.init(t,e)});Bme=ce("ZodIPv4",(t,e)=>{Wie.init(t,e),Uo.init(t,e)});zme=ce("ZodIPv6",(t,e)=>{Hie.init(t,e),Uo.init(t,e)});jme=ce("ZodCIDRv4",(t,e)=>{Kie.init(t,e),Uo.init(t,e)});Vme=ce("ZodCIDRv6",(t,e)=>{qie.init(t,e),Uo.init(t,e)});Wme=ce("ZodBase64",(t,e)=>{Yie.init(t,e),Uo.init(t,e)});Hme=ce("ZodBase64URL",(t,e)=>{Zie.init(t,e),Uo.init(t,e)});Kme=ce("ZodE164",(t,e)=>{Jie.init(t,e),Uo.init(t,e)});qme=ce("ZodJWT",(t,e)=>{Xie.init(t,e),Uo.init(t,e)});bHe=ce("ZodCustomStringFormat",(t,e)=>{Qie.init(t,e),Uo.init(t,e)});BU=ce("ZodNumber",(t,e)=>{R6.init(t,e),pr.init(t,e),t.gt=(r,o)=>t.check(xw(r,o)),t.gte=(r,o)=>t.check(Du(r,o)),t.min=(r,o)=>t.check(Du(r,o)),t.lt=(r,o)=>t.check(vw(r,o)),t.lte=(r,o)=>t.check(Yf(r,o)),t.max=(r,o)=>t.check(Yf(r,o)),t.int=r=>t.check(Ame(r)),t.safe=r=>t.check(Ame(r)),t.positive=r=>t.check(xw(0,r)),t.nonnegative=r=>t.check(Du(0,r)),t.negative=r=>t.check(vw(0,r)),t.nonpositive=r=>t.check(Yf(0,r)),t.multipleOf=(r,o)=>t.check(IT(r,o)),t.step=(r,o)=>t.check(IT(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});kN=ce("ZodNumberFormat",(t,e)=>{ese.init(t,e),BU.init(t,e)});zU=ce("ZodBoolean",(t,e)=>{BF.init(t,e),pr.init(t,e)});jU=ce("ZodBigInt",(t,e)=>{L6.init(t,e),pr.init(t,e),t.gte=(r,o)=>t.check(Du(r,o)),t.min=(r,o)=>t.check(Du(r,o)),t.gt=(r,o)=>t.check(xw(r,o)),t.gte=(r,o)=>t.check(Du(r,o)),t.min=(r,o)=>t.check(Du(r,o)),t.lt=(r,o)=>t.check(vw(r,o)),t.lte=(r,o)=>t.check(Yf(r,o)),t.max=(r,o)=>t.check(Yf(r,o)),t.positive=r=>t.check(xw(BigInt(0),r)),t.negative=r=>t.check(vw(BigInt(0),r)),t.nonpositive=r=>t.check(Yf(BigInt(0),r)),t.nonnegative=r=>t.check(Du(BigInt(0),r)),t.multipleOf=(r,o)=>t.check(IT(r,o));let n=t._zod.bag;t.minValue=n.minimum??null,t.maxValue=n.maximum??null,t.format=n.format??null});Gme=ce("ZodBigIntFormat",(t,e)=>{tse.init(t,e),jU.init(t,e)});_He=ce("ZodSymbol",(t,e)=>{nse.init(t,e),pr.init(t,e)});SHe=ce("ZodUndefined",(t,e)=>{rse.init(t,e),pr.init(t,e)});THe=ce("ZodNull",(t,e)=>{ose.init(t,e),pr.init(t,e)});PHe=ce("ZodAny",(t,e)=>{ise.init(t,e),pr.init(t,e)});EHe=ce("ZodUnknown",(t,e)=>{_T.init(t,e),pr.init(t,e)});AHe=ce("ZodNever",(t,e)=>{zF.init(t,e),pr.init(t,e)});kHe=ce("ZodVoid",(t,e)=>{sse.init(t,e),pr.init(t,e)});vq=ce("ZodDate",(t,e)=>{ase.init(t,e),pr.init(t,e),t.min=(r,o)=>t.check(Du(r,o)),t.max=(r,o)=>t.check(Yf(r,o));let n=t._zod.bag;t.minDate=n.minimum?new Date(n.minimum):null,t.maxDate=n.maximum?new Date(n.maximum):null});MHe=ce("ZodArray",(t,e)=>{jF.init(t,e),pr.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Ib(n,r)),t.nonempty=n=>t.check(Ib(1,n)),t.max=(n,r)=>t.check(kk(n,r)),t.length=(n,r)=>t.check(Mk(n,r)),t.unwrap=()=>t.element});xq=ce("ZodObject",(t,e)=>{lse.init(t,e),pr.init(t,e),Qe.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>UHe(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:QI()}),t.loose=()=>t.clone({...t._zod.def,catchall:QI()}),t.strict=()=>t.clone({...t._zod.def,catchall:wq()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>Qe.extend(t,n),t.merge=n=>Qe.merge(t,n),t.pick=n=>Qe.pick(t,n),t.omit=n=>Qe.omit(t,n),t.partial=(...n)=>Qe.partial(ehe,t,n[0]),t.required=(...n)=>Qe.required(the,t,n[0])});Zme=ce("ZodUnion",(t,e)=>{D6.init(t,e),pr.init(t,e),t.options=e.options});NHe=ce("ZodDiscriminatedUnion",(t,e)=>{Zme.init(t,e),cse.init(t,e)});OHe=ce("ZodIntersection",(t,e)=>{use.init(t,e),pr.init(t,e)});LHe=ce("ZodTuple",(t,e)=>{ST.init(t,e),pr.init(t,e),t.rest=n=>t.clone({...t._zod.def,rest:n})});Jme=ce("ZodRecord",(t,e)=>{dse.init(t,e),pr.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});$He=ce("ZodMap",(t,e)=>{fse.init(t,e),pr.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});FHe=ce("ZodSet",(t,e)=>{pse.init(t,e),pr.init(t,e),t.min=(...n)=>t.check(PT(...n)),t.nonempty=n=>t.check(PT(1,n)),t.max=(...n)=>t.check(Ak(...n)),t.size=(...n)=>t.check(YF(...n))});FU=ce("ZodEnum",(t,e)=>{mse.init(t,e),pr.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let i={};for(let s of r)if(n.has(s))i[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new FU({...e,checks:[],...Qe.normalizeParams(o),entries:i})},t.exclude=(r,o)=>{let i={...e.entries};for(let s of r)if(n.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new FU({...e,checks:[],...Qe.normalizeParams(o),entries:i})}});BHe=ce("ZodLiteral",(t,e)=>{hse.init(t,e),pr.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});jHe=ce("ZodFile",(t,e)=>{gse.init(t,e),pr.init(t,e),t.min=(n,r)=>t.check(PT(n,r)),t.max=(n,r)=>t.check(Ak(n,r)),t.mime=(n,r)=>t.check(n2(Array.isArray(n)?n:[n],r))});Xme=ce("ZodTransform",(t,e)=>{VF.init(t,e),pr.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=i=>{if(typeof i=="string")n.issues.push(Qe.issue(i,n.value,e));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=n.value),s.inst??(s.inst=t),s.continue??(s.continue=!0),n.issues.push(Qe.issue(s))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(i=>(n.value=i,n)):(n.value=o,n)}});ehe=ce("ZodOptional",(t,e)=>{$6.init(t,e),pr.init(t,e),t.unwrap=()=>t._zod.def.innerType});VHe=ce("ZodNullable",(t,e)=>{yse.init(t,e),pr.init(t,e),t.unwrap=()=>t._zod.def.innerType});WHe=ce("ZodDefault",(t,e)=>{wse.init(t,e),pr.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});KHe=ce("ZodPrefault",(t,e)=>{vse.init(t,e),pr.init(t,e),t.unwrap=()=>t._zod.def.innerType});the=ce("ZodNonOptional",(t,e)=>{xse.init(t,e),pr.init(t,e),t.unwrap=()=>t._zod.def.innerType});YHe=ce("ZodSuccess",(t,e)=>{bse.init(t,e),pr.init(t,e),t.unwrap=()=>t._zod.def.innerType});ZHe=ce("ZodCatch",(t,e)=>{Cse.init(t,e),pr.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});XHe=ce("ZodNaN",(t,e)=>{_se.init(t,e),pr.init(t,e)});nhe=ce("ZodPipe",(t,e)=>{WF.init(t,e),pr.init(t,e),t.in=e.in,t.out=e.out});QHe=ce("ZodReadonly",(t,e)=>{Sse.init(t,e),pr.init(t,e)});t6e=ce("ZodTemplateLiteral",(t,e)=>{Tse.init(t,e),pr.init(t,e)});n6e=ce("ZodLazy",(t,e)=>{Pse.init(t,e),pr.init(t,e),t.unwrap=()=>t._zod.def.getter()});o6e=ce("ZodPromise",(t,e)=>{Ise.init(t,e),pr.init(t,e),t.unwrap=()=>t._zod.def.innerType});Cq=ce("ZodCustom",(t,e)=>{Ese.init(t,e),pr.init(t,e)});HDt=(...t)=>yae({Pipe:nhe,Boolean:zU,String:UU,Transform:Xme},...t)});function YDt(t){vs({customError:t})}function ZDt(){return vs().customError}var GDt,l6e=C(()=>{Ql();GDt={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"}});var ohe={};zn(ohe,{bigint:()=>e$t,boolean:()=>QDt,date:()=>t$t,number:()=>XDt,string:()=>JDt});function JDt(t){return Lse(UU,t)}function XDt(t){return jse(BU,t)}function QDt(t){return Yse(zU,t)}function e$t(t){return Jse(jU,t)}function t$t(t){return sae(vq,t)}var c6e=C(()=>{Ql();fq()});var se={};zn(se,{$brand:()=>hoe,$input:()=>Nse,$output:()=>Mse,NEVER:()=>moe,TimePrecision:()=>Dse,ZodAny:()=>PHe,ZodArray:()=>MHe,ZodBase64:()=>Wme,ZodBase64URL:()=>Hme,ZodBigInt:()=>jU,ZodBigIntFormat:()=>Gme,ZodBoolean:()=>zU,ZodCIDRv4:()=>jme,ZodCIDRv6:()=>Vme,ZodCUID:()=>Lme,ZodCUID2:()=>Dme,ZodCatch:()=>ZHe,ZodCustom:()=>Cq,ZodCustomStringFormat:()=>bHe,ZodDate:()=>vq,ZodDefault:()=>WHe,ZodDiscriminatedUnion:()=>NHe,ZodE164:()=>Kme,ZodEmail:()=>Mme,ZodEmoji:()=>Ome,ZodEnum:()=>FU,ZodError:()=>K1t,ZodFile:()=>jHe,ZodGUID:()=>pq,ZodIPv4:()=>Bme,ZodIPv6:()=>zme,ZodISODate:()=>aq,ZodISODateTime:()=>sq,ZodISODuration:()=>cq,ZodISOTime:()=>lq,ZodIntersection:()=>OHe,ZodIssueCode:()=>GDt,ZodJWT:()=>qme,ZodKSUID:()=>Ume,ZodLazy:()=>n6e,ZodLiteral:()=>BHe,ZodMap:()=>$He,ZodNaN:()=>XHe,ZodNanoID:()=>Rme,ZodNever:()=>AHe,ZodNonOptional:()=>the,ZodNull:()=>THe,ZodNullable:()=>VHe,ZodNumber:()=>BU,ZodNumberFormat:()=>kN,ZodObject:()=>xq,ZodOptional:()=>ehe,ZodPipe:()=>nhe,ZodPrefault:()=>KHe,ZodPromise:()=>o6e,ZodReadonly:()=>QHe,ZodRealError:()=>AN,ZodRecord:()=>Jme,ZodSet:()=>FHe,ZodString:()=>UU,ZodStringFormat:()=>Uo,ZodSuccess:()=>YHe,ZodSymbol:()=>_He,ZodTemplateLiteral:()=>t6e,ZodTransform:()=>Xme,ZodTuple:()=>LHe,ZodType:()=>pr,ZodULID:()=>$me,ZodURL:()=>Nme,ZodUUID:()=>ev,ZodUndefined:()=>SHe,ZodUnion:()=>Zme,ZodUnknown:()=>EHe,ZodVoid:()=>kHe,ZodXID:()=>Fme,_ZodString:()=>kme,_default:()=>HHe,any:()=>IDt,array:()=>MN,base64:()=>fDt,base64url:()=>pDt,bigint:()=>bDt,boolean:()=>yq,catch:()=>JHe,check:()=>i6e,cidrv4:()=>uDt,cidrv6:()=>dDt,clone:()=>xs,coerce:()=>ohe,config:()=>vs,core:()=>Cw,cuid:()=>rDt,cuid2:()=>oDt,custom:()=>rhe,date:()=>EDt,discriminatedUnion:()=>NDt,e164:()=>mDt,email:()=>G1t,emoji:()=>tDt,endsWith:()=>t2,enum:()=>UHe,file:()=>FDt,flattenError:()=>$F,float32:()=>yDt,float64:()=>wDt,formatError:()=>FF,function:()=>xae,getErrorMap:()=>ZDt,globalRegistry:()=>Oa,gt:()=>xw,gte:()=>Du,guid:()=>Y1t,includes:()=>QF,instanceof:()=>WDt,int:()=>Ame,int32:()=>vDt,int64:()=>CDt,intersection:()=>RHe,ipv4:()=>lDt,ipv6:()=>cDt,iso:()=>uq,json:()=>KDt,jwt:()=>hDt,keyof:()=>ADt,ksuid:()=>aDt,lazy:()=>r6e,length:()=>Mk,literal:()=>zHe,locales:()=>KF,looseObject:()=>MDt,lowercase:()=>JF,lt:()=>vw,lte:()=>Yf,map:()=>LDt,maxLength:()=>kk,maxSize:()=>Ak,mime:()=>n2,minLength:()=>Ib,minSize:()=>PT,multipleOf:()=>IT,nan:()=>zDt,nanoid:()=>nDt,nativeEnum:()=>$Dt,negative:()=>cae,never:()=>wq,nonnegative:()=>dae,nonoptional:()=>GHe,nonpositive:()=>uae,normalize:()=>r2,null:()=>IHe,nullable:()=>hq,nullish:()=>UDt,number:()=>CHe,object:()=>Yme,optional:()=>mq,overwrite:()=>bw,parse:()=>_me,parseAsync:()=>Sme,partialRecord:()=>RDt,pipe:()=>gq,positive:()=>lae,prefault:()=>qHe,preprocess:()=>qDt,prettifyError:()=>Eoe,promise:()=>VDt,property:()=>fae,readonly:()=>e6e,record:()=>DHe,refine:()=>s6e,regex:()=>ZF,regexes:()=>bT,registry:()=>U6,safeParse:()=>Tme,safeParseAsync:()=>Ime,set:()=>DDt,setErrorMap:()=>YDt,size:()=>YF,startsWith:()=>e2,strictObject:()=>kDt,string:()=>Eme,stringFormat:()=>gDt,stringbool:()=>HDt,success:()=>BDt,superRefine:()=>a6e,symbol:()=>SDt,templateLiteral:()=>jDt,toJSONSchema:()=>Pb,toLowerCase:()=>i2,toUpperCase:()=>s2,transform:()=>Qme,treeifyError:()=>Poe,trim:()=>o2,tuple:()=>ODt,uint32:()=>xDt,uint64:()=>_Dt,ulid:()=>iDt,undefined:()=>TDt,union:()=>bq,unknown:()=>QI,uppercase:()=>XF,url:()=>eDt,uuid:()=>Z1t,uuidv4:()=>J1t,uuidv6:()=>X1t,uuidv7:()=>Q1t,void:()=>PDt,xid:()=>sDt});var ihe=C(()=>{Ql();fq();yme();Cme();Pme();l6e();Ql();Ase();Ql();kse();dq();dq();c6e();vs(F6())});var u6e=C(()=>{ihe();ihe()});var tv=C(()=>{u6e()});var p6e,f6e,m6e,_q=C(()=>{p6e=Symbol("Let zodToJsonSchema decide on which parser to use"),f6e={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},m6e=t=>typeof t=="string"?{...f6e,basePath:["#"],definitions:{},name:t}:{...f6e,basePath:["#"],definitions:{},...t}});function h6e(t){if(!t)return!0;for(let e in t)return!1;return!0}var VU,she=C(()=>{VU=t=>"_def"in t?t._def:t});var g6e,ahe=C(()=>{_q();she();g6e=t=>{let e=m6e(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[VU(o),{def:VU(o),path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function lhe(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function Ar(t,e,n,r,o){t[e]=n,lhe(t,e,r,o)}var bC=C(()=>{});function y6e(){return{}}var che=C(()=>{});function w6e(t,e){let n={type:"array"};return t.type?._def?.typeName!==he.ZodAny&&(n.items=_n(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Ar(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Ar(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Ar(n,"minItems",t.exactLength.value,t.exactLength.message,e),Ar(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var uhe=C(()=>{_g();bC();_s()});function v6e(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?Ar(n,"minimum",r.value,r.message,e):Ar(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Ar(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Ar(n,"maximum",r.value,r.message,e):Ar(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Ar(n,"maximum",r.value,r.message,e));break;case"multipleOf":Ar(n,"multipleOf",r.value,r.message,e);break}return n}var dhe=C(()=>{bC()});function x6e(){return{type:"boolean"}}var fhe=C(()=>{});function b6e(t,e){return _n(t.type._def,e)}var phe=C(()=>{_s()});var C6e,mhe=C(()=>{_s();C6e=(t,e)=>_n(t.innerType._def,e)});function hhe(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,i)=>hhe(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return n$t(t,e)}}var n$t,ghe=C(()=>{bC();n$t=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":Ar(n,"minimum",r.value,r.message,e);break;case"max":Ar(n,"maximum",r.value,r.message,e);break}return n}});function _6e(t,e){return{..._n(t.innerType._def,e),default:t.defaultValue()}}var yhe=C(()=>{_s()});function S6e(t,e,n){return e.effectStrategy==="input"?_n(t.schema._def,e,n):{}}var whe=C(()=>{_s()});function T6e(t){return{type:"string",enum:[...t.values]}}var vhe=C(()=>{});function I6e(t,e){let n=[_n(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),_n(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(i=>!!i),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(i=>{if(r$t(i))o.push(...i.allOf),i.unevaluatedProperties===void 0&&(r=void 0);else{let s=i;if("additionalProperties"in i&&i.additionalProperties===!1){let{additionalProperties:a,...l}=i;s=l}else r=void 0;o.push(s)}}),o.length?{allOf:o,...r}:void 0}var r$t,xhe=C(()=>{_s();r$t=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function P6e(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var bhe=C(()=>{});function Sq(t,e){let n={type:"string"};function r(o){return e.patternStrategy==="escape"?o$t(o):o}if(t.checks)for(let o of t.checks)switch(o.kind){case"min":Ar(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,o.value):o.value,o.message,e);break;case"max":Ar(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,o.value):o.value,o.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ym(n,"email",o.message,e);break;case"format:idn-email":Ym(n,"idn-email",o.message,e);break;case"pattern:zod":Zm(n,e0.email,o.message,e);break}break;case"url":Ym(n,"uri",o.message,e);break;case"uuid":Ym(n,"uuid",o.message,e);break;case"regex":Zm(n,o.regex,o.message,e);break;case"cuid":Zm(n,e0.cuid,o.message,e);break;case"cuid2":Zm(n,e0.cuid2,o.message,e);break;case"startsWith":Zm(n,RegExp(`^${r(o.value)}`),o.message,e);break;case"endsWith":Zm(n,RegExp(`${r(o.value)}$`),o.message,e);break;case"datetime":Ym(n,"date-time",o.message,e);break;case"date":Ym(n,"date",o.message,e);break;case"time":Ym(n,"time",o.message,e);break;case"duration":Ym(n,"duration",o.message,e);break;case"length":Ar(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,o.value):o.value,o.message,e),Ar(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,o.value):o.value,o.message,e);break;case"includes":{Zm(n,RegExp(r(o.value)),o.message,e);break}case"ip":{o.version!=="v6"&&Ym(n,"ipv4",o.message,e),o.version!=="v4"&&Ym(n,"ipv6",o.message,e);break}case"emoji":Zm(n,e0.emoji,o.message,e);break;case"ulid":{Zm(n,e0.ulid,o.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ym(n,"binary",o.message,e);break}case"contentEncoding:base64":{Ar(n,"contentEncoding","base64",o.message,e);break}case"pattern:zod":{Zm(n,e0.base64,o.message,e);break}}break}case"nanoid":Zm(n,e0.nanoid,o.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}var Che,e0,o$t,Ym,Zm,E6e,Tq=C(()=>{bC();e0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Che===void 0&&(Che=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Che),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};o$t=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ym=(t,e,n,r)=>{t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Ar(t,"format",e,n,r)},Zm=(t,e,n,r)=>{t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:E6e(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Ar(t,"pattern",E6e(e,r),n,r)},E6e=(t,e)=>{let n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;let r={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},o=r.i?n.source.toLowerCase():n.source,i="",s=!1,a=!1,l=!1;for(let c=0;c<o.length;c++){if(s){i+=o[c],s=!1;continue}if(r.i){if(a){if(o[c].match(/[a-z]/)){l?(i+=o[c],i+=`${o[c-2]}-${o[c]}`.toUpperCase(),l=!1):o[c+1]==="-"&&o[c+2]?.match(/[a-z]/)?(i+=o[c],l=!0):i+=`${o[c]}${o[c].toUpperCase()}`;continue}}else if(o[c].match(/[a-z]/)){i+=`[${o[c]}${o[c].toUpperCase()}]`;continue}}if(r.m){if(o[c]==="^"){i+=`(^|(?<=[\r
]))`;continue}else if(o[c]==="$"){i+=`($|(?=[\r
]))`;continue}}if(r.s&&o[c]==="."){i+=a?`${o[c]}\r
`:`[${o[c]}\r
]`;continue}i+=o[c],o[c]==="\\"?s=!0:a&&o[c]==="]"?a=!1:!a&&o[c]==="["&&(a=!0)}try{let c=new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return i}});function Iq(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===he.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,o)=>({...r,[o]:_n(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??{}}),{}),additionalProperties:!1};let n={type:"object",additionalProperties:_n(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===he.ZodString&&t.keyType._def.checks?.length){let r=Object.entries(Sq(t.keyType._def,e)).reduce((o,[i,s])=>i==="type"?o:{...o,[i]:s},{});return{...n,propertyNames:r}}else if(t.keyType?._def.typeName===he.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}var Pq=C(()=>{_g();_s();Tq()});function A6e(t,e){if(e.mapStrategy==="record")return Iq(t,e);let n=_n(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=_n(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var _he=C(()=>{_s();Pq()});function k6e(t){let e=t.values,r=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),o=Array.from(new Set(r.map(i=>typeof i)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}var She=C(()=>{});function M6e(){return{not:{}}}var The=C(()=>{});function N6e(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ihe=C(()=>{});function R6e(t,e){if(e.target==="openApi3")return O6e(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in WU&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,i)=>{let s=WU[i._def.typeName];return s&&!o.includes(s)?[...o,s]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((o,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...o,s];case"bigint":return[...o,"integer"];case"object":if(i._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(r.length===n.length){let o=r.filter((i,s,a)=>a.indexOf(i)===s);return{type:o.length>1?o:o[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(i=>!r.includes(i))],[])};return O6e(t,e)}var WU,O6e,Eq=C(()=>{_s();WU={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};O6e=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>_n(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function L6e(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:WU[t.innerType._def.typeName],nullable:!0}:{type:[WU[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=_n(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=_n(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Phe=C(()=>{_s();Eq()});function D6e(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",lhe(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?Ar(n,"minimum",r.value,r.message,e):Ar(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Ar(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Ar(n,"maximum",r.value,r.message,e):Ar(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Ar(n,"maximum",r.value,r.message,e));break;case"multipleOf":Ar(n,"multipleOf",r.value,r.message,e);break}return n}var Ehe=C(()=>{bC()});function i$t(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":_n(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":_n(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function $6e(t,e){let n={type:"object",...Object.entries(t.shape()).reduce((r,[o,i])=>{if(i===void 0||i._def===void 0)return r;let s=[...e.currentPath,"properties",o],a=_n(i._def,{...e,currentPath:s,propertyPath:s});if(a===void 0)return r;if(e.openaiStrictMode&&i.isOptional()&&!i.isNullable()&&typeof i._def?.defaultValue>"u")throw new Error(`Zod field at \`${s.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...r.properties,[o]:a},required:i.isOptional()&&!e.openaiStrictMode?r.required:[...r.required,o]}},{properties:{},required:[]}),additionalProperties:i$t(t,e)};return n.required.length||delete n.required,n}var Ahe=C(()=>{_s()});var F6e,khe=C(()=>{_s();F6e=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return _n(t.innerType._def,{...e,currentPath:e.currentPath});let n=_n(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}}});var U6e,Mhe=C(()=>{_s();U6e=(t,e)=>{if(e.pipeStrategy==="input")return _n(t.in._def,e);if(e.pipeStrategy==="output")return _n(t.out._def,e);let n=_n(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=_n(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}}});function B6e(t,e){return _n(t.type._def,e)}var Nhe=C(()=>{_s()});function z6e(t,e){let r={type:"array",uniqueItems:!0,items:_n(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Ar(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Ar(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var Ohe=C(()=>{bC();_s()});function j6e(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>_n(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:_n(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>_n(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var Rhe=C(()=>{_s()});function V6e(){return{not:{}}}var Lhe=C(()=>{});function W6e(){return{}}var Dhe=C(()=>{});var H6e,$he=C(()=>{_s();H6e=(t,e)=>_n(t.innerType._def,e)});function _n(t,e,n=!1){let r=e.seen.get(t);if(e.override){let s=e.override?.(t,e,r,n);if(s!==p6e)return s}if(r&&!n){let s=s$t(r,e);if(s!==void 0)return"$ref"in s&&e.seenRefs.add(s.$ref),s}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let i=l$t(t,t.typeName,e,n);return i&&c$t(t,e,i),o.jsonSchema=i,i}var s$t,a$t,l$t,c$t,_s=C(()=>{_g();che();uhe();dhe();fhe();phe();mhe();ghe();yhe();whe();vhe();xhe();bhe();_he();She();The();Ihe();Phe();Ehe();Ahe();khe();Mhe();Nhe();Pq();Ohe();Tq();Rhe();Lhe();Eq();Dhe();$he();_q();s$t=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let n=t.path.slice(e.basePath.length+1).join("_");return n!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:a$t(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,o)=>e.currentPath[o]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},a$t=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},l$t=(t,e,n,r)=>{switch(e){case he.ZodString:return Sq(t,n);case he.ZodNumber:return D6e(t,n);case he.ZodObject:return $6e(t,n);case he.ZodBigInt:return v6e(t,n);case he.ZodBoolean:return x6e();case he.ZodDate:return hhe(t,n);case he.ZodUndefined:return V6e();case he.ZodNull:return N6e(n);case he.ZodArray:return w6e(t,n);case he.ZodUnion:case he.ZodDiscriminatedUnion:return R6e(t,n);case he.ZodIntersection:return I6e(t,n);case he.ZodTuple:return j6e(t,n);case he.ZodRecord:return Iq(t,n);case he.ZodLiteral:return P6e(t,n);case he.ZodEnum:return T6e(t);case he.ZodNativeEnum:return k6e(t);case he.ZodNullable:return L6e(t,n);case he.ZodOptional:return F6e(t,n);case he.ZodMap:return A6e(t,n);case he.ZodSet:return z6e(t,n);case he.ZodLazy:return _n(t.getter()._def,n);case he.ZodPromise:return B6e(t,n);case he.ZodNaN:case he.ZodNever:return M6e();case he.ZodEffects:return S6e(t,n,r);case he.ZodAny:return y6e();case he.ZodUnknown:return W6e();case he.ZodDefault:return _6e(t,n);case he.ZodBranded:return b6e(t,n);case he.ZodReadonly:return H6e(t,n);case he.ZodCatch:return C6e(t,n);case he.ZodPipeline:return U6e(t,n);case he.ZodFunction:case he.ZodVoid:case he.ZodSymbol:return;default:return(o=>{})(e)}},c$t=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var Fhe,Uhe=C(()=>{_s();ahe();she();Fhe=(t,e)=>{let n=g6e(e),r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=_n(t._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i);let s=(()=>{if(h6e(n.definitions))return;let l={},c=new Set;for(let u=0;u<500;u++){let d=Object.entries(n.definitions).filter(([f])=>!c.has(f));if(d.length===0)break;for(let[f,p]of d)l[f]=_n(VU(p),{...n,currentPath:[...n.basePath,n.definitionPath,f]},!0)??{},c.add(f)}return l})(),a=r===void 0?s?{...o,[n.definitionPath]:s}:o:n.nameStrategy==="duplicate-ref"?{...o,...s||n.seenRefs.size?{[n.definitionPath]:{...s,...n.seenRefs.size?{[r]:o}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...s,[r]:o}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a}});var K6e=C(()=>{_q();ahe();bC();_s();che();uhe();dhe();fhe();phe();mhe();ghe();yhe();whe();vhe();xhe();bhe();_he();She();The();Ihe();Phe();Ehe();Ahe();khe();Mhe();Nhe();$he();Pq();Ohe();Tq();Rhe();Lhe();Eq();Dhe();Uhe();Uhe()});function q6e(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return nv(e,[],e)}function Bhe(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Bhe(e))return!0;for(let e of t.anyOf??[])if(Bhe(e))return!0;return!1}function nv(t,e,n){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!t0(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let r=t.$defs;if(t0(r))for(let[f,p]of Object.entries(r))nv(p,[...e,"$defs",f],n);let o=t.definitions;if(t0(o))for(let[f,p]of Object.entries(o))nv(p,[...e,"definitions",f],n);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let s=t.required??[],a=t.properties;if(t0(a)){for(let[f,p]of Object.entries(a))if(!Bhe(p)&&!s.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(a),t.properties=Object.fromEntries(Object.entries(a).map(([f,p])=>[f,nv(p,[...e,"properties",f],n)]))}let l=t.items;t0(l)&&(t.items=nv(l,[...e,"items"],n));let c=t.anyOf;Array.isArray(c)&&(t.anyOf=c.map((f,p)=>nv(f,[...e,"anyOf",String(p)],n)));let u=t.allOf;if(Array.isArray(u))if(u.length===1){let f=nv(u[0],[...e,"allOf","0"],n);Object.assign(t,f),delete t.allOf}else t.allOf=u.map((f,p)=>nv(f,[...e,"allOf",String(p)],n));t.default===null&&delete t.default;let d=t.$ref;if(d&&d$t(t,1)){if(typeof d!="string")throw new TypeError(`Received non-string $ref - ${d}; path=${e.join("/")}`);let f=u$t(n,d);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${d}\` to resolve to an object schema but got boolean`);if(!t0(f))throw new Error(`Expected \`$ref: ${d}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,nv(t,e,n)}return t}function u$t(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let n=e.slice(2).split("/"),r=t;for(let o of n){if(!t0(r))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(r)}`);let i=r[o];if(i===void 0)throw new Error(`Key ${o} not found while resolving ${e}`);r=i}return r}function t0(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function d$t(t,e){let n=0;for(let r in t)if(n++,n>e)return!0;return!1}var G6e=C(()=>{});function f$t(t,e){return Fhe(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function p$t(t){return q6e(Pb(t,{target:"draft-7"}))}function m$t(t){return"_zod"in t}function Y6e(t,e,n){return bWe({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:m$t(t)?p$t(t):f$t(t,{name:e})}},r=>t.parse(JSON.parse(r)))}var Z6e=C(()=>{tv();AM();K6e();Z5();G6e()});function X6e(t,e){if(typeof e<"u"&&!J6e.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${J6e.join(", ")}`);let n=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(n&&!e)return"jsonSchema";if(!n&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function h$t(t,e){let n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function Q6e(t,e,n){if(Zf(t))return Y6e(t,e,n);if(hl(t))return h$t({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:Hr(t,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=e}})}},r=>wT(t,JSON.parse(r)));throw new Error("Unsupported schema response format")}function e3e(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let n=e.images.filter(r=>typeof r?.image_url?.url=="string").map(r=>({type:"image",url:r.image_url.url}));return[{type:"text",text:t},...n]}return t}var J6e,zhe=C(()=>{Bd();Bu();Ql();Z6e();J6e=["jsonSchema","functionCalling","jsonMode"]});var g$t,t3e,n3e=C(()=>{g$t={"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}},t3e=g$t});var n0,HU=C(()=>{wC();EN();vC();xC();zhe();n3e();Gm();Bd();Bu();Jo();vI();qd();jm();Uw();fM();n0=class extends dp{constructor(e){super(e??{});I(this,"temperature");I(this,"topP");I(this,"frequencyPenalty");I(this,"presencePenalty");I(this,"n");I(this,"logitBias");I(this,"model","gpt-3.5-turbo");I(this,"modelKwargs");I(this,"stop");I(this,"stopSequences");I(this,"user");I(this,"timeout");I(this,"streaming",!1);I(this,"streamUsage",!0);I(this,"maxTokens");I(this,"logprobs");I(this,"topLogprobs");I(this,"apiKey");I(this,"organization");I(this,"__includeRawResponse");I(this,"client");I(this,"clientConfig");I(this,"supportsStrictToolCalling");I(this,"audio");I(this,"modalities");I(this,"reasoning");I(this,"zdrEnabled");I(this,"service_tier");I(this,"promptCacheKey");I(this,"promptCacheRetention");I(this,"verbosity");I(this,"defaultOptions");I(this,"lc_serializable",!0);let n=typeof e?.configuration?.apiKey=="string"||typeof e?.configuration?.apiKey=="function"?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??n??In("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??In("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1}_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(e){let n=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??void 0,ls_max_tokens:n.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}_getReasoningParams(e){if(!Xw(this.model))return;let n;return this.reasoning!==void 0&&(n={...n,...this.reasoning}),e?.reasoning!==void 0&&(n={...n,...e.reasoning}),n}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&jr(e.json_schema.schema)?Q6e(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let r={baseURL:this.clientConfig.baseURL},o=Hg(r),i={...this.clientConfig,baseURL:o,timeout:this.timeout,maxRetries:0};i.baseURL||delete i.baseURL,i.defaultHeaders=Kg(i.defaultHeaders),this.client=new en(i)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,n){return XI(e)?wHe(e.metadata.customTool):Rg(e)?n?.strict!==void 0?{...e,function:{...e.function,strict:n.strict}}:e:lHe(e,n)}bindTools(e,n){let r;return n?.strict!==void 0?r=n.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(o=>PN(o)||XI(o)?o:dHe(o)?o.extras.providerToolDefinition:this._convertChatOpenAIToolToCompletionsTool(o,{strict:r})),...n})}async stream(e,n){return super.stream(e,this._combineCallOptions(n))}async invoke(e,n){return super.invoke(e,this._combineCallOptions(n))}_combineLLMOutput(...e){return e.reduce((n,r)=>(r&&r.tokenUsage&&(n.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,n.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,n.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),n),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let n=0,r=0,o=0;this.model==="gpt-3.5-turbo-0301"?(r=4,o=-1):(r=3,o=1);let i=await Promise.all(e.map(async s=>{let a=await this.getNumTokens(s.content),l=await this.getNumTokens(Qw(s)),c=s.name!==void 0?o+await this.getNumTokens(s.name):0,u=a+r+l+c,d=s;if(d._getType()==="function"&&(u-=2),d.additional_kwargs?.function_call&&(u+=3),d?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(f){console.error("Error parsing function arguments",f,JSON.stringify(d.additional_kwargs.function_call)),u+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return n+=u,u}));return n+=3,{totalCount:n,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async r=>r.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([r.message])).countPerMessage[0]:await this.getNumTokens(r.message.content)))).reduce((r,o)=>r+o,0)}async _getEstimatedTokenCountFromPrompt(e,n,r){let o=(await this.getNumTokensFromMessages(e)).totalCount;if(n&&r!=="auto"){let i=cHe(n);o+=await this.getNumTokens(i),o+=9}return n&&e.find(i=>i._getType()==="system")&&(o-=4),r==="none"?o+=1:typeof r=="object"&&(o+=await this.getNumTokens(r.name)+4),o}async moderateContent(e,n){let r=this._getClientOptions(n?.options),o=n?.model??"omni-moderation-latest",i={input:e,model:o};return this.caller.call(async()=>{try{return await this.client.moderations.create(i,r)}catch(s){throw hp(s)}})}get profile(){return t3e[this.model]??{}}_getStructuredOutputMethod(e){let n={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(n?.method===void 0)return"jsonSchema"}else n.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return n.method}withStructuredOutput(e,n){let r,o,{schema:i,name:s,includeRaw:a}={...n,schema:e};if(n?.strict!==void 0&&n.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let l=X6e(this.model,n?.method);if(l==="jsonMode"){jr(i)?o=Vm.fromZodSchema(i):o=new Gd;let f=Hr(i);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...f}}})}else if(l==="jsonSchema"){let f={name:s??"extract",description:NT(i),schema:i,strict:n?.strict},p=Hr(f.schema);if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:f},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:f.name,description:f.description,...p}}}),jr(i)){let m=Vm.fromZodSchema(i);o=$w.from(h=>"parsed"in h.additional_kwargs?h.additional_kwargs.parsed:m)}else o=new Gd}else{let f=s??"extract";if(jr(i)){let p=Hr(i);r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:{name:f,description:p.description,parameters:p}}],tool_choice:{type:"function",function:{name:f}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:f,...p}},...n?.strict!==void 0?{strict:n.strict}:{}}),o=new up({returnSingle:!0,keyName:f,zodSchema:i})}else{let p;typeof i.name=="string"&&typeof i.parameters=="object"&&i.parameters!=null?(p=i,f=i.name):(f=i.title??f,p={name:f,description:i.description??"",parameters:i});let m=Hr(i);r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:p}],tool_choice:{type:"function",function:{name:f}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:f,...m}},...n?.strict!==void 0?{strict:n.strict}:{}}),o=new up({returnSingle:!0,keyName:f})}}if(!a)return r.pipe(o);let c=xl.assign({parsed:(f,p)=>o.invoke(f.raw,p)}),u=xl.assign({parsed:()=>null}),d=c.withFallbacks({fallbacks:[u]});return Kc.from([{raw:r},d])}}});var Aq,jhe,Vhe,r3e,o3e,KU,NN=C(()=>{vC();zhe();Kr();fM();Aq={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=Bc({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let n=e.mime_type||t.mime_type||"",r;try{r=A3(n)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!=="audio"||r.subtype!=="wav"&&r.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=A3(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=Bc({dataUrl:t.url}),n=IN(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,...t.metadata?.filename||t.metadata?.name?{filename:n}:{}}}}if(t.source_type==="base64"){let e=IN(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.filename||t.metadata?.name||t.metadata?.title?{filename:e}:{}}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},jhe=({message:t,rawResponse:e,includeRawResponse:n})=>{let r=t.tool_calls;switch(t.role){case"assistant":{let o=[],i=[];for(let c of r??[])try{o.push(Xb(c,{returnId:!0}))}catch(u){i.push(Bw(c,u.message))}let s={function_call:t.function_call,tool_calls:r};n!==void 0&&(s.__raw_response=e);let a={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};t.audio&&(s.audio=t.audio);let l=e3e(t.content||"",e.choices?.[0]?.message);return new kn({content:l,tool_calls:o,invalid_tool_calls:i,additional_kwargs:s,response_metadata:a,id:e.id})}default:return new rc(t.content||"",t.role??"unknown")}},Vhe=({delta:t,rawResponse:e,includeRawResponse:n,defaultRole:r})=>{let o=t.role??r,i=t.content??"",s;t.function_call?s={function_call:t.function_call}:t.tool_calls?s={tool_calls:t.tool_calls}:s={},n&&(s.__raw_response=e),t.audio&&(s.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(o==="user")return new Ub({content:i,response_metadata:a});if(o==="assistant"){let l=[];if(Array.isArray(t.tool_calls))for(let c of t.tool_calls)l.push({name:c.function?.name,args:c.function?.arguments,id:c.id,index:c.index,type:"tool_call_chunk"});return new Yt({content:i,tool_call_chunks:l,additional_kwargs:s,id:e.id,response_metadata:a})}else return o==="system"?new Sg({content:i,response_metadata:a}):o==="developer"?new Sg({content:i,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Fb({content:i,additional_kwargs:s,name:t.name,response_metadata:a}):o==="tool"?new Bk({content:i,additional_kwargs:s,tool_call_id:t.tool_call_id,response_metadata:a}):new $b({content:i,role:o,response_metadata:a})},r3e=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=Lle(()=>{let[,n]=t.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=IN(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},o3e=({message:t,model:e})=>{let n=Qw(t);if(n==="system"&&Xw(e)&&(n="developer"),n==="developer")return{role:"developer",content:t.contentBlocks.filter(o=>o.type==="text")};if(n==="system")return{role:"system",content:t.contentBlocks.filter(o=>o.type==="text")};if(n==="assistant")return{role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};if(n==="tool"&&Wd.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(o=>o.type==="text")};if(n==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(o=>o.type==="text").join("")};function*r(o){for(let i of o){i.type==="text"&&(yield{type:"text",text:i.text});let s=r3e(i);s&&(yield s)}}return{role:"user",content:Array.from(r(t.contentBlocks))}},KU=({messages:t,model:e})=>t.flatMap(n=>{if("output_version"in n.response_metadata&&n.response_metadata?.output_version==="v1")return o3e({message:n});let r=Qw(n);r==="system"&&Xw(e)&&(r="developer");let o=typeof n.content=="string"?n.content:n.content.map(s=>tc(s)?kw(s,Aq):s),i={role:r,content:o};if(n.name!=null&&(i.name=n.name),n.additional_kwargs.function_call!=null&&(i.function_call=n.additional_kwargs.function_call),kn.isInstance(n)&&n.tool_calls?.length?i.tool_calls=n.tool_calls.map(cU):(n.additional_kwargs.tool_calls!=null&&(i.tool_calls=n.additional_kwargs.tool_calls),Wd.isInstance(n)&&n.tool_call_id!=null&&(i.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio){let s={role:"assistant",audio:{id:n.additional_kwargs.audio.id}};return[i,s]}return i})});var qg,kq=C(()=>{wC();EN();vC();HU();NN();Kr();ac();qg=class extends n0{invocationParams(t,e){let n;t?.strict!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let r={};t?.stream_options!==void 0?r={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(r={stream_options:{include_usage:!0}});let o={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(s=>this._convertChatOpenAIToolToCompletionsTool(s,{strict:n})):void 0,tool_choice:oq(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...r,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(o.prediction=t.prediction),this.service_tier!==void 0&&(o.service_tier=this.service_tier),t?.service_tier!==void 0&&(o.service_tier=t.service_tier);let i=this._getReasoningParams(t);return i!==void 0&&i.effort!==void 0&&(o.reasoning_effort=i.effort),Xw(o.model)?o.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:o.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,o}async _generate(t,e,n){let r={},o=this.invocationParams(e),i=KU({messages:t,model:this.model});if(o.stream){let s=this._streamResponseChunks(t,e,n),a={};for await(let p of s){p.message.response_metadata={...p.generationInfo,...p.message.response_metadata};let m=p.generationInfo?.completion??0;a[m]===void 0?a[m]=p:a[m]=a[m].concat(p)}let l=Object.entries(a).sort(([p],[m])=>parseInt(p,10)-parseInt(m,10)).map(([p,m])=>m),{functions:c,function_call:u}=this.invocationParams(e),d=await this._getEstimatedTokenCountFromPrompt(t,c,u),f=await this._getNumTokensFromGenerations(l);return r.input_tokens=d,r.output_tokens=f,r.total_tokens=d+f,{generations:l,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let s=await this.completionWithRetry({...o,stream:!1,messages:i},{signal:e?.signal,...e?.options}),{completion_tokens:a,prompt_tokens:l,total_tokens:c,prompt_tokens_details:u,completion_tokens_details:d}=s?.usage??{};a&&(r.output_tokens=(r.output_tokens??0)+a),l&&(r.input_tokens=(r.input_tokens??0)+l),c&&(r.total_tokens=(r.total_tokens??0)+c),(u?.audio_tokens!==null||u?.cached_tokens!==null)&&(r.input_token_details={...u?.audio_tokens!==null&&{audio:u?.audio_tokens},...u?.cached_tokens!==null&&{cache_read:u?.cached_tokens}}),(d?.audio_tokens!==null||d?.reasoning_tokens!==null)&&(r.output_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.reasoning_tokens!==null&&{reasoning:d?.reasoning_tokens}});let f=[];for(let p of s?.choices??[]){let h={text:p.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(p.message??{role:"assistant"},s)};h.generationInfo={...p.finish_reason?{finish_reason:p.finish_reason}:{},...p.logprobs?{logprobs:p.logprobs}:{}},rp(h.message)&&(h.message.usage_metadata=r),h.message=new kn(Object.fromEntries(Object.entries(h.message).filter(([g])=>!g.startsWith("lc_")))),f.push(h)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamResponseChunks(t,e,n){let r=KU({messages:t,model:this.model}),o={...this.invocationParams(e,{streaming:!0}),messages:r,stream:!0},i,s=await this.completionWithRetry(o,e),a;for await(let l of s){let c=l?.choices?.[0];if(l.usage&&(a=l.usage),!c)continue;let{delta:u}=c;if(!u)continue;let d=this._convertCompletionsDeltaToBaseMessageChunk(u,l,i);i=u.role??i;let f={prompt:e.promptIndex??0,completion:c.index??0};if(typeof d.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let p={...f};c.finish_reason!=null&&(p.finish_reason=c.finish_reason,p.system_fingerprint=l.system_fingerprint,p.model_name=l.model,p.service_tier=l.service_tier),this.logprobs&&(p.logprobs=c.logprobs);let m=new Jr({message:d,text:d.content,generationInfo:p});yield m,await n?.handleLLMNewToken(m.text??"",f,void 0,void 0,void 0,{chunk:m})}if(a){let l={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},c={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}};yield new Jr({message:new Yt({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(l).length>0&&{input_token_details:l},...Object.keys(c).length>0&&{output_token_details:c}}}),text:""})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let n=this._getClientOptions(e),r=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return r&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(o){throw hp(o)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return Vhe({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return jhe({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}}});var Mq=C(()=>{xC();Gm();Jo()});var Whe=C(()=>{kq();Mq()});var ON,Hhe,Nq,u3e,Khe,d3e,Oq,Rq=C(()=>{EN();vC();NN();Kr();ac();fM();ON="__openai_function_call_ids__",Hhe=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},n={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:n}},Nq=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e,n=[],r=[],o=[],i={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},s={};for(let a of t.output)if(a.type==="message")e=a.id,n.push(...a.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(s.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations}):l.type==="refusal"?(s.refusal=l.refusal,[]):l));else if(a.type==="function_call"){let l={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Xb(l,{returnId:!0}))}catch(c){let u;typeof c=="object"&&c!=null&&"message"in c&&typeof c.message=="string"&&(u=c.message),o.push(Bw(l,u))}s[ON]??(s[ON]={}),a.id&&(s[ON][a.call_id]=a.id)}else if(a.type==="reasoning")s.reasoning=a;else if(a.type==="custom_tool_call"){let l=pHe(a);l?r.push(l):o.push(Bw(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let l=mHe(a);l?r.push(l):o.push(Bw(a,"Malformed computer call"))}else s.tool_outputs??(s.tool_outputs=[]),s.tool_outputs.push(a);return new kn({id:e,content:n,tool_calls:r,invalid_tool_calls:o,usage_metadata:Hhe(t.usage),additional_kwargs:s,response_metadata:i})},u3e=t=>{let e=(t.summary.length>1?t.summary.reduce((n,r)=>{let o=n[n.length-1];return o.index===r.index?o.text+=r.text:n.push(r),n},[{...t.summary[0]}]):t.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([r])=>r!=="index")));return{...t,summary:e}},Khe=t=>{let e=[],n={},r,o=[],i={model_provider:"openai"},s={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[t.annotation],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message")a=t.item.id;else if(t.type==="response.output_item.added"&&t.item.type==="function_call")o.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),s[ON]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")o.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),s.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(t.item.type))s.tool_outputs=[t.item];else if(t.type==="response.created")i.id=t.response.id,i.model_name=t.response.model,i.model=t.response.model;else if(t.type==="response.completed"){let l=Nq(t.response);r=Hhe(t.response.usage),t.response.text?.format?.type==="json_schema"&&(s.parsed??(s.parsed=JSON.parse(l.text)));for(let[c,u]of Object.entries(t.response))c!=="id"&&(i[c]=u)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")o.push({type:"tool_call_chunk",args:t.delta,index:t.output_index});else if(t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.completed")n={tool_outputs:{id:t.item_id,type:t.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(t.type==="response.refusal.done")s.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let l=t.item.summary?t.item.summary.map((c,u)=>({...c,index:u})):void 0;s.reasoning={id:t.item.id,type:t.item.type,...l?{summary:l}:{}}}else if(t.type==="response.reasoning_summary_part.added")s.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]};else if(t.type==="response.reasoning_summary_text.delta")s.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]};else return t.type==="response.image_generation_call.partial_image",null;return new Jr({text:e.map(l=>l.text).join(""),message:new Yt({id:a,content:e,tool_call_chunks:o,usage_metadata:r,additional_kwargs:s,response_metadata:i}),generationInfo:n})},d3e=t=>{let e=kn.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*n(){let r=Jw(()=>{try{let y=Qw(t);return y==="system"||y==="developer"||y==="assistant"||y==="user"?y:"assistant"}catch{return"assistant"}}),o,i=new Set,s=new Set,a=new Map,l=new Map;function*c(){if(!o)return;let y=o.content;(typeof y=="string"&&y.length>0||Array.isArray(y)&&y.length>0)&&(yield o),o=void 0}let u=y=>{o||(o={type:"message",role:r,content:[]}),typeof o.content=="string"?o.content=o.content.length>0?[{type:"input_text",text:o.content},...y]:[...y]:o.content.push(...y)},d=y=>{if(typeof y=="string")return y;try{return JSON.stringify(y??{})}catch{return"{}"}},f=y=>{let w=Jw(()=>{let v=y.metadata?.detail;return v==="low"||v==="high"||v==="auto"?v:"auto"});if(y.fileId)return{type:"input_image",detail:w,file_id:y.fileId};if(y.url)return{type:"input_image",detail:w,image_url:y.url};if(y.data){let v=typeof y.data=="string"?y.data:Buffer.from(y.data).toString("base64"),x=y.mimeType??"image/png";return{type:"input_image",detail:w,image_url:`data:${x};base64,${v}`}}},p=y=>{let w=IN(y);if(y.fileId&&typeof w=="string")return{type:"input_file",file_id:y.fileId,...w?{filename:w}:{}};if(y.url&&typeof w=="string")return{type:"input_file",file_url:y.url,...w?{filename:w}:{}};if(y.data&&typeof w=="string"){let v=typeof y.data=="string"?y.data:Buffer.from(y.data).toString("base64");return{type:"input_file",file_data:`data:${y.mimeType??"application/octet-stream"};base64,${v}`,...w?{filename:w}:{}}}},m=y=>{let w=Jw(()=>{if(Array.isArray(y.summary)){let _=y.summary?.map(T=>T?.text).filter(T=>typeof T=="string")??[];if(_.length>0)return _}return y.reasoning?[y.reasoning]:[]}),v=w.length>0?w.map(b=>({type:"summary_text",text:b})):[{type:"summary_text",text:""}],x={type:"reasoning",id:y.id??"",summary:v};return y.reasoning&&(x.content=[{type:"reasoning_text",text:y.reasoning}]),x},h=y=>({type:"function_call",name:y.name??"",call_id:y.id??"",arguments:d(y.args)}),g=y=>{let w=d(y.output),v=y.status==="success"?"completed":y.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:y.toolCallId??"",output:w,...v?{status:v}:{}}};for(let y of t.contentBlocks)if(y.type==="text")u([{type:"input_text",text:y.text}]);else if(y.type!=="invalid_tool_call"){if(y.type==="reasoning")yield*c(),yield m(y);else if(y.type==="tool_call"){yield*c();let w=y.id??"";w&&(i.add(w),a.delete(w)),yield h(y)}else if(y.type==="tool_call_chunk"){if(y.id){let w=a.get(y.id)??{name:y.name,args:[]};y.name&&(w.name=y.name),y.args&&w.args.push(y.args),a.set(y.id,w)}}else if(y.type==="server_tool_call"){yield*c();let w=y.id??"";w&&(s.add(w),l.delete(w)),yield h(y)}else if(y.type==="server_tool_call_chunk"){if(y.id){let w=l.get(y.id)??{name:y.name,args:[]};y.name&&(w.name=y.name),y.args&&w.args.push(y.args),l.set(y.id,w)}}else if(y.type==="server_tool_call_result")yield*c(),yield g(y);else if(y.type!=="audio")if(y.type==="file"){let w=p(y);w&&u([w])}else if(y.type==="image"){let w=f(y);w&&u([w])}else if(y.type==="video"){let w=p(y);w&&u([w])}else y.type==="text-plain"?y.text&&u([{type:"input_text",text:y.text}]):y.type==="non_standard"&&e&&(yield*c(),yield y.value)}yield*c();for(let[y,w]of a){if(!y||i.has(y))continue;let v=w.args.join("");!w.name&&!v||(yield{type:"function_call",call_id:y,name:w.name??"",arguments:v})}for(let[y,w]of l){if(!y||s.has(y))continue;let v=w.args.join("");!w.name&&!v||(yield{type:"function_call",call_id:y,name:w.name??"",arguments:v})}}return Array.from(n())},Oq=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(r=>{let o=r.response_metadata;if(o?.output_version==="v1")return d3e(r);let i=r.additional_kwargs,s=Qw(r);if(s==="system"&&Xw(n)&&(s="developer"),s==="function")throw new Error("Function messages are not supported in Responses API");if(s==="tool"){let a=r;if(i?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let u=a.content.find(p=>p.type==="input_image");if(u)return u;let d=a.content.find(p=>p.type==="computer_screenshot");if(d)return d;let f=a.content.find(p=>p.type==="image_url");if(f)return{type:"input_image",image_url:typeof f.image_url=="string"?f.image_url:f.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let l=Array.isArray(a.content)&&a.content.every(c=>typeof c=="object"&&c!==null&&"type"in c&&(c.type==="input_file"||c.type==="input_image"||c.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:l?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(s==="assistant"){if(!e&&o?.output!=null&&Array.isArray(o?.output)&&o?.output.length>0&&o?.output.every(f=>"type"in f))return o?.output;let a=[];if(i?.reasoning&&!e){let f=u3e(i.reasoning);a.push(f)}let{content:l}=r;i?.refusal&&(typeof l=="string"&&(l=[{type:"output_text",text:l,annotations:[]}]),l=[...l,{type:"refusal",refusal:i.refusal}]),(typeof l=="string"||l.length>0)&&a.push({type:"message",role:"assistant",...r.id&&!e&&r.id.startsWith("msg_")?{id:r.id}:{},content:Jw(()=>typeof l=="string"?l:l.flatMap(f=>f.type==="text"?{type:"output_text",text:f.text,annotations:f.annotations??[]}:f.type==="output_text"||f.type==="refusal"?f:[]))});let c=i?.[ON];kn.isInstance(r)&&r.tool_calls?.length?a.push(...r.tool_calls.map(f=>gHe(f)?{type:"custom_tool_call",id:f.call_id,call_id:f.id??"",input:f.args.input,name:f.name}:hHe(f)?{type:"computer_call",id:f.call_id,call_id:f.id??"",action:f.args.action}:{type:"function_call",name:f.name,arguments:JSON.stringify(f.args),call_id:f.id,...e?{}:{id:c?.[f.id]}})):i?.tool_calls&&a.push(...i.tool_calls.map(f=>({type:"function_call",name:f.function.name,call_id:f.id,arguments:f.function.arguments,...e?{}:{id:c?.[f.id]}})));let u=o?.output?.length?o?.output:i.tool_outputs,d=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(u!=null){let p=u?.filter(m=>d.includes(m.type));p.length>0&&a.push(...p)}return a}if(s==="user"||s==="system"||s==="developer"){if(typeof r.content=="string")return{type:"message",role:s,content:r.content};let a=[],l=r.content.flatMap(c=>{if(c.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:c.approval_request_id,approve:c.approve}),tc(c))return kw(c,Aq);if(c.type==="text")return{type:"input_text",text:c.text};if(c.type==="image_url"){let u=Jw(()=>{if(typeof c.image_url=="string")return c.image_url;if(typeof c.image_url=="object"&&c.image_url!==null&&"url"in c.image_url)return c.image_url.url}),d=Jw(()=>{if(typeof c.image_url=="string")return"auto";if(typeof c.image_url=="object"&&c.image_url!==null&&"detail"in c.image_url)return c.image_url.detail});return{type:"input_image",image_url:u,detail:d}}return c.type==="input_text"||c.type==="input_image"||c.type==="input_file"?c:[]});return l.length>0&&a.push({type:"message",role:s,content:l}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${s}`),[]})});var Lq,Dq=C(()=>{wC();EN();HU();Rq();qd();Lq=class extends n0{invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:fHe(t?.tool_choice)?t?.tool_choice:(()=>{let o=oq(t?.tool_choice);if(typeof o=="object"&&"type"in o){if(o.type==="function")return{type:"function",name:o.function.name};if(o.type==="allowed_tools")return{type:"allowed_tools",mode:o.allowed_tools.mode,tools:o.allowed_tools.tools};if(o.type==="custom")return{type:"custom",name:o.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let o=this._getResponseFormat(t?.response_format);return o?.type==="json_schema"?o.json_schema.schema!=null?{format:{type:"json_schema",schema:o.json_schema.schema,description:o.json_schema.description,name:o.json_schema.name,strict:o.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:o,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(t);return r!==void 0&&(n.reasoning=r),n}async _generate(t,e,n){let r=this.invocationParams(e);if(r.stream){let o=this._streamResponseChunks(t,e,n),i;for await(let s of o)s.message.response_metadata={...s.generationInfo,...s.message.response_metadata},i=i?.concat(s)??s;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:i?.message?.usage_metadata}}}else{let o=await this.completionWithRetry({input:Oq({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:e?.signal,...e?.options});return{generations:[{text:o.output_text,message:Nq(o)}],llmOutput:{id:o.id,estimatedTokenUsage:o.usage?{promptTokens:o.usage.input_tokens,completionTokens:o.usage.output_tokens,totalTokens:o.usage.total_tokens}:void 0}}}}async*_streamResponseChunks(t,e,n){let r=await this.completionWithRetry({...this.invocationParams(e),input:Oq({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);for await(let o of r){let i=Khe(o);i!=null&&(yield i,await n?.handleLLMNewToken(i.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:i}))}}async completionWithRetry(t,e){return this.caller.call(async()=>{let n=this._getClientOptions(e);try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(r){throw hp(r)}})}_reduceChatOpenAITools(t,e){let n=[];for(let r of t)if(PN(r))r.type==="image_generation"&&e?.stream&&(r.partial_images=1),n.push(r);else if(XI(r)){let o=r.metadata.customTool;n.push({type:"custom",name:o.name,description:o.description,format:o.format})}else Rg(r)?n.push({type:"function",name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:e?.strict??null}):iq(r)&&n.push(yHe(r));return n}}});var qhe=C(()=>{Mq();Dq()});var Zc,Ghe=C(()=>{EN();vC();HU();kq();Dq();Zc=class f3e extends n0{constructor(n){super(n);I(this,"useResponsesApi",!1);I(this,"responses");I(this,"completions");this.fields=n,this.useResponsesApi=n?.useResponsesApi??!1,this.responses=n?.responses??new Lq(n),this.completions=n?.completions??new qg(n)}get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}_useResponsesApi(n){let r=n?.tools?.some(PN),o=n?.previous_response_id!=null||n?.text!=null||n?.truncation!=null||n?.include!=null||n?.reasoning?.summary!=null||this.reasoning?.summary!=null,i=n?.tools?.some(iq)||n?.tools?.some(XI);return this.useResponsesApi||r||o||i||iHe(this.model)}getLsParams(n){let r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(n){let r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(n,r,o){return this._useResponsesApi(r)?this.responses._generate(n,r):this.completions._generate(n,r,o)}async*_streamResponseChunks(n,r,o){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(n,this._combineCallOptions(r),o);return}yield*this.completions._streamResponseChunks(n,this._combineCallOptions(r),o)}withConfig(n){let r=new f3e(this.fields);return r.defaultOptions={...this.defaultOptions,...n},r}}});var p3e=C(()=>{Mq();Whe();qhe();Ghe()});var Yhe=C(()=>{wC();xC();Gm();ac();Jo();qd();Ude();fU()});var m3e=C(()=>{xC();Yhe();Gm();Jo()});var rv,Zhe=C(()=>{wC();xC();Gm();Jo();fU();dU();rv=class extends Qb{constructor(e){let n={maxConcurrency:2,...e};super(n);I(this,"model","text-embedding-ada-002");I(this,"modelName");I(this,"batchSize",512);I(this,"stripNewLines",!0);I(this,"dimensions");I(this,"timeout");I(this,"organization");I(this,"encodingFormat");I(this,"client");I(this,"clientConfig");I(this,"apiKey");let r=n?.apiKey??n?.openAIApiKey??In("OPENAI_API_KEY");this.organization=n?.configuration?.organization??In("OPENAI_ORGANIZATION"),this.model=n?.model??n?.modelName??this.model,this.modelName=this.model,this.batchSize=n?.batchSize??this.batchSize,this.stripNewLines=n?.stripNewLines??this.stripNewLines,this.timeout=n?.timeout,this.dimensions=n?.dimensions,this.encodingFormat=n?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration}}async embedDocuments(e){let n=xI(this.stripNewLines?e.map(s=>s.replace(/\n/g," ")):e,this.batchSize),r=n.map(s=>{let a={model:this.model,input:s};return this.dimensions&&(a.dimensions=this.dimensions),this.encodingFormat&&(a.encoding_format=this.encodingFormat),this.embeddingWithRetry(a)}),o=await Promise.all(r),i=[];for(let s=0;s<o.length;s+=1){let a=n[s],{data:l}=o[s];for(let c=0;c<a.length;c+=1)i.push(l[c].embedding)}return i}async embedQuery(e){let n={model:this.model,input:this.stripNewLines?e.replace(/\n/g," "):e};this.dimensions&&(n.dimensions=this.dimensions),this.encodingFormat&&(n.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(n);return r[0].embedding}async embeddingWithRetry(e){if(!this.client){let r={baseURL:this.clientConfig.baseURL},o=Hg(r),i={...this.clientConfig,baseURL:o,timeout:this.timeout,maxRetries:0};i.baseURL||delete i.baseURL,i.defaultHeaders=Kg(i.defaultHeaders),this.client=new en(i)}let n={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(e,n)}catch(r){throw hp(r)}})}}});var Jhe,h3e=C(()=>{wC();xC();Zhe();Gm();Jo();Jhe=class extends rv{constructor(e){super(e);I(this,"azureOpenAIApiVersion");I(this,"azureOpenAIApiKey");I(this,"azureADTokenProvider");I(this,"azureOpenAIApiInstanceName");I(this,"azureOpenAIApiDeploymentName");I(this,"azureOpenAIBasePath");this.batchSize=e?.batchSize??1,this.azureOpenAIApiKey=e?.azureOpenAIApiKey??(typeof e?.apiKey=="string"?e?.apiKey:void 0)??In("AZURE_OPENAI_API_KEY"),this.azureOpenAIApiVersion=e?.azureOpenAIApiVersion??e?.openAIApiVersion??In("AZURE_OPENAI_API_VERSION"),this.azureOpenAIBasePath=e?.azureOpenAIBasePath??In("AZURE_OPENAI_BASE_PATH"),this.azureOpenAIApiInstanceName=e?.azureOpenAIApiInstanceName??In("AZURE_OPENAI_API_INSTANCE_NAME"),this.azureOpenAIApiDeploymentName=(e?.azureOpenAIApiEmbeddingsDeploymentName||e?.azureOpenAIApiDeploymentName)??(In("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME")||In("AZURE_OPENAI_API_DEPLOYMENT_NAME")),this.azureADTokenProvider=e?.azureADTokenProvider}async embeddingWithRetry(e){if(!this.client){let r={azureOpenAIApiDeploymentName:this.azureOpenAIApiDeploymentName,azureOpenAIApiInstanceName:this.azureOpenAIApiInstanceName,azureOpenAIApiKey:this.azureOpenAIApiKey,azureOpenAIBasePath:this.azureOpenAIBasePath,azureADTokenProvider:this.azureADTokenProvider,baseURL:this.clientConfig.baseURL},o=Hg(r),{apiKey:i,...s}=this.clientConfig,a={...s,baseURL:o,timeout:this.timeout,maxRetries:0};this.azureADTokenProvider||(a.apiKey=r.azureOpenAIApiKey),a.baseURL||delete a.baseURL,a.defaultHeaders=Kg(a.defaultHeaders,!0,"2.0.0"),this.client=new JI({apiVersion:this.azureOpenAIApiVersion,azureADTokenProvider:this.azureADTokenProvider,deployment:this.azureOpenAIApiDeploymentName,...a})}let n={};return this.azureOpenAIApiKey&&(n.headers={"api-key":this.azureOpenAIApiKey,...n.headers},n.query={"api-version":this.azureOpenAIApiVersion,...n.query}),this.caller.call(async()=>{try{return await this.client.embeddings.create(e,n)}catch(r){throw hp(r)}})}}});function Gg(t,e){let n=u2(e.schema),r=w2(e.schema);if(!e.schema||n||r)return new w3e({...e,description:e.description??e.schema?.description??`${e.name} tool`,func:async(s,a,l)=>new Promise((c,u)=>{let d=Fi(l,{callbacks:a?.getChild()});vl.runWithConfig(Gu(d),async()=>{try{c(t(s,d))}catch(f){u(f)}})})});let o=e.schema,i=e.description??e.schema.description??`${e.name} tool`;return new b$t({...e,description:i,schema:o,func:async(s,a,l)=>new Promise((c,u)=>{let d,f=()=>{l?.signal&&d&&l.signal.removeEventListener("abort",d)};l?.signal&&(d=()=>{f(),u(Kb(l.signal))},l.signal.addEventListener("abort",d,{once:!0}));let p=Fi(l,{callbacks:a?.getChild()});vl.runWithConfig(Gu(p),async()=>{try{let m=await t(s,p);if(Vue(m)){c(m);return}if(l?.signal?.aborted){f();return}f(),c(m)}catch(m){f(),u(m)}})})})}function C$t(t){let{content:e,artifact:n,toolCallId:r,metadata:o}=t;return r&&!Ple(e)?typeof e=="string"||Array.isArray(e)&&e.every(i=>typeof i=="object")?new Wd({status:"success",content:e,artifact:n,tool_call_id:r,name:t.name,metadata:o}):new Wd({status:"success",content:_$t(e),artifact:n,tool_call_id:r,name:t.name,metadata:o}):e}function _$t(t){try{return JSON.stringify(t)??""}catch{return`${t}`}}var g3e,y3e,w3e,b$t,gp=C(()=>{$n();L3();zk();Hb();sI();aI();Ng();rM();vg();Bu();Hue();qd();Jue();_g();P3();tv();g3e=class extends nU{constructor(e){super(e??{});I(this,"extras");I(this,"returnDirect",!1);I(this,"verboseParsingErrors",!1);I(this,"responseFormat","content");I(this,"defaultConfig");this.verboseParsingErrors=e?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=e?.responseFormat??this.responseFormat,this.defaultConfig=e?.defaultConfig??this.defaultConfig,this.metadata=e?.metadata??this.metadata,this.extras=e?.extras??this.extras}get lc_namespace(){return["langchain","tools"]}async invoke(e,n){let r,o=fr(nM(this.defaultConfig,n));return Db(e)?(r=e.args,o={...o,toolCall:e}):r=e,this.call(r,o)}async call(e,n,r){let o=Db(e)?e.args:e,i;if(jr(this.schema))try{i=await MT(this.schema,o)}catch(m){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
Details: ${m.message}`),_ae(m)&&(h=`${h}

${se.prettifyError(m)}`),new S2(h,JSON.stringify(e))}else{let m=Yo(o,this.schema);if(!m.valid){let h="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(h=`${h}
Details: ${m.errors.map(g=>`${g.keywordLocation}: ${g.error}`).join(`
`)}`),new S2(h,JSON.stringify(e))}i=o}let s=Wb(n),a=Ws.configure(s.callbacks,this.callbacks,s.tags||r,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),l;Db(e)&&(l=e.id),!l&&HFe(s)&&(l=s.toolCall.id);let c=await a?.handleToolStart(this.toJSON(),typeof e=="string"?e:JSON.stringify(e),s.runId,void 0,void 0,void 0,s.runName,l);delete s.runId;let u;try{let m=await this._call(i,c,s);u=Vue(m)?await Xje(m,async h=>{try{await c?.handleToolEvent(h)}catch(g){await c?.handleToolError(g)}}):m}catch(m){throw await c?.handleToolError(m),m}let d,f;if(this.responseFormat==="content_and_artifact")if(Array.isArray(u)&&u.length===2)[d,f]=u;else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.
Result: ${JSON.stringify(u)}`);else d=u;let p=C$t({content:d,artifact:f,toolCallId:l,name:this.name,metadata:this.metadata});return await c?.handleToolEnd(p),p}},y3e=class extends g3e{constructor(e){super(e);I(this,"schema",we.object({input:we.string().optional()}).transform(e=>e.input))}call(e,n){let r=typeof e=="string"||e==null?{input:e}:e;return super.call(r,n)}},w3e=class extends y3e{constructor(e){super(e);I(this,"name");I(this,"description");I(this,"func");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect}static lc_name(){return"DynamicTool"}async call(e,n){let r=Wb(n);return r.runName===void 0&&(r.runName=this.name),super.call(e,r)}_call(e,n,r){return this.func(e,n,r)}},b$t=class extends g3e{constructor(e){super(e);I(this,"description");I(this,"func");I(this,"schema");this.name=e.name,this.description=e.description,this.func=e.func,this.returnDirect=e.returnDirect??this.returnDirect,this.schema=e.schema}static lc_name(){return"DynamicStructuredTool"}async call(e,n,r){let o=Wb(n);return o.runName===void 0&&(o.runName=this.name),super.call(e,o,r)}_call(e,n,r){return this.func(e,n,r)}}});var Xhe=C(()=>{Gm();Jo();gp()});var v3e=C(()=>{});var x3e=C(()=>{});var b3e=C(()=>{});var C3e=C(()=>{});var _3e=C(()=>{});var S$t,T$t,I$t,P$t,E$t,A$t,k$t,M$t,N$t,O$t,vKn,S3e=C(()=>{Kr();gp();tv();S$t=se.object({type:se.literal("screenshot")}),T$t=se.object({type:se.literal("click"),x:se.number(),y:se.number(),button:se.enum(["left","right","wheel","back","forward"]).default("left")}),I$t=se.object({type:se.literal("double_click"),x:se.number(),y:se.number(),button:se.enum(["left","right","wheel","back","forward"]).default("left")}),P$t=se.object({type:se.literal("drag"),path:se.array(se.object({x:se.number(),y:se.number()}))}),E$t=se.object({type:se.literal("keypress"),keys:se.array(se.string())}),A$t=se.object({type:se.literal("move"),x:se.number(),y:se.number()}),k$t=se.object({type:se.literal("scroll"),x:se.number(),y:se.number(),scroll_x:se.number(),scroll_y:se.number()}),M$t=se.object({type:se.literal("type"),text:se.string()}),N$t=se.object({type:se.literal("wait"),duration:se.number().optional()}),O$t=se.discriminatedUnion("type",[S$t,T$t,I$t,P$t,E$t,A$t,k$t,M$t,N$t]),vKn=se.object({action:O$t})});var R$t,_Kn,T3e=C(()=>{gp();tv();R$t=se.object({type:se.literal("exec"),command:se.array(se.string()),env:se.record(se.string(),se.string()).optional(),working_directory:se.string().optional(),timeout_ms:se.number().optional(),user:se.string().optional()}),_Kn=se.discriminatedUnion("type",[R$t])});var PKn,I3e=C(()=>{gp();tv();PKn=se.object({commands:se.array(se.string()).describe("Array of shell commands to execute"),timeout_ms:se.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:se.number().optional().describe("Optional maximum number of characters to return from each command")})});var L$t,D$t,$$t,MKn,P3e=C(()=>{gp();tv();L$t=se.object({type:se.literal("create_file"),path:se.string(),diff:se.string()}),D$t=se.object({type:se.literal("update_file"),path:se.string(),diff:se.string()}),$$t=se.object({type:se.literal("delete_file"),path:se.string()}),MKn=se.discriminatedUnion("type",[L$t,D$t,$$t])});var E3e=C(()=>{Xhe();v3e();x3e();b3e();C3e();_3e();S3e();T3e();I3e();P3e()});var A3e=C(()=>{jm();gp();aI()});var k3e=C(()=>{NN()});var M3e=C(()=>{NN();Rq()});var Yg=C(()=>{wC();vC();xC();HU();NN();kq();Whe();Rq();Dq();qhe();Ghe();p3e();Yhe();m3e();Zhe();h3e();Xhe();E3e();A3e();k3e();M3e();Gm()});var $q,N3e=C(()=>{dU();fU();Jo();$q=class extends Qb{constructor(n){let r={maxConcurrency:2,...n};super(r);this.model="jina-clip-v2";this.batchSize=24;this.baseUrl="https://api.jina.ai/v1/embeddings";this.stripNewLines=!0;this.dimensions=1024;this.normalized=!0;let o=r?.apiKey||In("JINA_API_KEY")||In("JINA_AUTH_TOKEN");if(!o)throw new Error("Jina API key not found");this.apiKey=o,this.model=r?.model??r?.modelName??this.model,this.baseUrl=r?.baseUrl??this.baseUrl,this.dimensions=r?.dimensions??this.dimensions,this.batchSize=r?.batchSize??this.batchSize,this.stripNewLines=r?.stripNewLines??this.stripNewLines,this.normalized=r?.normalized??this.normalized}async embedDocuments(n){let r=xI(this.doStripNewLines(n),this.batchSize),o=r.map(a=>{let l=this.getParams(a);return this.embeddingWithRetry(l)}),i=await Promise.all(o),s=[];for(let a=0;a<i.length;a+=1){let l=r[a],c=i[a]||[];for(let u=0;u<l.length;u+=1)s.push(c[u])}return s}async embedQuery(n){let r=this.getParams(this.doStripNewLines([n]),!0);return(await this.embeddingWithRetry(r)||[[]])[0]}doStripNewLines(n){return this.stripNewLines?n.map(r=>typeof r=="string"?r.replace(/\n/g," "):r.text?{text:r.text.replace(/\n/g," ")}:r):n}getParams(n,r){return{model:this.model,input:n,dimensions:this.dimensions,task:r?"retrieval.query":"retrieval.passage",normalized:this.normalized}}async embeddingWithRetry(n){let o=await(await fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(n)})).json();if("detail"in o&&o.detail)throw new Error(`${o.detail}`);return o.data.map(({embedding:i})=>i)}}});var r0,O3e=C(()=>{qe();Yg();r0=class extends rv{constructor(e){super(e),this.customConfig=e}async embedQuery(e){return(await this.callEmbeddingAPI([e]))[0]}async embedDocuments(e){return await this.callEmbeddingAPI(e)}async callEmbeddingAPI(e){let n={model:this.customConfig.modelName,input:e,encoding_format:"float"},r=this.customConfig.configuration,i=`${r?.baseURL||"https://api.openai.com/v1"}/embeddings`,s=this.customConfig.apiKey,l=await(r?.fetch||Qy)(i,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json",...this.customConfig.headers||{}},body:JSON.stringify(n)});if(!l.ok){let u=await l.text();throw new Error(`Embedding API request failed: ${l.status} ${l.statusText} - ${u}`)}let c=await l.json();if(!c.data||!Array.isArray(c.data))throw new Error("Invalid API response format: missing or invalid data array");return c.data.map(u=>{if(!u.embedding||!Array.isArray(u.embedding))throw new Error("Invalid API response format: missing or invalid embedding array");return u.embedding})}}});var Fq,F$t,is,o0=C(()=>{It();Su();Nf();ye();Se();qe();_de();Bde();Yg();Fq=require("obsidian");Zg();N3e();O3e();F$t={"copilot-plus":r0,"copilot-plus-jina":$q,openai:rv,cohereai:rv,google:Cde,"azure openai":Jhe,ollama:Fde,"lm-studio":r0,"3rd party (openai-format)":rv,siliconflow:r0,openrouterai:r0},is=class t{constructor(){this.providerApiKeyMap={"copilot-plus":()=>q().plusLicenseKey,"copilot-plus-jina":()=>q().plusLicenseKey,openai:()=>q().openAIApiKey,cohereai:()=>q().cohereApiKey,google:()=>q().googleApiKey,"azure openai":()=>q().azureOpenAIApiKey,ollama:()=>"default-key","lm-studio":()=>"default-key","3rd party (openai-format)":()=>"default-key",siliconflow:()=>q().siliconflowApiKey,openrouterai:()=>q().openRouterAiApiKey};this.initialize(),Ho(()=>this.initialize())}initialize(){let e=q().activeEmbeddingModels;this.activeEmbeddingModels=e,this.buildModelMap(e)}static getInstance(){return t.instance||(t.instance=new t),t.instance}getProviderConstructor(e){let n=F$t[e.provider];if(!n)throw console.warn(`Unknown provider: ${e.provider} for model: ${e.name}`),new Error(`Unknown provider: ${e.provider} for model: ${e.name}`);return n}buildModelMap(e){t.modelMap={};let n=t.modelMap;e.forEach(r=>{if(r.enabled){if(!Object.values(um).contains(r.provider)){console.warn(`Unknown provider: ${r.provider} for embedding model: ${r.name}`);return}let o=this.getProviderConstructor(r),i=r.apiKey||this.providerApiKeyMap[r.provider](),s=ln(r);n[s]={hasApiKey:!!i,EmbeddingConstructor:o,vendor:r.provider}}})}static getModelName(e){let n=e;if(n.model)return n.model;if(n.modelName)return n.modelName;throw new Error(`Embeddings instance missing model or modelName properties: ${JSON.stringify(e)}`)}getCustomModel(e){return this.activeEmbeddingModels.filter(n=>{let r=ln(n);return e===r})[0]}async getEmbeddingsAPI(){let n=q().embeddingModelKey;if(!Object.prototype.hasOwnProperty.call(t.modelMap,n))throw new Gn(`No embedding model found for: ${n}`);let r=this.getCustomModel(n);if(r.plusExclusive&&!q().isPlusUser)throw new Fq.Notice("Plus-only model, please consider upgrading to Plus to access it."),new Gn("Plus-only model selected but user is not on Plus plan");if(r.believerExclusive){let a=await di.getInstance().validateLicenseKey();if(!a.plan||a.plan.toLowerCase()!=="believer")throw new Fq.Notice("Believer-only model, please consider upgrading to Believer to access it."),new Gn("Believer-only model selected but user is not on Believer plan")}let o=t.modelMap[n];if(!o.hasApiKey)throw new Gn(`API key is not provided for the embedding model: ${n}`);let i=await this.getEmbeddingConfig(r);try{return t.embeddingModel=new o.EmbeddingConstructor(i),t.embeddingModel}catch(s){let a=s instanceof Error?s.message:String(s);throw new Gn(`Error creating embedding model: ${n}. ${a}`)}}async getEmbeddingConfig(e){let n=q(),r=e.name,o={maxRetries:3,maxConcurrency:3},s={"copilot-plus":{modelName:r,apiKey:await pn(n.plusLicenseKey),timeout:1e4,batchSize:q().embeddingBatchSize,configuration:{baseURL:jy,fetch:e.enableCors?fo:void 0}},"copilot-plus-jina":{model:r,apiKey:await pn(n.plusLicenseKey),timeout:1e4,batchSize:q().embeddingBatchSize,dimensions:e.dimensions,baseUrl:jy+"/embeddings",configuration:{fetch:e.enableCors?fo:void 0}},openai:{modelName:r,apiKey:await pn(e.apiKey||n.openAIApiKey),timeout:1e4,batchSize:q().embeddingBatchSize,configuration:{baseURL:e.baseUrl,fetch:e.enableCors?fo:void 0}},cohereai:{modelName:r,apiKey:await pn(e.apiKey||n.cohereApiKey),timeout:1e4,batchSize:q().embeddingBatchSize,configuration:{baseURL:e.baseUrl||Cu.cohereai.host,fetch:e.enableCors?fo:void 0}},google:{modelName:r,apiKey:await pn(n.googleApiKey)},"azure openai":{modelName:r,azureOpenAIApiKey:await pn(e.apiKey||n.azureOpenAIApiKey),azureOpenAIApiInstanceName:e.azureOpenAIApiInstanceName||n.azureOpenAIApiInstanceName,azureOpenAIApiDeploymentName:e.azureOpenAIApiEmbeddingDeploymentName||n.azureOpenAIApiEmbeddingDeploymentName,azureOpenAIApiVersion:e.azureOpenAIApiVersion||n.azureOpenAIApiVersion},ollama:{baseUrl:e.baseUrl||"http://localhost:11434",model:r,truncate:!0,headers:{Authorization:`Bearer ${await pn(e.apiKey||"default-key")}`}},"lm-studio":{modelName:r,openAIApiKey:await pn(e.apiKey||"default-key"),configuration:{baseURL:e.baseUrl||"http://localhost:1234/v1",fetch:e.enableCors?fo:void 0}},"3rd party (openai-format)":{modelName:r,openAIApiKey:await pn(e.apiKey||""),batchSize:q().embeddingBatchSize,configuration:{baseURL:e.baseUrl,fetch:e.enableCors?fo:void 0,dangerouslyAllowBrowser:!0}},siliconflow:{modelName:r,apiKey:await pn(e.apiKey||n.siliconflowApiKey),batchSize:q().embeddingBatchSize,configuration:{baseURL:e.baseUrl||Cu.siliconflow.host,fetch:e.enableCors?fo:void 0}},openrouterai:{modelName:r,apiKey:await pn(e.apiKey||n.openRouterAiApiKey),batchSize:q().embeddingBatchSize,configuration:{baseURL:e.baseUrl||"https://openrouter.ai/api/v1",fetch:e.enableCors?fo:void 0}}}[e.provider]||{};return{...o,...s}}async ping(e){let n=async r=>{let o={...e,enableCors:r},i=await this.getEmbeddingConfig(o);await new(this.getProviderConstructor(o))(i).embedQuery("test")};try{return await n(!1),!0}catch(r){k("First ping attempt failed, trying with CORS...");try{return await n(!0),new Fq.Notice("Connection successful, but requires CORS to be enabled. Please enable CORS for this model once you add it above."),!0}catch(o){let i=`
without CORS Error: `+Xt(r)+`
with CORS Error: `+Xt(o);throw new Error(i)}}}}});function L3e(t){return t.replace(/\\/g,"/").replace(/\/+$/,"")}function Jm(t){return(t.miyoServerUrl||"").trim()}function Fa(t){return!t.enableMiyo||!Qhe()?!1:!R3e.Platform.isMobile||!!Jm(t)}function Jg(t){return t.vault.getName()}function Uq(t,e){let n=L3e(e).replace(/^\/+/,""),r=Jg(t);return r?`${r}/${n}`:n}function i0(t,e){let n=L3e(e),r=Jg(t);if(!r)return n;let o=`${r}/`;return n.startsWith(o)?n.slice(o.length):n}var R3e,yp=C(()=>{ns();R3e=require("obsidian")});var D3e,Bq,$3e=C(()=>{ye();Se();qe();D3e=require("obsidian"),Bq=class t{constructor(){this.cachedBaseUrl=null}static getInstance(){return t.instance||(t.instance=new t),t.instance}async resolveBaseUrl(e={}){let n=(e.overrideUrl||"").trim();if(n.length>0)return this.normalizeBaseUrl(n);if(this.cachedBaseUrl&&!e.forceRefresh)return this.cachedBaseUrl;if(!D3e.Platform.isDesktopApp)return null;let r=await this.readServiceConfig();if(r==="missing"){let i=this.getDefaultBaseUrl();return this.cachedBaseUrl=null,q().debug&&k(`Miyo service discovery file missing; using fallback ${i}`),i}if(!r)return this.cachedBaseUrl=null,null;let o=this.normalizeBaseUrl(`http://${r.host}:${r.port}`);return this.cachedBaseUrl=o,o}normalizeBaseUrl(e){return e.trim().replace(/\/+$/,"")}getDefaultBaseUrl(){return this.normalizeBaseUrl("http://127.0.0.1:8742")}getServiceFilePaths(){let e=this.getNodeRequire();if(!e)return[];let n=e("os"),r=e("process"),o=e("path"),i=n.homedir(),s=n.platform(),a=r.env||{};if(s==="win32"){let l=(a.LOCALAPPDATA||"").trim(),c=(a.APPDATA||"").trim();return[l,o.join(i,"AppData","Local"),c,o.join(i,"AppData","Roaming")].filter((d,f,p)=>d.length>0&&p.indexOf(d)===f).map(d=>o.join(d,"Miyo","service.json"))}return s==="linux"?[o.join(i,".config","Miyo","service.json")]:s==="darwin"?[o.join(i,"Library","Application Support","Miyo","service.json")]:(ee(`Miyo service discovery unsupported platform: ${s}`),[])}async readServiceConfig(){let e=this.getServiceFilePaths();if(e.length===0)return null;let n=this.getNodeRequire();if(!n)return null;let r=n("fs"),o=!1;for(let i of e)try{let s=await r.promises.readFile(i,"utf8"),a=JSON.parse(s);return!a.host||typeof a.host!="string"?(ee("Miyo service discovery missing host"),null):typeof a.port!="number"||Number.isNaN(a.port)?(ee("Miyo service discovery missing port"),null):(q().debug&&k(`Miyo service discovery resolved host=${a.host} port=${a.port}`),a)}catch(s){if(this.isMissingFileError(s)){o=!0;continue}return q().debug&&ee(`Miyo service discovery failed: ${Xt(s)}`),null}return o?"missing":null}isMissingFileError(e){return e?.code==="ENOENT"}getNodeRequire(){let e=window?.require;return typeof e=="function"?e:null}}});var F3e,wp,RN=C(()=>{Su();ye();$3e();Se();qe();F3e=require("obsidian"),wp=class{constructor(){this.discovery=Bq.getInstance()}async resolveBaseUrl(e){let n=await this.discovery.resolveBaseUrl({overrideUrl:e});if(!n)throw new Error("Miyo base URL not available");return n}async isBackendAvailable(e){try{let n=await this.resolveBaseUrl(e),r=await this.requestJson(n,"/v0/health",{method:"GET"});return r?.status!=="ok"?(ee(`Miyo health check failed: status="${r?.status??"unknown"}"`),!1):!0}catch(n){return ee(`Miyo backend availability check failed: ${Xt(n)}`),!1}}async getFolder(e,n){return this.requestJson(e,"/v0/folder",{method:"GET",query:{path:n}})}async scanFolder(e,n,r=!1){return this.requestJson(e,"/v0/scan",{method:"POST",body:{path:n,force:r}})}async listFolderFiles(e,n){return this.requestJson(e,"/v0/folder/files",{method:"GET",query:{folder_name:n.folderName,title:n.title,file_path:n.filePath,mtime_after:n.mtimeAfter,mtime_before:n.mtimeBefore,offset:n.offset,limit:n.limit,order_by:n.orderBy}})}async getDocumentsByPath(e,n,r){return this.requestJson(e,"/v0/folder/documents",{method:"GET",query:{path:r,folder_name:n}})}async search(e,n,r,o,i){let s={query:r,...n?{folder_name:n}:{},limit:o,...i&&i.length>0?{filters:i}:{}};return q().debug&&k("Miyo search request:",{baseUrl:e,payload:s}),this.requestJson(e,"/v0/search",{method:"POST",body:s})}async searchRelated(e,n,r){let o={file_path:n,...r?.folderName?{folder_name:r.folderName}:{},...typeof r?.limit=="number"?{limit:r.limit}:{},...r?.filters&&r.filters.length>0?{filters:r.filters}:{}};return this.requestJson(e,"/v0/search/related",{method:"POST",body:o})}async parseDoc(e,n,r){return this.requestJson(e,"/v0/parse-doc",{method:"POST",body:{folder_name:n,path:r}})}async buildHeaders(){let e=q(),n={},r=e.plusLicenseKey?await pn(e.plusLicenseKey):"";return r&&(n.Authorization=`Bearer ${r}`),n}async requestJson(e,n,r){let o=new URL(n,e);r.query&&Object.entries(r.query).forEach(([c,u])=>{u!=null&&o.searchParams.set(c,String(u))});let i=r.body?JSON.stringify(r.body):void 0,s=await this.buildHeaders();k("Miyo request:",{method:r.method,url:o.toString(),hasBody:!!i,hasAuthorizationHeader:!!s.Authorization,...q().debug&&r.method==="POST"?{postBody:r.body}:{}});let a=await(0,F3e.requestUrl)({url:o.toString(),method:r.method,headers:s,contentType:i?"application/json":void 0,body:i,throw:!1});if(a.status>=400){let u=this.parseResponseJson(a.json,a.text)?.detail||a.text||"";throw ee(`Miyo request failed (${a.status}): ${u}`),new Error(u?`Miyo request failed with status ${a.status}: ${u}`:`Miyo request failed with status ${a.status}`)}let l=this.parseResponseJson(a.json,a.text);return q().debug&&k(`Miyo request ${r.method} ${o.toString()} succeeded`),l}parseResponseJson(e,n){if(typeof e=="string")try{return JSON.parse(e)}catch(r){return z(`Failed to parse Miyo JSON response: ${Xt(r)}`),{}}if(e!=null)return e;if(n)try{return JSON.parse(n)}catch(r){return z(`Failed to parse Miyo text response: ${Xt(r)}`),{}}return{}}}});var U3e,zq,B3e=C(()=>{U3e=require("obsidian");ye();RN();yp();Se();zq=class{constructor(e){this.app=e;this.client=new wp}async initialize(e){try{let n=await this.getBaseUrl();await this.client.getFolder(n,this.getFolderName())}catch(n){ee(`Miyo backend initialization failed: ${n}`),new U3e.Notice("Failed to initialize Miyo backend. Check Miyo service discovery or folder setup.")}}async clearIndex(e){ee("Miyo clearIndex requested from Copilot, but folder lifecycle is managed in Miyo.")}requiresEmbeddings(){return!1}async upsert(e){k(`Skipping direct Miyo upsert for ${e.path}; Miyo manages indexing itself.`)}async upsertBatch(e){return e.length>0&&k(`Skipping direct Miyo batch upsert for ${e.length} documents.`),0}async removeByPath(e){k(`Skipping direct Miyo delete for ${e}; Miyo manages file lifecycle itself.`)}async getIndexedFiles(){let e=await this.getAllIndexedFiles();return Array.from(new Set(e.map(n=>this.toVaultPath(n.path)))).sort()}async getLatestFileMtime(){return(await this.getAllIndexedFiles()).reduce((n,r)=>Math.max(n,r.mtime??0),0)}async isIndexEmpty(){return(await this.getAllIndexedFiles()).length===0}async hasIndex(e){return(await this.getDocumentsByPath(e)).length>0}async getDocumentsByPath(e){let n=await this.getBaseUrl(),r=Uq(this.app,e);return((await this.client.getDocumentsByPath(n,this.getFolderName(),r)).documents??[]).map(s=>this.fromMiyoDocument(e,s))}async checkAndHandleEmbeddingModelChange(e){return!1}async save(){}async checkIndexIntegrity(){}async garbageCollect(){return k("Skipping Miyo garbage collection; folder lifecycle is managed in Miyo."),0}markFileMissingEmbeddings(e){}clearFilesMissingEmbeddings(){}getFilesMissingEmbeddings(){return[]}markUnsavedChanges(){}onunload(){}isRemoteBackend(){return!0}async requestIndexRefresh(e=!1){let n=await this.getBaseUrl();await this.client.scanFolder(n,this.getFolderName(),e)}async getBaseUrl(){let e=Jm(q());return this.client.resolveBaseUrl(e)}getFolderName(){return Jg(this.app)}async getAllIndexedFiles(){let e=await this.getBaseUrl(),n=200,r=0,o=null,i=[];do{let s=await this.client.listFolderFiles(e,{folderName:this.getFolderName(),offset:r,limit:n}),a=s.files??[];if(i.push(...a),o===null&&(o=s.total??a.length),r+=a.length,a.length===0)break}while(r<o);return i}toVaultPath(e){return i0(this.app,e)}fromMiyoDocument(e,n){let r=n.path?this.toVaultPath(n.path):e,o=n.chunk_text??"",i={...n.metadata??{}};return!i.chunkId&&n.chunk_index!==void 0&&(i.chunkId=`${r}#${n.chunk_index}`),n.chunk_index!==void 0&&i.chunkIndex===void 0&&(i.chunkIndex=n.chunk_index),{id:n.id,title:n.title??"",content:o,embedding:[],path:r,embeddingModel:n.embedding_model??"",created_at:typeof n.created_at=="number"?n.created_at:0,ctime:n.ctime??0,mtime:n.mtime??0,tags:n.tags??[],extension:n.extension??"",nchars:n.nchars??o.length,metadata:i}}}});function V3e(t){return t!==void 0&&qU.includes(t)?z3e[t]:void 0}var z3e,j3e,qU,jq=C(()=>{z3e={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"},j3e={dutch:/[^A-Za-zàèéìòóù0-9_'-]+/gim,english:/[^A-Za-zàèéìòóù0-9_'-]+/gim,french:/[^a-z0-9äâàéèëêïîöôùüûœç-]+/gim,italian:/[^A-Za-zàèéìòóù0-9_'-]+/gim,norwegian:/[^a-z0-9_æøåÆØÅäÄöÖüÜ]+/gim,portuguese:/[^a-z0-9à-úÀ-Ú]/gim,russian:/[^a-z0-9а-яА-ЯёЁ]+/gim,spanish:/[^a-z0-9A-Zá-úÁ-ÚñÑüÜ]+/gim,swedish:/[^a-z0-9_åÅäÄöÖüÜ-]+/gim,german:/[^a-z0-9A-ZäöüÄÖÜß]+/gim,finnish:/[^a-z0-9äöÄÖ]+/gim,danish:/[^a-z0-9æøåÆØÅ]+/gim,hungarian:/[^a-z0-9áéíóöőúüűÁÉÍÓÖŐÚÜŰ]+/gim,romanian:/[^a-z0-9ăâîșțĂÂÎȘȚ]+/gim,serbian:/[^a-z0-9čćžšđČĆŽŠĐ]+/gim,turkish:/[^a-z0-9çÇğĞıİöÖşŞüÜ]+/gim,lithuanian:/[^a-z0-9ąčęėįšųūžĄČĘĖĮŠŲŪŽ]+/gim,arabic:/[^a-z0-9أ-ي]+/gim,nepali:/[^a-z0-9अ-ह]+/gim,irish:/[^a-z0-9áéíóúÁÉÍÓÚ]+/gim,indian:/[^a-z0-9अ-ह]+/gim,armenian:/[^a-z0-9ա-ֆ]+/gim,greek:/[^a-z0-9α-ωά-ώ]+/gim,indonesian:/[^a-z0-9]+/gim,ukrainian:/[^a-z0-9а-яА-ЯіїєІЇЄ]+/gim,slovenian:/[^a-z0-9čžšČŽŠ]+/gim,bulgarian:/[^a-z0-9а-яА-Я]+/gim,tamil:/[^a-z0-9அ-ஹ]+/gim,sanskrit:/[^a-z0-9A-Zāīūṛḷṃṁḥśṣṭḍṇṅñḻḹṝ]+/gim},qU=Object.keys(z3e)});function So(t,e){if(e.length<ege)Array.prototype.push.apply(t,e);else{let n=e.length;for(let r=0;r<n;r+=ege)Array.prototype.push.apply(t,e.slice(r,r+ege))}}function G3e(t,...e){return t.replace(/%(?:(?<position>\d+)\$)?(?<width>-?\d*\.?\d*)(?<type>[dfs])/g,function(...n){let r=n[n.length-1],{width:o,type:i,position:s}=r,a=s?e[Number.parseInt(s)-1]:e.shift(),l=o===""?0:Number.parseInt(o);switch(i){case"d":return a.toString().padStart(l,"0");case"f":{let c=a,[u,d]=o.split(".").map(f=>Number.parseFloat(f));return typeof d=="number"&&d>=0&&(c=c.toFixed(d)),typeof u=="number"&&u>=0?c.toString().padStart(l,"0"):c.toString()}case"s":return l<0?a.toString().padEnd(-l," "):a.toString().padStart(l," ");default:return a}})}function z$t(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function j$t(){return typeof process<"u"&&process.release&&process.release.name==="node"}function q3e(){return BigInt(Math.floor(performance.now()*1e6))}function s0(t){return typeof t=="number"&&(t=BigInt(t)),t<W3e?`${t}ns`:t<H3e?`${t/W3e}\u03BCs`:t<K3e?`${t/H3e}ms`:`${t/K3e}s`}function Xm(){return z$t()?q3e():j$t()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?q3e():BigInt(0)}function GU(){return`${U$t}-${B$t++}`}function LN(t,e){return Object.hasOwn===void 0?Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0:Object.hasOwn(t,e)?t[e]:void 0}function Y3e(t,e){return e[1]===t[1]?t[0]-e[0]:e[1]-t[1]}function DN(t){if(t.length===0)return[];if(t.length===1)return t[0];for(let n=1;n<t.length;n++)if(t[n].length<t[0].length){let r=t[0];t[0]=t[n],t[n]=r}let e=new Map;for(let n of t[0])e.set(n,1);for(let n=1;n<t.length;n++){let r=0;for(let o of t[n]){let i=e.get(o);i===n&&(e.set(o,i+1),r++)}if(r===0)return[]}return t[0].filter(n=>{let r=e.get(n);return r!==void 0&&e.set(n,0),r===t.length})}function Vq(t,e){let n={},r=e.length;for(let o=0;o<r;o++){let i=e[o],s=i.split("."),a=t,l=s.length;for(let c=0;c<l;c++)if(a=a[s[c]],typeof a=="object"){if(a!==null&&"lat"in a&&"lon"in a&&typeof a.lat=="number"&&typeof a.lon=="number"){a=n[i]=a;break}else if(!Array.isArray(a)&&a!==null&&c===l-1){a=void 0;break}}else if((a===null||typeof a!="object")&&c<l-1){a=void 0;break}typeof a<"u"&&(n[i]=a)}return n}function $N(t,e){return Vq(t,[e])[e]}function tge(t,e){let n=V$t[e];if(n===void 0)throw new Error(qt("INVALID_DISTANCE_SUFFIX",t).message);return t*n}function Wq(t,e){t.hits=t.hits.map(n=>({...n,document:{...n.document,...e.reduce((r,o)=>{let i=o.split("."),s=i.pop(),a=r;for(let l of i)a[l]=a[l]??{},a=a[l];return a[s]=null,r},n.document)}}))}function Ss(t){return t?.constructor?.name==="AsyncFunction"}var U$t,B$t,W3e,H3e,K3e,ege,V$t,ss=C(()=>{Ua();U$t=Date.now().toString().slice(5),B$t=0,W3e=BigInt(1e3),H3e=BigInt(1e6),K3e=BigInt(1e9),ege=65535;V$t={cm:.01,m:1,km:1e3,ft:.3048,yd:.9144,mi:1609.344}});function qt(t,...e){let n=new Error(G3e(H$t[t]??`Unsupported Orama Error code: ${t}`,...e));return n.code=t,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}var W$t,H$t,Ua=C(()=>{jq();ss();W$t=qU.join(`
 - `),H$t={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
 - ${W$t}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages."}});function Z3e(t){return{raw:Number(t),formatted:s0(t)}}function J3e(t){if(t.id){if(typeof t.id!="string")throw qt("DOCUMENT_ID_MUST_BE_STRING",typeof t.id);return t.id}return GU()}function nge(t,e){for(let[n,r]of Object.entries(e)){let o=t[n];if(!(typeof o>"u")&&!(r==="geopoint"&&typeof o=="object"&&typeof o.lon=="number"&&typeof o.lat=="number")&&!(r==="enum"&&(typeof o=="string"||typeof o=="number"))){if(r==="enum[]"&&Array.isArray(o)){let i=o.length;for(let s=0;s<i;s++)if(typeof o[s]!="string"&&typeof o[s]!="number")return n+"."+s;continue}if(ov(r)){let i=oge(r);if(!Array.isArray(o)||o.length!==i)throw qt("INVALID_INPUT_VECTOR",n,i,o.length);continue}if(FN(r)){if(!Array.isArray(o))return n;let i=rge(r),s=o.length;for(let a=0;a<s;a++)if(typeof o[a]!==i)return n+"."+a;continue}if(typeof r=="object"){if(!o||typeof o!="object")return n;let i=nge(o,r);if(i)return n+"."+i;continue}if(typeof o!==r)return n}}}function X3e(t){return t==="geopoint"}function ov(t){return typeof t=="string"&&/^vector\[\d+\]$/.test(t)}function FN(t){return typeof t=="string"&&K$t[t]}function rge(t){return q$t[t]}function oge(t){let e=Number(t.slice(7,-1));switch(!0){case isNaN(e):throw qt("INVALID_VECTOR_VALUE",t);case e<=0:throw qt("INVALID_VECTOR_SIZE",t);default:return e}}var K$t,q$t,YU=C(()=>{Ua();ss();ss();K$t={string:!1,number:!1,boolean:!1,enum:!1,geopoint:!1,"string[]":!0,"number[]":!0,"boolean[]":!0,"enum[]":!0},q$t={"string[]":"string","number[]":"number","boolean[]":"boolean","enum[]":"enum"}});function Q3e(){return{idToInternalId:new Map,internalIdToId:[],save:G$t,load:Y$t}}function G$t(t){return{internalIdToId:t.internalIdToId}}function Y$t(t,e){let{internalIdToId:n}=e;t.internalDocumentIDStore.idToInternalId.clear(),t.internalDocumentIDStore.internalIdToId=[];let r=n.length;for(let o=0;o<r;o++){let i=n[o];t.internalDocumentIDStore.idToInternalId.set(i,o+1),t.internalDocumentIDStore.internalIdToId.push(i)}}function mo(t,e){if(typeof e=="string"){let n=t.idToInternalId.get(e);if(n)return n;let r=t.idToInternalId.size+1;return t.idToInternalId.set(e,r),t.internalIdToId.push(e),r}return e>t.internalIdToId.length?mo(t,e.toString()):e}function vp(t,e){if(t.internalIdToId.length<e)throw new Error(`Invalid internalId ${e}`);return t.internalIdToId[e-1]}var xp=C(()=>{});function J$t(t,e){return{sharedInternalDocumentStore:e,docs:{},count:0}}function X$t(t,e){let n=mo(t.sharedInternalDocumentStore,e);return t.docs[n]}function Q$t(t,e){let n=e.length,r=Array.from({length:n});for(let o=0;o<n;o++){let i=mo(t.sharedInternalDocumentStore,e[o]);r[o]=t.docs[i]}return r}function eFt(t){return t.docs}function tFt(t,e,n){let r=mo(t.sharedInternalDocumentStore,e);return typeof t.docs[r]<"u"?!1:(t.docs[r]=n,t.count++,!0)}function nFt(t,e){let n=mo(t.sharedInternalDocumentStore,e);return typeof t.docs[n]>"u"?!1:(delete t.docs[n],t.count--,!0)}function rFt(t){return t.count}function oFt(t,e){let n=e;return{docs:n.docs,count:n.count,sharedInternalDocumentStore:t}}function iFt(t){return{docs:t.docs,count:t.count}}function eKe(){return{create:J$t,get:X$t,getMultiple:Q$t,getAll:eFt,store:tFt,remove:nFt,count:rFt,load:oFt,save:iFt}}var ige=C(()=>{xp()});function nKe(t,e){let n=[],r=t.plugins?.length;if(!r)return n;for(let o=0;o<r;o++)try{let i=t.plugins[o];typeof i[e]=="function"&&n.push(i[e])}catch(i){throw console.error("Caught error in getAllPluginsByHook:",i),qt("PLUGIN_CRASHED")}return n}var tKe,rKe=C(()=>{Ua();tKe=["beforeInsert","afterInsert","beforeRemove","afterRemove","beforeUpdate","afterUpdate","beforeSearch","afterSearch","beforeInsertMultiple","afterInsertMultiple","beforeRemoveMultiple","afterRemoveMultiple","beforeUpdateMultiple","afterUpdateMultiple","beforeLoad","afterLoad","afterCreate"]});function Qm(t,e,n,r){if(t.some(Ss))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function a0(t,e,n){if(t.some(Ss))return(async()=>{for(let o of t)await o(e,n)})();for(let o of t)o(e,n)}function UN(t,e,n,r,o){if(t.some(Ss))return(async()=>{for(let s of t)await s(e,n,r,o)})();for(let s of t)s(e,n,r,o)}function BN(t,e,n,r){if(t.some(Ss))return(async()=>{for(let i of t)await i(e,n,r)})();for(let i of t)i(e,n,r)}function iKe(t,e){if(t.some(Ss))return(async()=>{for(let r of t)await r(e)})();for(let r of t)r(e)}var oKe,sge,CC=C(()=>{ss();oKe=["tokenizer","index","documentsStore","sorter"],sge=["validateSchema","getDocumentIndexId","getDocumentProperties","formatElapsedTime"]});function age(t){let e=t.r;return t.r=e.l,e.l=t,t.h=Math.max(bp(t.l),bp(t.r))+1,e.h=Math.max(bp(e.l),bp(e.r))+1,e}function lge(t){let e=t.l;return t.l=e.r,e.r=t,t.h=Math.max(bp(t.l),bp(t.r))+1,e.h=Math.max(bp(e.l),bp(e.r))+1,e}function aKe(t,e,n){let r=[];function o(i){i!==null&&(e<i.k&&o(i.l),i.k>=e&&i.k<=n&&So(r,i.v),n>i.k&&o(i.r))}return o(t.root),r}function cge(t,e,n=!1){let r=[];if(t===null)return r;let o=[t.root];for(;o.length>0;){let i=o.pop();i&&(n&&i.k>=e&&So(r,i.v),!n&&i.k>e&&So(r,i.v),o.push(i.r),o.push(i.l))}return r}function uge(t,e,n=!1){let r=[];if(t===null)return r;let o=[t.root];for(;o.length>0;){let i=o.pop();i&&(n&&i.k<=e&&So(r,i.v),!n&&i.k<e&&So(r,i.v),o.push(i.r),o.push(i.l))}return r}function lKe(t,e){for(;t!==null;)if(e<t.k)t=t.l;else if(e>t.k)t=t.r;else return t;return null}function cKe(t,e){return{root:{k:t,v:e,l:null,r:null,h:0}}}function uKe(t,e,n,r=500){function o(i,s,a){if(i===null)return sKe++,{k:s,v:a,l:null,r:null,h:0};if(s<i.k)i.l=o(i.l,s,a);else if(s>i.k)i.r=o(i.r,s,a);else return i.v.push(...a),i;return sKe%r===0?aFt(i,s):i}t.root=o(t.root,e,n)}function aFt(t,e){t.h=1+Math.max(bp(t.l),bp(t.r));let n=bp(t.l)-bp(t.r);return n>1&&e<t.l.k?lge(t):n<-1&&e>t.r.k?age(t):n>1&&e>t.l.k?(t.l=age(t.l),lge(t)):n<-1&&e<t.r.k?(t.r=lge(t.r),age(t)):t}function bp(t){return t!==null?t.h:-1}function dKe(t,e){let n=lKe(t.root,e);return n===null?null:n.v}function lFt(t,e){if(t===null||t.root===null)return;let n=t.root,r=null;for(;n!=null&&n.k!==e;)r=n,e<n.k?n=n.l:n=n.r;if(n===null)return;(()=>{if(n.l===null&&n.r===null)r===null?t.root=null:r.l===n?r.l=null:r.r=null;else if(n.l!=null&&n.r!=null){let i=n.r,s=n;for(;i.l!=null;)s=i,i=i.l;n.k=i.k,s===n?s.r=i.r:s.l=i.r}else{let i=n.l!=null?n.l:n.r;r===null?t.root=i:r.l===n?r.l=i:r.r=i}})()}function fKe(t,e,n){let r=lKe(t.root,n);if(r){if(r.v.length===1){lFt(t,n);return}r.v.splice(r.v.indexOf(e),1)}}var sKe,pKe=C(()=>{ss();sKe=0});function mKe(){return{numberToDocumentId:new Map}}function hKe(t,e,n){return t.numberToDocumentId.has(e)?(t.numberToDocumentId.get(e).push(n),t):(t.numberToDocumentId.set(e,[n]),t)}function gKe(t,e,n){t?.numberToDocumentId.set(n,t?.numberToDocumentId.get(n)?.filter(r=>r!==e)??[]),t?.numberToDocumentId.get(n)?.length===0&&t?.numberToDocumentId.delete(n)}function yKe(t,e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"eq":{let o=e[r];return t.numberToDocumentId.get(o)??[]}case"in":{let o=e[r],i=[];for(let s of o){let a=t.numberToDocumentId.get(s);a!=null&&So(i,a)}return i}case"nin":{let o=e[r],i=[],s=t.numberToDocumentId.keys();for(let a of s){if(o.includes(a))continue;let l=t.numberToDocumentId.get(a);l!=null&&So(i,l)}return i}}throw new Error("Invalid operation")}function wKe(t,e){let n=Object.keys(e);if(n.length!==1)throw new Error("Invalid operation");let r=n[0];switch(r){case"containsAll":{let i=e[r].map(s=>t.numberToDocumentId.get(s)??[]);return DN(i)}}throw new Error("Invalid operation")}var vKe=C(()=>{ss()});function cFt(t,e,n){if(n<0)return-1;if(t===e)return 0;let r=t.length,o=e.length;if(r===0)return o<=n?o:-1;if(o===0)return r<=n?r:-1;if(t=t.toLowerCase(),e=e.toLowerCase(),e.startsWith(t)||t.startsWith(e))return 0;if(Math.abs(r-o)>n)return-1;let i=[];for(let s=0;s<=r;s++){i[s]=[s];for(let a=1;a<=o;a++)i[s][a]=s===0?a:0}for(let s=1;s<=r;s++){let a=1/0;for(let l=1;l<=o;l++)t[s-1]===e[l-1]?i[s][l]=i[s-1][l-1]:i[s][l]=Math.min(i[s-1][l]+1,i[s][l-1]+1,i[s-1][l-1]+1),a=Math.min(a,i[s][l]);if(a>n)return-1}return i[r][o]<=n?i[r][o]:-1}function dge(t,e,n){let r=cFt(t,e,n);return{distance:r,isBounded:r>=0}}var fge=C(()=>{});function zN(t,e){t.w=e.w+t.s}function Hq(t,e){t.d.push(e)}function uFt(t,e){let n=t.d.indexOf(e);return n===-1?!1:(t.d.splice(n,1),!0)}function mge(t,e,n,r,o){if(t.e){let{w:i,d:s}=t;if(r&&i!==n)return{};if(LN(e,i)==null&&(o?Math.abs(n.length-i.length)<=o&&dge(n,i,o).isBounded&&(e[i]=[]):e[i]=[]),LN(e,i)!=null&&s.length>0){let a=new Set(e[i]),l=s.length;for(let c=0;c<l;c++)a.add(s[c]);e[i]=Array.from(a)}}for(let i of Object.keys(t.c))mge(t.c[i],e,n,r,o);return e}function xKe(t,e){let n="",r=Math.min(t.length,e.length);for(let o=0;o<r;o++){if(t[o]!==e[o])return n;n+=t[o]}return n}function l0(t=!1,e="",n=""){return new pge(n,e,t)}function bKe(t,e,n){let r=e.length;for(let o=0;o<r;o++){let i=e[o],s=e.substring(o),a=t.c[i];if(a){let l=a.s,c=l.length,u=xKe(l,s),d=u.length;if(l===s){Hq(a,n),a.e=!0;return}let f=l[d];if(d<c&&d===s.length){let p=l0(!0,s,i);p.c[f]=a;let m=p.c[f];m.s=l.substring(d),m.k=f,t.c[i]=p,zN(p,t),zN(m,p),Hq(p,n);return}if(d<c&&d<s.length){let p=l0(!1,u,i);p.c[f]=a,t.c[i]=p;let m=p.c[f];m.s=l.substring(d),m.k=f;let h=s[d],g=l0(!0,e.substring(o+d),h);Hq(g,n),p.c[h]=g,zN(p,t),zN(g,p),zN(m,p);return}o+=c-1,t=a}else{let l=l0(!0,s,i);Hq(l,n),t.c[i]=l,zN(l,t);return}}}function ZU(t,e,n,r,o,i){if(!(r<0)){if(t.w.startsWith(e)){mge(t,i,e,!1,0);return}if(t.e){let{w:s,d:a}=t;if(s&&(dge(e,s,o).isBounded&&(i[s]=[]),LN(i,s)!=null&&a.length>0)){let l=new Set(i[s]),c=a.length;for(let u=0;u<c;u++)l.add(a[u]);i[s]=Array.from(l)}}if(!(n>=e.length)){e[n]in t.c&&ZU(t.c[e[n]],e,n+1,r,o,i),ZU(t,e,n+1,r-1,o,i);for(let s in t.c)ZU(t.c[s],e,n,r-1,o,i);for(let s in t.c)s!==e[n]&&ZU(t.c[s],e,n+1,r-1,o,i)}}}function hge(t,{term:e,exact:n,tolerance:r}){if(r&&!n){let o={};return r=r||0,ZU(t,e,0,r||0,r,o),o}else{let o=e.length;for(let s=0;s<o;s++){let a=e[s];if(a in t.c){let l=t.c[a],c=l.s,u=e.substring(s),f=xKe(c,u).length;if(f!==c.length&&f!==u.length){if(r)break;return{}}s+=l.s.length-1,t=l}else return{}}let i={};return mge(t,i,e,n,r),i}}function CKe(t,e,n,r=!0){if(!e)return!0;let o=e.length;for(let i=0;i<o;i++){let s=e[i];if(s in t.c){let a=t.c[s];i+=a.s.length-1,t=a,r&&t.w!==e||uFt(t,n)}else return!1}return!0}var pge,_Ke=C(()=>{fge();ss();pge=class{constructor(e,n,r){I(this,"k");I(this,"s");I(this,"c",{});I(this,"d",[]);I(this,"e");I(this,"w","");this.k=e,this.s=n,this.e=r}toJSON(){return{w:this.w,s:this.s,c:this.c,d:this.d,e:this.e}}}});function SKe(){return{root:null}}function TKe(t,e,n){let r={point:e,docIDs:n};if(t.root==null){t.root=r;return}let o=t.root,i=0;for(;o!==null;){if(o.point.lon===e.lon&&o.point.lat===e.lat){let a=o.docIDs??[];o.docIDs=Array.from(new Set([...a,...n||[]]));return}if(i%2===0)if(e.lon<o.point.lon){if(o.left==null){o.left=r;return}o=o.left}else{if(o.right==null){o.right=r;return}o=o.right}else if(e.lat<o.point.lat){if(o.left==null){o.left=r;return}o=o.left}else{if(o.right==null){o.right=r;return}o=o.right}i++}}function IKe(t,e,n){let r=t.root,o=0,i=null,s=null;for(;r!==null;){if(r?.point.lon===e.lon&&r.point.lat===e.lat){let l=r.docIDs?.indexOf(n);if(l!==void 0&&l>-1){r.docIDs?.splice(l,1),(r.docIDs==null||r.docIDs.length===0)&&(i!=null?s==="left"?i.left=r.left!==null?r.left:r.right:s==="right"&&(i.right=r.right!==null?r.right:r.left):t.root=r.left!==null?r.left:r.right);return}}let a=o%2;i=r,a===0?e.lon<r.point.lon?(r=r?.left,s="left"):(r=r?.right,s="right"):e.lat<r.point.lat?(r=r?.left,s="left"):(r=r?.right,s="right"),o++}}function PKe(t,e,n,r=!0,o="asc",i=!1){let s=i?kKe:AKe,a=[{node:t,depth:0}],l=[];for(;a.length>0;){let{node:c,depth:u}=a.pop();if(c===null)continue;let d=s(e,c.point);(r?d<=n:d>n)&&l.push({point:c.point,docIDs:c.docIDs??[]}),c.left!=null&&a.push({node:c.left,depth:u+1}),c.right!=null&&a.push({node:c.right,depth:u+1})}return o&&l.sort((c,u)=>{let d=s(e,c.point),f=s(e,u.point);return o.toLowerCase()==="asc"?d-f:f-d}),l}function EKe(t,e,n=!0,r=null,o=!1){let i=[{node:t,depth:0}],s=[];for(;i.length>0;){let l=i.pop();if(l==null||l.node==null)continue;let{node:c,depth:u}=l,d=u+1;c.left!=null&&i.push({node:c.left,depth:d}),c.right!=null&&i.push({node:c.right,depth:d});let f=fFt(e,c.point);f&&n?s.push({point:c.point,docIDs:c.docIDs??[]}):!f&&!n&&s.push({point:c.point,docIDs:c.docIDs??[]})}let a=dFt(e);if(r){let l=o?kKe:AKe;s.sort((c,u)=>{let d=l(a,c.point),f=l(a,u.point);return r.toLowerCase()==="asc"?d-f:f-d})}return s}function dFt(t){let e=0,n=0,r=0,o=t.length;for(let s=0,a=o-1;s<o;a=s++){let l=t[s].lon,c=t[s].lat,u=t[a].lon,d=t[a].lat,f=l*d-u*c;e+=f,n+=(l+u)*f,r+=(c+d)*f}e/=2;let i=6*e;return n/=i,r/=i,{lon:n,lat:r}}function fFt(t,e){let n=!1,r=e.lon,o=e.lat,i=t.length;for(let s=0,a=i-1;s<i;a=s++){let l=t[s].lon,c=t[s].lat,u=t[a].lon,d=t[a].lat;c>o!=d>o&&r<(u-l)*(o-c)/(d-c)+l&&(n=!n)}return n}function AKe(t,e){let n=Math.PI/180,r=t.lat*n,o=e.lat*n,i=(e.lat-t.lat)*n,s=(e.lon-t.lon)*n,a=Math.sin(i/2)*Math.sin(i/2)+Math.cos(r)*Math.cos(o)*Math.sin(s/2)*Math.sin(s/2);return 6371e3*(2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)))}function kKe(t,e){let r=.0033528106647474805,o=(1-r)*6378137,i=Math.PI/180,s=t.lat*i,a=e.lat*i,l=(e.lon-t.lon)*i,c=Math.atan((1-r)*Math.tan(s)),u=Math.atan((1-r)*Math.tan(a)),d=Math.sin(c),f=Math.cos(c),p=Math.sin(u),m=Math.cos(u),h=l,g,y=1e3,w,v,x,b,_;do{let D=Math.sin(h),$=Math.cos(h);x=Math.sqrt(m*D*(m*D)+(f*p-d*m*$)*(f*p-d*m*$)),b=d*p+f*m*$,_=Math.atan2(x,b),w=f*m*D/x,v=1-w*w;let B=b-2*d*p/v,W=r/16*v*(4+r*(4-3*v));g=h,h=l+(1-W)*r*w*(_+W*x*(B+W*b*(-1+2*B*B)))}while(Math.abs(h-g)>1e-12&&--y>0);let T=v*(6378137*6378137-o*o)/(o*o),S=1+T/16384*(4096+T*(-768+T*(320-175*T))),P=T/1024*(256+T*(-128+T*(74-47*T))),A=P*x*(b-2*d*p/v+P/4*(b*(-1+2*x*x)-P/6*_*(-3+4*x*x)*(-3+4*_*_)));return o*S*(_-A)}var MKe=C(()=>{});function Kq(t,e,n=0,r){if(e===0)throw qt("INVALID_BOOST_VALUE");let o=new Map,i=t.length;for(let h=0;h<i;h++){let g=t[h],y=g.length;for(let w=0;w<y;w++){let[v,x]=g[w],b=x*e,_=o.get(v)?.[0];_!==void 0?o.set(v,[_*1.5+b,(o?.get(v)?.[1]||0)+1]):o.set(v,[b,1])}}let s=[];for(let h of o.entries())s.push([h[0],h[1][0]]);let a=s.sort((h,g)=>g[1]-h[1]);if(n===1)return a;let l=a.length,c=[];for(let h of o.entries())c.push([h[0],h[1][0],h[1][1]]);let u=c.sort((h,g)=>h[2]>g[2]?-1:h[2]<g[2]?1:h[1]>g[1]?-1:h[1]<g[1]?1:0),d;for(let h=0;h<l&&u[h][2]===r;h++)d=h;if(typeof d>"u"){if(n===0)return[];d=0}let f=u.length,p=new Array(f);for(let h=0;h<f;h++)p[h]=[u[h][0],u[h][1]];if(n===0)return p.slice(0,d+1);let m=d+Math.ceil(n*100*(l-d)/100);return p.slice(0,l+m)}function gge(t,e,n,r,o,{k:i,b:s,d:a}){return Math.log(1+(n-e+.5)/(e+.5))*(a+t*(i+1))/(t+i*(1-s+s*r/o))}var JU=C(()=>{Ua()});function yge(t,e){let n=0;for(let r=0;r<e;r++)n+=t[r]*t[r];return Math.sqrt(n)}function qq(t,e,n,r=.8){let o=yge(t,n),i=[];for(let[s,[a,l]]of Object.entries(e)){let c=0;for(let d=0;d<n;d++)c+=t[d]*l[d];let u=c/(o*a);u>=r&&i.push([s,u])}return i.sort((s,a)=>a[1]-s[1])}var Gq=C(()=>{});function pFt(t,e,n,r,o){let i=mo(t.sharedInternalDocumentStore,n);t.avgFieldLength[e]=((t.avgFieldLength[e]??0)*(o-1)+r.length)/o,t.fieldLengths[e][i]=r.length,t.frequencies[e][i]={}}function mFt(t,e,n,r,o){let i=0;for(let l of r)l===o&&i++;let s=mo(t.sharedInternalDocumentStore,n),a=i/r.length;t.frequencies[e][s][o]=a,o in t.tokenOccurrences[e]||(t.tokenOccurrences[e][o]=0),t.tokenOccurrences[e][o]=(t.tokenOccurrences[e][o]??0)+1}function hFt(t,e,n,r){let o=mo(t.sharedInternalDocumentStore,n);r>1?t.avgFieldLength[e]=(t.avgFieldLength[e]*r-t.fieldLengths[e][o])/(r-1):t.avgFieldLength[e]=void 0,t.fieldLengths[e][o]=void 0,t.frequencies[e][o]=void 0}function gFt(t,e,n){t.tokenOccurrences[e][n]--}function yFt(t,e,n,r,o){let i=Array.from(o),s=e.avgFieldLength[n],a=e.fieldLengths[n],l=e.tokenOccurrences[n],c=e.frequencies[n],u=typeof l[r]=="number"?l[r]??0:0,d=[],f=i.length;for(let p=0;p<f;p++){let m=mo(e.sharedInternalDocumentStore,i[p]),h=c?.[m]?.[r]??0,g=gge(h,u,t.docsCount,a[m],s,t.params.relevance);d.push([m,g])}return d}function OKe(t,e,n,r,o=""){r||(r={sharedInternalDocumentStore:e,indexes:{},vectorIndexes:{},searchableProperties:[],searchablePropertiesWithTypes:{},frequencies:{},tokenOccurrences:{},avgFieldLength:{},fieldLengths:{}});for(let[i,s]of Object.entries(n)){let a=`${o}${o?".":""}${i}`;if(typeof s=="object"&&!Array.isArray(s)){OKe(t,e,s,r,a);continue}if(ov(s))r.searchableProperties.push(a),r.searchablePropertiesWithTypes[a]=s,r.vectorIndexes[a]={size:oge(s),vectors:{}};else{let l=/\[/.test(s);switch(s){case"boolean":case"boolean[]":r.indexes[a]={type:"Bool",node:{true:[],false:[]},isArray:l};break;case"number":case"number[]":r.indexes[a]={type:"AVL",node:cKe(0,[]),isArray:l};break;case"string":case"string[]":r.indexes[a]={type:"Radix",node:l0(),isArray:l},r.avgFieldLength[a]=0,r.frequencies[a]={},r.tokenOccurrences[a]={},r.fieldLengths[a]={};break;case"enum":case"enum[]":r.indexes[a]={type:"Flat",node:mKe(),isArray:l};break;case"geopoint":r.indexes[a]={type:"BKD",node:SKe(),isArray:l};break;default:throw qt("INVALID_SCHEMA_TYPE",Array.isArray(s)?"array":s,a)}r.searchableProperties.push(a),r.searchablePropertiesWithTypes[a]=s}}return r}function wFt(t,e,n,r,o,i,s,a){return l=>{let c=mo(e.sharedInternalDocumentStore,r),{type:u,node:d}=e.indexes[n];switch(u){case"Bool":{d[l?"true":"false"].push(c);break}case"AVL":{let f=a?.avlRebalanceThreshold??1;uKe(d,l,[c],f);break}case"Radix":{let f=i.tokenize(l,o,n);t.insertDocumentScoreParameters(e,n,c,f,s);for(let p of f)t.insertTokenScoreParameters(e,n,c,f,p),bKe(d,p,c);break}case"Flat":{hKe(d,l,c);break}case"BKD":{TKe(d,l,[c]);break}}}}function vFt(t,e,n,r,o,i,s,a,l,c){if(ov(i))return xFt(e,n,o,r);let u=wFt(t,e,n,r,s,a,l,c);if(!FN(i))return u(o);let d=o,f=d.length;for(let p=0;p<f;p++)u(d[p])}function xFt(t,e,n,r){n instanceof Float32Array||(n=new Float32Array(n));let o=t.vectorIndexes[e].size,i=yge(n,o);t.vectorIndexes[e].vectors[r]=[i,n]}function NKe(t,e,n,r,o,i,s,a,l){let c=mo(e.sharedInternalDocumentStore,r);if(ov(i))return delete e.vectorIndexes[n].vectors[r],!0;let{type:u,node:d}=e.indexes[n];switch(u){case"AVL":return fKe(d,c,o),!0;case"Bool":{let p=d[o?"true":"false"].indexOf(c);return d[o?"true":"false"].splice(p,1),!0}case"Radix":{let f=a.tokenize(o,s,n);t.removeDocumentScoreParameters(e,n,r,l);for(let p of f)t.removeTokenScoreParameters(e,n,p),CKe(d,p,c);return!0}case"Flat":return gKe(d,c,o),!0;case"BKD":return IKe(d,o,c),!1}}function bFt(t,e,n,r,o,i,s,a,l){if(!FN(i))return NKe(t,e,n,r,o,i,s,a,l);let c=rge(i),u=o,d=u.length;for(let f=0;f<d;f++)NKe(t,e,n,r,u[f],c,s,a,l);return!0}function CFt(t,e,n,r){if(!(n in e.tokenOccurrences))return[];let{node:o,type:i}=e.indexes[n];if(i!=="Radix")throw qt("WRONG_SEARCH_PROPERTY_TYPE",n);let{exact:s,tolerance:a}=t.params,l=hge(o,{term:r,exact:s,tolerance:a}),c=new Set;for(let u in l)if(LN(l,u))for(let f of l[u])c.add(f);return t.index.calculateResultScores(t,e,n,r,Array.from(c))}function _Ft(t,e,n){let r=Object.keys(n),o=r.reduce((i,s)=>({[s]:[],...i}),{});for(let i of r){let s=n[i];if(typeof e.indexes[i]>"u")throw qt("UNKNOWN_FILTER_PROPERTY",i);let{node:a,type:l,isArray:c}=e.indexes[i];if(l==="Bool"){let f=a[s.toString()];So(o[i],f);continue}if(l==="BKD"){let d;if("radius"in s)d="radius";else if("polygon"in s)d="polygon";else throw new Error(`Invalid operation ${s}`);if(d==="radius"){let{value:f,coordinates:p,unit:m="m",inside:h=!0,highPrecision:g=!1}=s[d],y=tge(f,m),w=PKe(a.root,p,y,h,void 0,g);So(o[i],w.flatMap(({docIDs:v})=>v))}else{let{coordinates:f,inside:p=!0,highPrecision:m=!1}=s[d],h=EKe(a.root,f,p,void 0,m);So(o[i],h.flatMap(({docIDs:g})=>g))}continue}if(l==="Radix"&&(typeof s=="string"||Array.isArray(s))){for(let d of[s].flat()){let f=t.tokenizer.tokenize(d,t.language,i);for(let p of f){let m=hge(a,{term:p,exact:!0});So(o[i],Object.values(m).flat())}}continue}let u=Object.keys(s);if(u.length>1)throw qt("INVALID_FILTER_OPERATION",u.length);if(l==="Flat"){let d=c?wKe:yKe;So(o[i],d(a,s));continue}if(l==="AVL"){let d=u[0],f=s[d],p=[];switch(d){case"gt":{p=cge(a,f,!1);break}case"gte":{p=cge(a,f,!0);break}case"lt":{p=uge(a,f,!1);break}case"lte":{p=uge(a,f,!0);break}case"eq":{p=dKe(a,f)??[];break}case"between":{let[m,h]=f;p=aKe(a,m,h);break}}So(o[i],p)}}return DN(Object.values(o))}function SFt(t){return t.searchableProperties}function TFt(t){return t.searchablePropertiesWithTypes}function RKe(t){let e=l0(t.e,t.s,t.k);e.d=t.d,e.w=t.w;for(let n of Object.keys(t.c))e.c[n]=RKe(t.c[n]);return e}function IFt(t){return{numberToDocumentId:new Map(t)}}function PFt(t){return Array.from(t.numberToDocumentId.entries())}function EFt(t,e){let{indexes:n,vectorIndexes:r,searchableProperties:o,searchablePropertiesWithTypes:i,frequencies:s,tokenOccurrences:a,avgFieldLength:l,fieldLengths:c}=e,u={},d={};for(let f of Object.keys(n)){let{node:p,type:m,isArray:h}=n[f];switch(m){case"Radix":u[f]={type:"Radix",node:RKe(p),isArray:h};break;case"Flat":u[f]={type:"Flat",node:IFt(p),isArray:h};break;default:u[f]=n[f]}}for(let f of Object.keys(r)){let p=r[f].vectors;for(let m in p)p[m]=[p[m][0],new Float32Array(p[m][1])];d[f]={size:r[f].size,vectors:p}}return{sharedInternalDocumentStore:t,indexes:u,vectorIndexes:d,searchableProperties:o,searchablePropertiesWithTypes:i,frequencies:s,tokenOccurrences:a,avgFieldLength:l,fieldLengths:c}}function AFt(t){let{indexes:e,vectorIndexes:n,searchableProperties:r,searchablePropertiesWithTypes:o,frequencies:i,tokenOccurrences:s,avgFieldLength:a,fieldLengths:l}=t,c={};for(let d of Object.keys(n)){let f=n[d].vectors;for(let p in f)f[p]=[f[p][0],Array.from(f[p][1])];c[d]={size:n[d].size,vectors:f}}let u={};for(let d of Object.keys(e)){let{type:f,node:p,isArray:m}=e[d];if(f!=="Flat"){u[d]=e[d];continue}u[d]={type:"Flat",node:PFt(p),isArray:m}}return{indexes:u,vectorIndexes:c,searchableProperties:r,searchablePropertiesWithTypes:o,frequencies:i,tokenOccurrences:s,avgFieldLength:a,fieldLengths:l}}function LKe(){return{create:OKe,insert:vFt,remove:bFt,insertDocumentScoreParameters:pFt,insertTokenScoreParameters:mFt,removeDocumentScoreParameters:hFt,removeTokenScoreParameters:gFt,calculateResultScores:yFt,search:CFt,searchByWhereClause:_Ft,getSearchableProperties:SFt,getSearchablePropertiesWithTypes:TFt,load:EFt,save:AFt}}var wge=C(()=>{Ua();pKe();vKe();_Ke();MKe();ss();JU();Gq();YU();xp()});function DKe(t,e,n,r,o){let i={language:t.tokenizer.language,sharedInternalDocumentStore:e,enabled:!0,isSorted:!0,sortableProperties:[],sortablePropertiesWithTypes:{},sorts:{}};for(let[s,a]of Object.entries(n)){let l=`${o}${o?".":""}${s}`;if(!r.includes(l)){if(typeof a=="object"&&!Array.isArray(a)){let c=DKe(t,e,a,r,l);So(i.sortableProperties,c.sortableProperties),i.sorts={...i.sorts,...c.sorts},i.sortablePropertiesWithTypes={...i.sortablePropertiesWithTypes,...c.sortablePropertiesWithTypes};continue}if(!ov(a))switch(a){case"boolean":case"number":case"string":i.sortableProperties.push(l),i.sortablePropertiesWithTypes[l]=a,i.sorts[l]={docs:new Map,orderedDocsToRemove:new Map,orderedDocs:[],type:a};break;case"geopoint":case"enum":continue;case"enum[]":case"boolean[]":case"number[]":case"string[]":continue;default:throw qt("INVALID_SORT_SCHEMA_TYPE",Array.isArray(a)?"array":a,l)}}}return i}function MFt(t,e,n,r){return r?.enabled!==!1?DKe(t,e,n,(r||{}).unsortableProperties||[],""):{disabled:!0}}function NFt(t,e,n,r){if(!t.enabled)return;t.isSorted=!1;let o=mo(t.sharedInternalDocumentStore,n),i=t.sorts[e];i.orderedDocsToRemove.has(o)&&vge(t,e),i.docs.set(o,i.orderedDocs.length),i.orderedDocs.push([o,r])}function $Ke(t){if(t.isSorted||!t.enabled)return;let e=Object.keys(t.sorts);for(let n of e)DFt(t,n);t.isSorted=!0}function OFt(t,e,n){return e[1].localeCompare(n[1],V3e(t))}function RFt(t,e){return t[1]-e[1]}function LFt(t,e){return e[1]?-1:1}function DFt(t,e){let n=t.sorts[e],r;switch(n.type){case"string":r=OFt.bind(null,t.language);break;case"number":r=RFt.bind(null);break;case"boolean":r=LFt.bind(null);break}n.orderedDocs.sort(r);let o=n.orderedDocs.length;for(let i=0;i<o;i++){let s=n.orderedDocs[i][0];n.docs.set(s,i)}}function $Ft(t){let e=Object.keys(t.sorts);for(let n of e)vge(t,n)}function vge(t,e){let n=t.sorts[e];n.orderedDocsToRemove.size&&(n.orderedDocs=n.orderedDocs.filter(r=>!n.orderedDocsToRemove.has(r[0])),n.orderedDocsToRemove.clear())}function FFt(t,e,n){if(!t.enabled)return;let r=t.sorts[e],o=mo(t.sharedInternalDocumentStore,n);r.docs.get(o)&&(r.docs.delete(o),r.orderedDocsToRemove.set(o,!0))}function UFt(t,e,n){if(!t.enabled)throw qt("SORT_DISABLED");let r=n.property,o=n.order==="DESC",i=t.sorts[r];if(!i)throw qt("UNABLE_TO_SORT_ON_UNKNOWN_FIELD",r,t.sortableProperties.join(", "));return vge(t,r),$Ke(t),e.sort((s,a)=>{let l=i.docs.get(mo(t.sharedInternalDocumentStore,s[0])),c=i.docs.get(mo(t.sharedInternalDocumentStore,a[0])),u=typeof l<"u",d=typeof c<"u";return!u&&!d?0:u?d?o?c-l:l-c:-1:1}),e}function BFt(t){return t.enabled?t.sortableProperties:[]}function zFt(t){return t.enabled?t.sortablePropertiesWithTypes:{}}function jFt(t,e){let n=e;if(!n.enabled)return{enabled:!1};let r=Object.keys(n.sorts).reduce((o,i)=>{let{docs:s,orderedDocs:a,type:l}=n.sorts[i];return o[i]={docs:new Map(Object.entries(s).map(([c,u])=>[+c,u])),orderedDocsToRemove:new Map,orderedDocs:a,type:l},o},{});return{sharedInternalDocumentStore:t,language:n.language,sortableProperties:n.sortableProperties,sortablePropertiesWithTypes:n.sortablePropertiesWithTypes,sorts:r,enabled:!0,isSorted:n.isSorted}}function VFt(t){if(!t.enabled)return{enabled:!1};$Ft(t),$Ke(t);let e=Object.keys(t.sorts).reduce((n,r)=>{let{docs:o,orderedDocs:i,type:s}=t.sorts[r];return n[r]={docs:Object.fromEntries(o.entries()),orderedDocs:i,type:s},n},{});return{language:t.language,sortableProperties:t.sortableProperties,sortablePropertiesWithTypes:t.sortablePropertiesWithTypes,sorts:e,enabled:t.enabled,isSorted:t.isSorted}}function FKe(){return{create:MFt,insert:NFt,remove:FFt,save:VFt,load:jFt,sortBy:UFt,getSortableProperties:BFt,getSortablePropertiesWithTypes:zFt}}var xge=C(()=>{Ua();YU();xp();ss();jq()});function KFt(t){return t<192||t>383?t:HFt[t-192]||t}function UKe(t){let e=[];for(let n=0;n<t.length;n++)e[n]=KFt(t.charCodeAt(n));return String.fromCharCode(...e)}var HFt,BKe=C(()=>{HFt=[65,65,65,65,65,65,65,67,69,69,69,69,73,73,73,73,69,78,79,79,79,79,79,null,79,85,85,85,85,89,80,115,97,97,97,97,97,97,97,99,101,101,101,101,105,105,105,105,101,110,111,111,111,111,111,null,111,117,117,117,117,121,112,121,65,97,65,97,65,97,67,99,67,99,67,99,67,99,68,100,68,100,69,101,69,101,69,101,69,101,69,101,71,103,71,103,71,103,71,103,72,104,72,104,73,105,73,105,73,105,73,105,73,105,73,105,74,106,75,107,107,76,108,76,108,76,108,76,108,76,108,78,110,78,110,78,110,110,78,110,79,111,79,111,79,111,79,111,82,114,82,114,82,114,83,115,83,115,83,115,83,115,84,116,84,116,84,116,85,117,85,117,85,117,85,117,85,117,85,117,87,119,89,121,89,90,122,90,122,90,122,115]});function jKe(t){let e,n,r,o,i,s;if(t.length<3)return t;let a=t.substring(0,1);if(a=="y"&&(t=a.toUpperCase()+t.substring(1)),r=/^(.+?)(ss|i)es$/,o=/^(.+?)([^s])s$/,r.test(t)?t=t.replace(r,"$1$2"):o.test(t)&&(t=t.replace(o,"$1$2")),r=/^(.+?)eed$/,o=/^(.+?)(ed|ing)$/,r.test(t)){let l=r.exec(t);r=new RegExp(bge),r.test(l[1])&&(r=/.$/,t=t.replace(r,""))}else o.test(t)&&(e=o.exec(t)[1],o=new RegExp(zKe),o.test(e)&&(t=e,o=/(at|bl|iz)$/,i=new RegExp("([^aeiouylsz])\\1$"),s=new RegExp("^"+Xg+Zq+"[^aeiouwxy]$"),o.test(t)?t=t+"e":i.test(t)?(r=/.$/,t=t.replace(r,"")):s.test(t)&&(t=t+"e")));if(r=/^(.+?)y$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(zKe),e&&r.test(e)&&(t=e+"i")),r=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,r.test(t)){let l=r.exec(t);e=l?.[1],n=l?.[2],r=new RegExp(bge),e&&r.test(e)&&(t=e+qFt[n])}if(r=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,r.test(t)){let l=r.exec(t);e=l?.[1],n=l?.[2],r=new RegExp(bge),e&&r.test(e)&&(t=e+GFt[n])}if(r=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/,o=/^(.+?)(s|t)(ion)$/,r.test(t))e=r.exec(t)?.[1],r=new RegExp(Yq),e&&r.test(e)&&(t=e);else if(o.test(t)){let l=o.exec(t);e=l?.[1]??""+l?.[2]??"",o=new RegExp(Yq),o.test(e)&&(t=e)}return r=/^(.+?)e$/,r.test(t)&&(e=r.exec(t)?.[1],r=new RegExp(Yq),o=new RegExp(ZFt),i=new RegExp("^"+Xg+Zq+"[^aeiouwxy]$"),e&&(r.test(e)||o.test(e)&&!i.test(e))&&(t=e)),r=/ll$/,o=new RegExp(Yq),r.test(t)&&o.test(t)&&(r=/.$/,t=t.replace(r,"")),a=="y"&&(t=a.toLowerCase()+t.substring(1)),t}var qFt,GFt,YFt,Zq,Xg,XU,bge,ZFt,Yq,zKe,VKe=C(()=>{qFt={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},GFt={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},YFt="[^aeiou]",Zq="[aeiouy]",Xg=YFt+"[^aeiouy]*",XU=Zq+"[aeiou]*",bge="^("+Xg+")?"+XU+Xg,ZFt="^("+Xg+")?"+XU+Xg+"("+XU+")?$",Yq="^("+Xg+")?"+XU+Xg+XU+Xg,zKe="^("+Xg+")?"+Zq});function Cge(t,e){let n=`${this.language}:${t}:${e}`;return this.normalizationCache.has(n)?this.normalizationCache.get(n):this.stopWords?.includes(e)?(this.normalizationCache.set(n,""),""):(this.stemmer&&!this.stemmerSkipProperties.has(t)&&(e=this.stemmer(e)),e=UKe(e),this.normalizationCache.set(n,e),e)}function JFt(t){for(;t[t.length-1]==="";)t.pop();for(;t[0]==="";)t.shift();return t}function WKe(t,e,n){if(e&&e!==this.language)throw qt("LANGUAGE_NOT_SUPPORTED",e);if(typeof t!="string")return[t];let r;if(n&&this.tokenizeSkipProperties.has(n))r=[this.normalizeToken.bind(this,n??"")(t)];else{let i=j3e[this.language];r=t.toLowerCase().split(i).map(this.normalizeToken.bind(this,n??"")).filter(Boolean)}let o=JFt(r);return this.allowDuplicates?o:Array.from(new Set(o))}function _ge(t={}){if(!t.language)t.language="english";else if(!qU.includes(t.language))throw qt("LANGUAGE_NOT_SUPPORTED",t.language);let e;if(t.stemming||t.stemmer&&!("stemming"in t))if(t.stemmer){if(typeof t.stemmer!="function")throw qt("INVALID_STEMMER_FUNCTION_TYPE");e=t.stemmer}else if(t.language==="english")e=jKe;else throw qt("MISSING_STEMMER",t.language);let n;if(t.stopWords!==!1){if(n=[],Array.isArray(t.stopWords))n=t.stopWords;else if(typeof t.stopWords=="function")n=t.stopWords(n);else if(t.stopWords)throw qt("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");if(!Array.isArray(n))throw qt("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY");for(let o of n)if(typeof o!="string")throw qt("CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY")}let r={tokenize:WKe,language:t.language,stemmer:e,stemmerSkipProperties:new Set(t.stemmerSkipProperties?[t.stemmerSkipProperties].flat():[]),tokenizeSkipProperties:new Set(t.tokenizeSkipProperties?[t.tokenizeSkipProperties].flat():[]),stopWords:n,allowDuplicates:!!t.allowDuplicates,normalizeToken:Cge,normalizationCache:new Map};return r.tokenize=WKe.bind(r),r.normalizeToken=Cge,r}var Jq=C(()=>{Ua();BKe();jq();VKe()});function QFt(t){let e={formatElapsedTime:Z3e,getDocumentIndexId:J3e,getDocumentProperties:Vq,validateSchema:nge};for(let n of sge){let r=n;if(t[r]){if(typeof t[r]!="function")throw qt("COMPONENT_MUST_BE_FUNCTION",r)}else t[r]=e[r]}for(let n of Object.keys(t))if(!oKe.includes(n)&&!sge.includes(n))throw qt("UNSUPPORTED_COMPONENT",n)}function jN({schema:t,sort:e,language:n,components:r,id:o,plugins:i}){r||(r={}),o||(o=GU());let s=r.tokenizer,a=r.index,l=r.documentsStore,c=r.sorter;if(s?s.tokenize?s=s:s=_ge(s):s=_ge({language:n??"english"}),r.tokenizer&&n)throw qt("NO_LANGUAGE_WITH_CUSTOM_TOKENIZER");let u=Q3e();a||(a=LKe()),c||(c=FKe()),l||(l=eKe()),QFt(r);let{getDocumentProperties:d,getDocumentIndexId:f,validateSchema:p,formatElapsedTime:m}=r,h={data:{},caches:{},schema:t,tokenizer:s,index:a,sorter:c,documentsStore:l,internalDocumentIDStore:u,getDocumentProperties:d,getDocumentIndexId:f,validateSchema:p,beforeInsert:[],afterInsert:[],beforeRemove:[],afterRemove:[],beforeUpdate:[],afterUpdate:[],beforeSearch:[],afterSearch:[],beforeInsertMultiple:[],afterInsertMultiple:[],beforeRemoveMultiple:[],afterRemoveMultiple:[],afterUpdateMultiple:[],beforeUpdateMultiple:[],afterCreate:[],formatElapsedTime:m,id:o,plugins:i,version:e2t()};h.data={index:h.index.create(h,u,t),docs:h.documentsStore.create(h,u),sorting:h.sorter.create(h,u,t,e)};for(let y of tKe)h[y]=(h[y]??[]).concat(nKe(h,y));let g=h.afterCreate;return g&&iKe(g,h),h}function e2t(){return"{{VERSION}}"}var HKe=C(()=>{YU();ige();rKe();CC();wge();xp();xge();Jq();Ua();ss()});var KKe=C(()=>{});var Sge=C(()=>{YU();ige();wge();Jq();xge();xp()});var Xq,Tge,Ige,Pge=C(()=>{Xq="fulltext",Tge="hybrid",Ige="vector"});var _C,SC,Ege=C(()=>{Pge();_C=Symbol("orama.insertions"),SC=Symbol("orama.removals")});function Age(t){typeof t[_C]!="number"&&(queueMicrotask(()=>{t[_C]=void 0}),t[_C]=0),t[_C]>1e3?(qKe("Orama's insert operation is synchronous. Please avoid inserting a large number of document in a single operation in order not to block the main thread or, in alternative, please use insertMultiple.",{code:"ORAMA0001"}),t[_C]=-1):t[_C]>=0&&t[_C]++}function kge(t){typeof t[SC]!="number"&&(queueMicrotask(()=>{t[SC]=void 0}),t[SC]=0),t[SC]>1e3?(qKe("Orama's remove operation is synchronous. Please avoid removing a large number of document in a single operation in order not to block the main thread, in alternative, please use updateMultiple.",{code:"ORAMA0002"}),t[SC]=-1):t[SC]>=0&&t[SC]++}var qKe,Mge=C(()=>{Ege();qKe=globalThis.process?.emitWarning??function(e,n){console.warn(`[WARNING] [${n.code}] ${e}`)}});function QU(t,e,n,r,o){let i=t.validateSchema(e,t.schema);if(i)throw qt("SCHEMA_VALIDATION_FAILURE",i);return Ss(t.index.beforeInsert)||Ss(t.index.insert)||Ss(t.index.afterInsert)?o2t(t,e,n,r,o):i2t(t,e,n,r,o)}async function o2t(t,e,n,r,o){let{index:i,docs:s}=t.data,a=t.getDocumentIndexId(e);if(typeof a!="string")throw qt("DOCUMENT_ID_MUST_BE_STRING",typeof a);if(!t.documentsStore.store(s,a,e))throw qt("DOCUMENT_ALREADY_EXISTS",a);let l=t.documentsStore.count(s);r||await Qm(t.beforeInsert,t,a,e);let c=t.index.getSearchableProperties(i),u=t.index.getSearchablePropertiesWithTypes(i),d=t.getDocumentProperties(e,c);for(let[f,p]of Object.entries(d)){if(typeof p>"u")continue;let m=typeof p,h=u[f];GKe(m,h,f,p)}return await s2t(t,a,c,d,l,n,e,o),r||await Qm(t.afterInsert,t,a,e),Age(t),a}function i2t(t,e,n,r,o){let{index:i,docs:s}=t.data,a=t.getDocumentIndexId(e);if(typeof a!="string")throw qt("DOCUMENT_ID_MUST_BE_STRING",typeof a);if(!t.documentsStore.store(s,a,e))throw qt("DOCUMENT_ALREADY_EXISTS",a);let l=t.documentsStore.count(s);r||Qm(t.beforeInsert,t,a,e);let c=t.index.getSearchableProperties(i),u=t.index.getSearchablePropertiesWithTypes(i),d=t.getDocumentProperties(e,c);for(let[f,p]of Object.entries(d)){if(typeof p>"u")continue;let m=typeof p,h=u[f];GKe(m,h,f,p)}return a2t(t,a,c,d,l,n,e,o),r||Qm(t.afterInsert,t,a,e),Age(t),a}function GKe(t,e,n,r){if(!(X3e(e)&&typeof r=="object"&&typeof r.lon=="number"&&typeof r.lat=="number")&&!(ov(e)&&Array.isArray(r))&&!(FN(e)&&Array.isArray(r))&&!(n2t.has(e)&&r2t.has(t))&&t!==e)throw qt("INVALID_DOCUMENT_PROPERTY",n,e,t)}async function s2t(t,e,n,r,o,i,s,a){for(let u of n){let d=r[u];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[u];await t.index.beforeInsert?.(t.data.index,u,e,d,f,i,t.tokenizer,o),await t.index.insert(t.index,t.data.index,u,e,d,f,i,t.tokenizer,o,a),await t.index.afterInsert?.(t.data.index,u,e,d,f,i,t.tokenizer,o)}let l=t.sorter.getSortableProperties(t.data.sorting),c=t.getDocumentProperties(s,l);for(let u of l){let d=c[u];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[u];t.sorter.insert(t.data.sorting,u,e,d,f,i)}}function a2t(t,e,n,r,o,i,s,a){for(let u of n){let d=r[u];if(typeof d>"u")continue;let f=t.index.getSearchablePropertiesWithTypes(t.data.index)[u];t.index.beforeInsert?.(t.data.index,u,e,d,f,i,t.tokenizer,o),t.index.insert(t.index,t.data.index,u,e,d,f,i,t.tokenizer,o,a),t.index.afterInsert?.(t.data.index,u,e,d,f,i,t.tokenizer,o)}let l=t.sorter.getSortableProperties(t.data.sorting),c=t.getDocumentProperties(s,l);for(let u of l){let d=c[u];if(typeof d>"u")continue;let f=t.sorter.getSortablePropertiesWithTypes(t.data.sorting)[u];t.sorter.insert(t.data.sorting,u,e,d,f,i)}}var n2t,r2t,Nge=C(()=>{Sge();ss();CC();Mge();Ua();n2t=new Set(["enum","enum[]"]),r2t=new Set(["string","number"])});function c0(t,e,n,r){return Ss(t.index.beforeRemove)||Ss(t.index.remove)||Ss(t.index.afterRemove)?l2t(t,e,n,r):c2t(t,e,n,r)}async function l2t(t,e,n,r){let o=!0,{index:i,docs:s}=t.data,a=t.documentsStore.get(s,e);if(!a)return!1;let l=vp(t.internalDocumentIDStore,mo(t.internalDocumentIDStore,e)),c=t.documentsStore.count(s);r||await Qm(t.beforeRemove,t,l);let u=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(a,u);for(let h of u){let g=f[h];if(typeof g>"u")continue;let y=d[h];await t.index.beforeRemove?.(t.data.index,h,l,g,y,n,t.tokenizer,c),await t.index.remove(t.index,t.data.index,h,e,g,y,n,t.tokenizer,c)||(o=!1),await t.index.afterRemove?.(t.data.index,h,l,g,y,n,t.tokenizer,c)}let p=await t.sorter.getSortableProperties(t.data.sorting),m=await t.getDocumentProperties(a,p);for(let h of p)typeof m[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||await Qm(t.afterRemove,t,l),t.documentsStore.remove(t.data.docs,e),kge(t),o}function c2t(t,e,n,r){let o=!0,{index:i,docs:s}=t.data,a=t.documentsStore.get(s,e);if(!a)return!1;let l=vp(t.internalDocumentIDStore,mo(t.internalDocumentIDStore,e)),c=t.documentsStore.count(s);r||Qm(t.beforeRemove,t,l);let u=t.index.getSearchableProperties(i),d=t.index.getSearchablePropertiesWithTypes(i),f=t.getDocumentProperties(a,u);for(let h of u){let g=f[h];if(typeof g>"u")continue;let y=d[h];t.index.beforeRemove?.(t.data.index,h,l,g,y,n,t.tokenizer,c),t.index.remove(t.index,t.data.index,h,e,g,y,n,t.tokenizer,c)||(o=!1),t.index.afterRemove?.(t.data.index,h,l,g,y,n,t.tokenizer,c)}let p=t.sorter.getSortableProperties(t.data.sorting),m=t.getDocumentProperties(a,p);for(let h of p)typeof m[h]>"u"||t.sorter.remove(t.data.sorting,h,e);return r||Qm(t.afterRemove,t,l),t.documentsStore.remove(t.data.docs,e),kge(t),o}function eB(t,e,n,r,o){return Ss(t.index.beforeRemove)||Ss(t.index.remove)||Ss(t.index.afterRemove)||Ss(t.beforeRemoveMultiple)||Ss(t.afterRemoveMultiple)?u2t(t,e,n,r,o):d2t(t,e,n,r,o)}async function u2t(t,e,n,r,o){let i=0;n||(n=1e3);let s=o?[]:e.map(a=>vp(t.internalDocumentIDStore,mo(t.internalDocumentIDStore,a)));return o||await a0(t.beforeRemoveMultiple,t,s),await new Promise((a,l)=>{let c=0;async function u(){let d=e.slice(c*n,++c*n);if(!d.length)return a();for(let f of d)try{await c0(t,f,r,o)&&i++}catch(p){l(p)}setTimeout(u,0)}setTimeout(u,0)}),o||await a0(t.afterRemoveMultiple,t,s),i}function d2t(t,e,n,r,o){let i=0;n||(n=1e3);let s=o?[]:e.map(c=>vp(t.internalDocumentIDStore,mo(t.internalDocumentIDStore,c)));o||a0(t.beforeRemoveMultiple,t,s);let a=0;function l(){let c=e.slice(a*n,++a*n);if(c.length){for(let u of c)c0(t,u,r,o)&&i++;setTimeout(l,0)}}return l(),o||a0(t.afterRemoveMultiple,t,s),i}var Oge=C(()=>{CC();xp();Mge();ss()});function f2t(t,e){return t[1]-e[1]}function p2t(t,e){return e[1]-t[1]}function m2t(t="desc"){return t.toLowerCase()==="asc"?f2t:p2t}function VN(t,e,n){let r={},o=e.map(([c])=>c),i=t.documentsStore.getMultiple(t.data.docs,o),s=Object.keys(n),a=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let c of s){let u;if(a[c]==="number"){let{ranges:d}=n[c],f=d.length,p=Array.from({length:f});for(let m=0;m<f;m++){let h=d[m];p[m]=[`${h.from}-${h.to}`,0]}u=Object.fromEntries(p)}r[c]={count:0,values:u??{}}}let l=i.length;for(let c=0;c<l;c++){let u=i[c];for(let d of s){let f=d.includes(".")?$N(u,d):u[d],p=a[d],m=r[d].values;switch(p){case"number":{let h=n[d].ranges;YKe(h,m)(f);break}case"number[]":{let h=new Set,g=n[d].ranges,y=YKe(g,m,h);for(let w of f)y(w);break}case"boolean":case"enum":case"string":{ZKe(m,p)(f);break}case"boolean[]":case"enum[]":case"string[]":{let y=ZKe(m,p==="boolean[]"?"boolean":"string",new Set);for(let w of f)y(w);break}default:throw qt("FACET_NOT_SUPPORTED",p)}}}for(let c of s){let u=r[c];if(u.count=Object.keys(u.values).length,a[c]==="string"){let d=n[c],f=m2t(d.sort);u.values=Object.fromEntries(Object.entries(u.values).sort(f).slice(d.offset??0,d.limit??10))}}return r}function YKe(t,e,n){return r=>{for(let o of t){let i=`${o.from}-${o.to}`;n?.has(i)||r>=o.from&&r<=o.to&&(e[i]===void 0?e[i]=1:(e[i]++,n?.add(i)))}}}function ZKe(t,e,n){let r=e==="boolean"?"false":"";return o=>{let i=o?.toString()??r;n?.has(i)||(t[i]=(t[i]??0)+1,n?.add(i))}}var Qq=C(()=>{Ua();ss()});function WN(t,e){let n=new Map,r=[];for(let o of t)n.set(o,!0);for(let o of e){let[i]=o;n.has(i)&&(r.push(o),n.delete(i))}return r}var eG=C(()=>{});function HN(t,e,n){let r=n.properties,o=r.length,i=t.index.getSearchablePropertiesWithTypes(t.data.index);for(let y=0;y<o;y++){let w=r[y];if(typeof i[w]>"u")throw qt("UNKNOWN_GROUP_BY_PROPERTY",w);if(!JKe.includes(i[w]))throw qt("INVALID_GROUP_BY_PROPERTY",w,JKe.join(", "),i[w])}let s=e.map(([y])=>vp(t.internalDocumentIDStore,y)),a=t.documentsStore.getMultiple(t.data.docs,s),l=a.length,c=n.maxResult||Number.MAX_SAFE_INTEGER,u=[],d={};for(let y=0;y<o;y++){let w=r[y],v={property:w,perValue:{}},x=new Set;for(let b=0;b<l;b++){let _=a[b],T=$N(_,w);if(typeof T>"u")continue;let S=typeof T!="boolean"?T:""+T,P=v.perValue[S]??{indexes:[],count:0};P.count>=c||(P.indexes.push(b),P.count++,v.perValue[S]=P,x.add(T))}u.push(Array.from(x)),d[w]=v}let f=XKe(u),p=f.length,m=[];for(let y=0;y<p;y++){let w=f[y],v=w.length,x={values:[],indexes:[]},b=[];for(let _=0;_<v;_++){let T=w[_],S=r[_];b.push(d[S].perValue[typeof T!="boolean"?T:""+T].indexes),x.values.push(T)}x.indexes=DN(b).sort((_,T)=>_-T),x.indexes.length!==0&&m.push(x)}let h=m.length,g=Array.from({length:h});for(let y=0;y<h;y++){let w=m[y],v=n.reduce||h2t,x=w.indexes.map(S=>({id:s[S],score:e[S][1],document:a[S]})),b=v.reducer.bind(null,w.values),_=v.getInitialValue(w.indexes.length),T=x.reduce(b,_);g[y]={values:w.values,result:T}}return g}function XKe(t,e=0){if(e+1===t.length)return t[e].map(i=>[i]);let n=t[e],r=XKe(t,e+1),o=[];for(let i of n)for(let s of r){let a=[i];So(a,s),o.push(a)}return o}var h2t,JKe,tG=C(()=>{Ua();ss();xp();h2t={reducer:(t,e,n,r)=>(e[r]=n,e),getInitialValue:t=>Array.from({length:t})},JKe=["string","number","boolean"]});function QKe(t,e,n){let r=Xm(),o=t.beforeSearch?.length||t.afterSearch?.length;function i(){e.relevance=Object.assign(nG,e.relevance??{});let a=Object.keys(t.data.index.vectorIndexes),l=e.facets&&Object.keys(e.facets).length>0,{limit:c=10,offset:u=0,term:d,properties:f,threshold:p=0,distinctOn:m,includeVectors:h=!1}=e,g=e.preflight===!0,{index:y,docs:w}=t.data,v=t.tokenizer.tokenize(d??"",n),x=t.caches.propertiesToSearch;if(!x){let D=t.index.getSearchablePropertiesWithTypes(y);x=t.index.getSearchableProperties(y),x=x.filter($=>D[$].startsWith("string")),t.caches.propertiesToSearch=x}if(f&&f!=="*"){for(let D of f)if(!x.includes(D))throw qt("UNKNOWN_INDEX",D,x.join(", "));x=x.filter(D=>f.includes(D))}let b=u0(t.tokenizer,t.index,t.documentsStore,n,e,x,v,t.documentsStore.count(w),r),_=Object.keys(e.where??{}).length>0,T=[];_&&(T=t.index.searchByWhereClause(b,y,e.where));let S=v.length;if(S||f?.length){let D=x.length;for(let $=0;$<D;$++){let B=x[$],W=b.indexMap[B];if(S!==0)for(let H=0;H<S;H++){let te=v[H],fe=t.index.search(b,y,B,te);So(W[te],fe)}else{W[""]=[];let H=t.index.search(b,y,B,"");So(W[""],H)}let F=Object.values(W);b.docsIntersection[B]=Kq(F,e?.boost?.[B]??1,p,S);let Z=b.docsIntersection[B],V=Z.length;for(let H=0;H<V;H++){let[te,fe]=Z[H],me=b.uniqueDocsIDs[te];me?b.uniqueDocsIDs[te]=me+fe+.5:b.uniqueDocsIDs[te]=fe}}}else v.length===0&&d?b.uniqueDocsIDs={}:b.uniqueDocsIDs=Object.fromEntries(Object.keys(t.documentsStore.getAll(t.data.docs)).map(D=>[D,0]));let P=Object.entries(b.uniqueDocsIDs).map(([D,$])=>[+D,$]);if(_&&(P=WN(T,P)),e.sortBy)if(typeof e.sortBy=="function"){let D=P.map(([W])=>W),B=t.documentsStore.getMultiple(t.data.docs,D).map((W,F)=>[P[F][0],P[F][1],W]);B.sort(e.sortBy),P=B.map(([W,F])=>[W,F])}else P=t.sorter.sortBy(t.data.sorting,P,e.sortBy).map(([D,$])=>[mo(t.internalDocumentIDStore,D),$]);else P=P.sort(Y3e);let A;g||(A=m?t5e(t,P,u,c,m):rG(t,P,u,c));let O={elapsed:{formatted:"",raw:0},hits:[],count:P.length};if(typeof A<"u"&&(O.hits=A.filter(Boolean),h||Wq(O,a)),l){let D=VN(t,P,e.facets);O.facets=D}return e.groupBy&&(O.groups=HN(t,P,e.groupBy)),O.elapsed=t.formatElapsedTime(Xm()-b.timeStart),O}async function s(){t.beforeSearch&&await BN(t.beforeSearch,t,e,n);let a=i();return t.afterSearch&&await UN(t.afterSearch,t,e,n,a),a}return o?s():i()}var e5e=C(()=>{JU();Qq();eG();tG();CC();xp();Ua();ss();d0()});function Rge(t,e,n="english"){let r=Xm(),o=t.beforeSearch?.length||t.afterSearch?.length;function i(){let{vector:a}=e;if(a&&(!("value"in a)||!("property"in a)))throw qt("INVALID_VECTOR_INPUT",Object.keys(a).join(", "));let{limit:l=10,offset:c=0,includeVectors:u=!1}=e,d=t.data.index.vectorIndexes[a.property],f=d.size,p=d.vectors,m=e.facets&&Object.keys(e.facets).length>0,h=Object.keys(e.where??{}).length>0,{index:g,docs:y}=t.data;if(a?.value.length!==f)throw a?.property===void 0||a?.value.length===void 0?qt("INVALID_INPUT_VECTOR","undefined",f,"undefined"):qt("INVALID_INPUT_VECTOR",a.property,f,a.value.length);a instanceof Float32Array||(a.value=new Float32Array(a.value));let w=qq(a.value,p,f,e.similarity).map(([D,$])=>[mo(t.internalDocumentIDStore,D),$]),v=t.caches.propertiesToSearch;if(!v){let D=t.index.getSearchablePropertiesWithTypes(g);v=t.index.getSearchableProperties(g),v=v.filter($=>D[$].startsWith("string")),t.caches.propertiesToSearch=v}let x=[],b=u0(t.tokenizer,t.index,t.documentsStore,n,e,v,x,t.documentsStore.count(y),r),_=[];h&&(_=t.index.searchByWhereClause(b,g,e.where),w=WN(_,w));let T=[];m&&(T=VN(t,w,e.facets));let S=Array.from({length:l});for(let D=0;D<l;D++){let $=w[D+c];if(!$)break;let B=t.data.docs.docs[$[0]];if(B){u||(B[a.property]=null);let W={id:vp(t.internalDocumentIDStore,$[0]),score:$[1],document:B};S[D]=W}}let P=[];e.groupBy&&(P=HN(t,w,e.groupBy));let O=Xm()-r;return{count:w.length,hits:S.filter(Boolean),elapsed:{raw:Number(O),formatted:s0(O)},...T?{facets:T}:{},...P?{groups:P}:{}}}async function s(){t.beforeSearch&&await BN(t.beforeSearch,t,e,n);let a=i();return t.afterSearch&&await UN(t.afterSearch,t,e,n,a),a}return o?s():i()}var Lge=C(()=>{d0();ss();Qq();Ua();Gq();eG();tG();xp();CC()});function r5e(t,e,n){let r=Xm(),o=t.beforeSearch?.length||t.afterSearch?.length;function i(){let{offset:a=0,limit:l=10,includeVectors:c=!1}=e,u=e.facets&&Object.keys(e.facets).length>0,d=g2t(t,e,n),f=y2t(t,e),{index:p,docs:m}=t.data,h=e.hybridWeights,g=v2t(d,f,e.term??"",h),y=t.tokenizer.tokenize(e.term??"",n),w=t.caches.propertiesToSearch;if(!w){let O=t.index.getSearchablePropertiesWithTypes(p);w=t.index.getSearchableProperties(p),w=w.filter(D=>O[D].startsWith("string")),t.caches.propertiesToSearch=w}if(e.properties&&e.properties!=="*"){for(let O of e.properties)if(!w.includes(O))throw qt("UNKNOWN_INDEX",O,w.join(", "));w=w.filter(O=>e.properties.includes(O))}let v=u0(t.tokenizer,t.index,t.documentsStore,n,e,w,y,t.documentsStore.count(m),r),x=Object.keys(e.where??{}).length>0,b=[];x&&(b=t.index.searchByWhereClause(v,p,e.where),g=WN(b,g));let _;u&&(_=VN(t,g,e.facets));let T;e.groupBy&&(T=HN(t,g,e.groupBy));let S=rG(t,g,a,l).filter(Boolean),P=Xm(),A={count:g.length,elapsed:{raw:Number(P-r),formatted:s0(P-r)},hits:S,..._?{facets:_}:{},...T?{groups:T}:{}};if(!c){let O=Object.keys(t.data.index.vectorIndexes);Wq(A,O)}return A}async function s(){t.beforeSearch&&await BN(t.beforeSearch,t,e,n);let a=i();return t.afterSearch&&await UN(t.afterSearch,t,e,n,a),a}return o?s():i()}function g2t(t,e,n){let r=Xm();e.relevance=Object.assign(nG,e.relevance??{});let{term:o="",properties:i,threshold:s=0}=e,{index:a,docs:l}=t.data,c=t.tokenizer.tokenize(o,n),u=t.caches.propertiesToSearch;if(!u){let m=t.index.getSearchablePropertiesWithTypes(a);u=t.index.getSearchableProperties(a),u=u.filter(h=>m[h].startsWith("string")),t.caches.propertiesToSearch=u}if(i&&i!=="*"){let m=new Set(u),h=new Set(i);for(let g of i)if(!m.has(g))throw qt("UNKNOWN_INDEX",g,u.join(", "));u=u.filter(g=>h.has(g))}let d=u0(t.tokenizer,t.index,t.documentsStore,n,e,u,c,t.documentsStore.count(l),r),f=c.length;if(f||i&&i.length>0){let m=u.length;for(let h=0;h<m;h++){let g=u[h];if(f!==0)for(let b=0;b<f;b++){let _=c[b],T=t.index.search(d,a,g,_);So(d.indexMap[g][_],T)}else{let b=[];d.indexMap[g][""]=b;let _=t.index.search(d,a,g,"");So(b,_)}let y=d.indexMap[g],w=Object.values(y);d.docsIntersection[g]=Kq(w,e?.boost?.[g]??1,s,f);let v=d.docsIntersection[g],x=v.length;for(let b=0;b<x;b++){let[_,T]=v[b],S=d.uniqueDocsIDs[_];d.uniqueDocsIDs[_]=S?S+T+.5:T}}}else c.length===0&&o?d.uniqueDocsIDs={}:d.uniqueDocsIDs=Object.fromEntries(Object.keys(t.documentsStore.getAll(t.data.docs)).map(m=>[m,0]));let p=Object.entries(d.uniqueDocsIDs).map(([m,h])=>[+m,h]).sort((m,h)=>h[1]-m[1]);return o5e(p)}function y2t(t,e){let n=e.vector,r=t.data.index.vectorIndexes[n?.property],o=r.size,i=r.vectors;if(n&&(!n.value||!n.property))throw qt("INVALID_VECTOR_INPUT",Object.keys(n).join(", "));if(n.value.length!==o)throw qt("INVALID_INPUT_VECTOR",n.property,o,n.value.length);n instanceof Float32Array||(n.value=new Float32Array(n.value));let s=qq(n.value,i,o,e.similarity).map(([a,l])=>[mo(t.internalDocumentIDStore,a),l]);return o5e(s)}function Dge([,t]){return t}function o5e(t){let e=Math.max.apply(Math,t.map(Dge));return t.map(([n,r])=>[n,r/e])}function n5e(t,e){return t/e}function w2t(t,e){return(n,r)=>n*t+r*e}function v2t(t,e,n,r){let o=Math.max.apply(Math,t.map(Dge)),i=Math.max.apply(Math,e.map(Dge)),s=r&&r.text&&r.vector,{text:a,vector:l}=s?r:x2t(n),c=new Map,u=t.length,d=w2t(a,l);for(let p=0;p<u;p++){let[m,h]=t[p],g=n5e(h,o),y=d(g,0);c.set(m,y)}let f=e.length;for(let p=0;p<f;p++){let[m,h]=e[p],g=n5e(h,i),y=c.get(m)??0;c.set(m,y+d(0,g))}return[...c].sort((p,m)=>m[1]-p[1])}function x2t(t){return{text:.5,vector:.5}}var i5e=C(()=>{ss();eG();JU();Ua();d0();Qq();tG();Gq();xp();d0();CC()});function u0(t,e,n,r,o,i,s,a,l){let c={},u={};for(let d of i){let f={};for(let p of s)f[p]=[];c[d]=f,u[d]=[]}return{timeStart:l,tokenizer:t,index:e,documentsStore:n,language:r,params:o,docsCount:a,uniqueDocsIDs:{},indexMap:c,docsIntersection:u}}function Zu(t,e,n){let r=e.mode??Xq;if(r===Xq)return QKe(t,e,n);if(r===Ige)return Rge(t,e);if(r===Tge)return r5e(t,e);throw qt("INVALID_SEARCH_MODE",r)}function t5e(t,e,n,r,o){let i=t.data.docs,s=new Map,a=[],l=new Set,c=e.length,u=0;for(let d=0;d<c;d++){let f=e[d];if(typeof f>"u")continue;let[p,m]=f;if(l.has(p))continue;let h=t.documentsStore.get(i,p),g=$N(h,o);if(!(typeof g>"u"||s.has(g))&&(s.set(g,!0),u++,!(u<=n)&&(a.push({id:vp(t.internalDocumentIDStore,p),score:m,document:h}),l.add(p),u>=n+r)))break}return a}function rG(t,e,n,r){let o=t.data.docs,i=Array.from({length:r}),s=new Set;for(let a=n;a<r+n;a++){let l=e[a];if(typeof l>"u")break;let[c,u]=l;if(!s.has(c)){let d=t.documentsStore.get(o,c);i[a]={id:vp(t.internalDocumentIDStore,c),score:u,document:d},s.add(c)}}return i}var nG,d0=C(()=>{xp();Ua();ss();Pge();e5e();Lge();i5e();nG={k:1.2,b:.75,d:.5}});function oG(t,e){t.internalDocumentIDStore.load(t,e.internalDocumentIDStore),t.data.index=t.index.load(t.internalDocumentIDStore,e.index),t.data.docs=t.documentsStore.load(t.internalDocumentIDStore,e.docs),t.data.sorting=t.sorter.load(t.internalDocumentIDStore,e.sorting),t.tokenizer.language=e.language}function $ge(t){return{internalDocumentIDStore:t.internalDocumentIDStore.save(t.internalDocumentIDStore),index:t.index.save(t.data.index),docs:t.documentsStore.save(t.data.docs),sorting:t.sorter.save(t.data.sorting),language:t.tokenizer.language}}var s5e=C(()=>{});var a5e=C(()=>{CC();Ua();Nge();Oge();ss()});var l5e=C(()=>{Ua();d0()});var c5e=C(()=>{fge();ss();JU();Jq()});var iG=C(()=>{HKe();KKe();Nge();Oge();d0();Lge();s5e();a5e();l5e();Ege();Sge();c5e()});function S2t(t,e){let n=u5e(t,r=>e.priority<=r.priority);t.splice(n+1,0,e)}function u5e(t,e){for(let n=t.length-1;n>=0;n--)if(e(t[n]))return n;return-1}var R9n,L9n,C2t,_2t,Fge,T2t,f0,Uge=C(()=>{R9n=new Error("timeout while waiting for mutex to become available"),L9n=new Error("mutex already locked"),C2t=new Error("request for lock canceled"),_2t=function(t,e,n,r){function o(i){return i instanceof n?i:new n(function(s){s(i)})}return new(n||(n=Promise))(function(i,s){function a(u){try{c(r.next(u))}catch(d){s(d)}}function l(u){try{c(r.throw(u))}catch(d){s(d)}}function c(u){u.done?i(u.value):o(u.value).then(a,l)}c((r=r.apply(t,e||[])).next())})},Fge=class{constructor(e,n=C2t){this._value=e,this._cancelError=n,this._queue=[],this._weightedWaiters=[]}acquire(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((r,o)=>{let i={resolve:r,reject:o,weight:e,priority:n},s=u5e(this._queue,a=>n<=a.priority);s===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(s+1,0,i)})}runExclusive(e){return _2t(this,arguments,void 0,function*(n,r=1,o=0){let[i,s]=yield this.acquire(r,o);try{return yield n(i)}finally{s()}})}waitForUnlock(e=1,n=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,n)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),S2t(this._weightedWaiters[e-1],{resolve:r,priority:n})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let n=this._value;this._value-=e.weight,e.resolve([n,this._newReleaser(e.weight)])}_newReleaser(e){let n=!1;return()=>{n||(n=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let n=this._weightedWaiters[e-1];n&&(n.forEach(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let n=this._value;n>0;n--){let r=this._weightedWaiters[n-1];if(!r)continue;let o=r.findIndex(i=>i.priority<=e);(o===-1?r:r.splice(0,o)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,n){return(this._queue.length===0||this._queue[0].priority<n)&&e<=this._value}};T2t=function(t,e,n,r){function o(i){return i instanceof n?i:new n(function(s){s(i)})}return new(n||(n=Promise))(function(i,s){function a(u){try{c(r.next(u))}catch(d){s(d)}}function l(u){try{c(r.throw(u))}catch(d){s(d)}}function c(u){u.done?i(u.value):o(u.value).then(a,l)}c((r=r.apply(t,e||[])).next())})},f0=class{constructor(e){this._semaphore=new Fge(1,e)}acquire(){return T2t(this,arguments,void 0,function*(e=0){let[,n]=yield this._semaphore.acquire(1,e);return n})}runExclusive(e,n=0){return this._semaphore.runExclusive(()=>e(),1,n)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}});function f5e(t){let e="";for(let n=0;n<t.length;n++)e+=d5e[t[n]>>>4]+d5e[t[n]&15];return e}function E2t(t,e){return t<<e|t>>>32-e}function Jc(t){let e=new TextEncoder().encode(t),n=e.length,r=(n+8>>>6)+1<<6,o=new Uint8Array(r);o.set(e),o[n]=128;let i=new DataView(o.buffer),s=n*8>>>0,a=Math.floor(n/536870912);i.setUint32(r-8,s,!0),i.setUint32(r-4,a,!0);let l=1732584193,c=-271733879,u=-1732584194,d=271733878,f=new Int32Array(16);for(let h=0;h<r;h+=64){for(let x=0;x<16;x++)f[x]=i.getInt32(h+x*4,!0);let g=l,y=c,w=u,v=d;for(let x=0;x<64;x++){let b,_;x<16?(b=y&w|~y&v,_=x):x<32?(b=v&y|~v&w,_=5*x+1&15):x<48?(b=y^w^v,_=3*x+5&15):(b=w^(y|~v),_=7*x&15);let T=v;v=w,w=y,y=y+E2t(g+b+I2t[x]+f[_]|0,P2t[x])|0,g=T}l=l+g|0,c=c+y|0,u=u+w|0,d=d+v|0}let p=new Uint8Array(16),m=new DataView(p.buffer);return m.setInt32(0,l,!0),m.setInt32(4,c,!0),m.setInt32(8,u,!0),m.setInt32(12,d,!0),f5e(p)}function Qg(t,e){return t>>>e|t<<32-e}function p5e(t){let e=new TextEncoder().encode(t),n=e.length,r=(n+8>>>6)+1<<6,o=new Uint8Array(r);o.set(e),o[n]=128;let i=new DataView(o.buffer),s=n*8>>>0,a=Math.floor(n/536870912);i.setUint32(r-8,a,!1),i.setUint32(r-4,s,!1);let l=1779033703,c=-1150833019,u=1013904242,d=-1521486534,f=1359893119,p=-1694144372,m=528734635,h=1541459225,g=new Int32Array(64);for(let v=0;v<r;v+=64){for(let D=0;D<16;D++)g[D]=i.getInt32(v+D*4,!1);for(let D=16;D<64;D++){let $=g[D-15],B=g[D-2],W=Qg($,7)^Qg($,18)^$>>>3,F=Qg(B,17)^Qg(B,19)^B>>>10;g[D]=g[D-16]+W+g[D-7]+F|0}let x=l,b=c,_=u,T=d,S=f,P=p,A=m,O=h;for(let D=0;D<64;D++){let $=Qg(S,6)^Qg(S,11)^Qg(S,25),B=S&P^~S&A,W=O+$+B+A2t[D]+g[D]|0,F=Qg(x,2)^Qg(x,13)^Qg(x,22),Z=x&b^x&_^b&_,V=F+Z|0;O=A,A=P,P=S,S=T+W|0,T=_,_=b,b=x,x=W+V|0}l=l+x|0,c=c+b|0,u=u+_|0,d=d+T|0,f=f+S|0,p=p+P|0,m=m+A|0,h=h+O|0}let y=new Uint8Array(32),w=new DataView(y.buffer);return w.setInt32(0,l,!1),w.setInt32(4,c,!1),w.setInt32(8,u,!1),w.setInt32(12,d,!1),w.setInt32(16,f,!1),w.setInt32(20,p,!1),w.setInt32(24,m,!1),w.setInt32(28,h,!1),f5e(y)}var d5e,I2t,P2t,A2t,TC=C(()=>{d5e="0123456789abcdef";I2t=new Int32Array([-680876936,-389564586,606105819,-1044525330,-176418897,1200080426,-1473231341,-45705983,1770035416,-1958414417,-42063,-1990404162,1804603682,-40341101,-1502002290,1236535329,-165796510,-1069501632,643717713,-373897302,-701558691,38016083,-660478335,-405537848,568446438,-1019803690,-187363961,1163531501,-1444681467,-51403784,1735328473,-1926607734,-378558,-2022574463,1839030562,-35309556,-1530992060,1272893353,-155497632,-1094730640,681279174,-358537222,-722521979,76029189,-640364487,-421815835,530742520,-995338651,-198630844,1126891415,-1416354905,-57434055,1700485571,-1894986606,-1051523,-2054922799,1873313359,-30611744,-1560198380,1309151649,-145523070,-1120210379,718787259,-343485551]),P2t=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];A2t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298])});var Bge,k2t,sG,m5e=C(()=>{Nf();ye();Se();iG();Bge="copilot-index-chunk-",k2t=".json",sG=class{constructor(e,n,r){this.app=e;this.baseDir=n;this.identifier=r}getChunkPath(e){return`${this.baseDir}/${Bge}${this.identifier}-${e}.json`}getMetadataPath(){return`${this.baseDir}/${Bge}${this.identifier}-metadata.json`}getLegacyPath(){return`${this.baseDir}/copilot-index-${this.identifier}${k2t}`}assignDocumentToPartition(e,n){let o=Array.from(e).reduce((i,s)=>(i<<5)-i+s.charCodeAt(0),0);return Math.abs(o)%n}distributeDocumentsToPartitions(e,n){let r=new Map,o={};for(let s=0;s<n;s++)r.set(s,[]);q().debug&&k(`Total documents to distribute: ${e.length}`);for(let s of e){let a=String(s.id),l=this.assignDocumentToPartition(a,n),c=r.get(l);if(!c)throw new Error(`Invalid partition index: ${l}`);c.push(s),o[a]=l}let i=0;return r.forEach((s,a)=>{i+=s.length,q().debug&&k(`Partition ${a+1}: ${s.length} documents`)}),q().debug&&(k(`Total documents distributed: ${i}`),i!==e.length&&console.error(`Document count mismatch! Original: ${e.length}, Distributed: ${i}`)),r}async ensureDirectoryExists(e){let n=e.substring(0,e.lastIndexOf("/"));await this.app.vault.adapter.exists(n)||await this.app.vault.adapter.mkdir(n)}async saveDatabase(e){try{let n=$ge(e),r=q().numPartitions;if(r===1){let c=this.getLegacyPath();await this.ensureDirectoryExists(c),await this.app.vault.adapter.write(c,JSON.stringify({...n,schema:e.schema}));return}let o=n.docs?.docs,i=Array.isArray(o)?o:Object.values(o||{});if(q().debug&&k(`Starting save with ${i.length??0} total documents`),!i||i.length===0){let c={numPartitions:r,schema:e.schema,lastModified:Date.now(),documentPartitions:{}},u=this.getMetadataPath();await this.ensureDirectoryExists(u),await this.app.vault.adapter.write(u,JSON.stringify(c)),q().debug&&k("Saved empty database state");return}let s=this.distributeDocumentsToPartitions(i,r),a={numPartitions:r,schema:e.schema,lastModified:Date.now(),documentPartitions:Object.fromEntries(i.map(c=>[c.id,this.assignDocumentToPartition(String(c.id),r)]))};await this.saveMetadata(a);let l={...n,docs:{docs:{},count:0},index:{...n.index,vectorIndexes:void 0}};for(let[c,u]of s.entries()){let d={index:{vectorIndexes:{embedding:{size:n.index.vectorIndexes.embedding.size,vectors:Object.fromEntries(Object.entries(n.index.vectorIndexes.embedding.vectors).filter(([m])=>u.some(h=>h.id===m)))}}},docs:{docs:Object.fromEntries(u.map((m,h)=>[(h+1).toString(),m])),count:u.length}},f=c===0?{...l,docs:d.docs,index:{...l.index,vectorIndexes:d.index.vectorIndexes}}:d,p=this.getChunkPath(c);await this.ensureDirectoryExists(p),await this.app.vault.adapter.write(p,JSON.stringify(f)),q().debug&&k(`Saved partition ${c+1}/${r}`)}q().debug&&k("Saved all partitions")}catch(n){throw console.error("Error saving database:",n),new Gn(`Failed to save database: ${n.message}`)}}async loadDatabase(){try{let e=this.getLegacyPath();if(await this.app.vault.adapter.exists(e)){let l=JSON.parse(await this.app.vault.adapter.read(e));if(!l?.schema)throw new Gn("Invalid legacy database format");let c=jN({schema:l.schema,components:{tokenizer:{stemmer:void 0,stopWords:void 0}}});return oG(c,l),c}let n=await this.loadMetadata(),r=jN({schema:n.schema,components:{tokenizer:{stemmer:void 0,stopWords:void 0}}}),o=null,i=[];for(let l=0;l<n.numPartitions;l++){let c=this.getChunkPath(l);if(await this.app.vault.adapter.exists(c)){let u=JSON.parse(await this.app.vault.adapter.read(c));i.push(u),l===0&&(o=u)}}if(!o)throw new Gn("No data found in chunks");let s={},a=1;for(let l of o.internalDocumentIDStore.internalIdToId){let c=i.flatMap(u=>Object.values(u.docs.docs)).find(u=>u.id===l);c?(s[a.toString()]=c,a++):q().debug&&console.warn(`Document ${l} not found in any chunk`)}return o.docs.docs=s,o.docs.count=Object.keys(s).length,o.internalDocumentIDStore.internalIdToId=Object.values(s).map(l=>l.id),o.index.vectorIndexes.embedding.vectors=Object.assign({},...i.map(l=>l.index?.vectorIndexes?.embedding?.vectors||{})),oG(r,o),r}catch(e){throw console.error("Error loading database:",e),new Gn(`Failed to load database: ${e.message}`)}}async clearStorage(){try{let e=this.getLegacyPath();await this.app.vault.adapter.exists(e)&&await this.app.vault.adapter.remove(e);let n=await this.app.vault.adapter.list(this.baseDir);for(let r of n.files)r.startsWith(`${this.baseDir}/${Bge}${this.identifier}`)&&await this.app.vault.adapter.remove(r)}catch(e){throw console.error("Error clearing storage:",e),new Gn(`Failed to clear storage: ${e.message}`)}}async exists(){let e=this.getLegacyPath();if(q().numPartitions===1)return await this.app.vault.adapter.exists(e);let n=this.getMetadataPath();return await this.app.vault.adapter.exists(n)||await this.app.vault.adapter.exists(e)}async loadMetadata(){let e=this.getMetadataPath();if(!await this.app.vault.adapter.exists(e))throw new Gn("No existing database found");let n=JSON.parse(await this.app.vault.adapter.read(e));if(!n?.schema)throw new Gn("Invalid metadata file: missing schema");return n}async saveMetadata(e){let n=this.getMetadataPath();await this.ensureDirectoryExists(n),await this.app.vault.adapter.write(n,JSON.stringify(e))}}});var g5e={};zn(g5e,{categorizePatterns:()=>ey,createPatternSettingsValue:()=>ty,extractAppIgnoreSettings:()=>Wge,getAllQAMarkdownContent:()=>Vge,getDecodedPatterns:()=>eh,getExtensionPattern:()=>Hge,getFilePattern:()=>KN,getMatchingPatterns:()=>Bo,getTagPattern:()=>tB,getVectorLength:()=>jge,isInternalExcludedFile:()=>nB,previewPatternValue:()=>O2t,shouldIndexFile:()=>Qr});async function jge(t){if(!t)throw new Gn("Embedding instance not found.");try{let n=await t.embedQuery("Sample text for embedding");if(!n||n.length===0)throw new Gn("Failed to get valid embedding vector length");return k(`Detected vector length: ${n.length} for model: ${is.getModelName(t)}`),n.length}catch(e){throw z("Error getting vector length:",e),new Gn("Failed to determine embedding vector length. Please check your Copilot settings to make sure you have a working embedding model.")}}async function Vge(t){let e="",{inclusions:n,exclusions:r}=Bo(),o=t.vault.getMarkdownFiles().filter(i=>Qr(i,n,r));return await Promise.all(o.map(i=>t.vault.cachedRead(i))).then(i=>i.map(s=>e+=s+" ")),e}function eh(t){let e=[];return e.push(...t.split(",").map(n=>{let r=n.trim();try{return decodeURIComponent(r)}catch{return r}}).filter(n=>n.length>0)),e}function M2t(){return q().qaExclusions?eh(q().qaExclusions):[]}function N2t(){return q().qaInclusions?eh(q().qaInclusions):[]}function Bo(t){let e=t?.inclusions?eh(t.inclusions):t?.isProject?[]:N2t(),n=t?.exclusions?eh(t.exclusions):t?.isProject?[]:M2t();return{inclusions:e.length>0?ey(e):null,exclusions:n.length>0?ey(n):null}}function Qr(t,e,n,r){return!(nB(t)||n&&h5e(t.path,n)||e&&!h5e(t.path,e)||r&&!e)}function ey(t){let e=[],n=[],r=[],o=[],i=/^#[^\s#]+$/,s=/^\*\.([a-zA-Z0-9.]+)$/,a=/^\[\[(.*?)\]\]$/;return t.forEach(l=>{i.test(l)?e.push(l):s.test(l)?n.push(l):a.test(l)?o.push(l):r.push(l)}),{tagPatterns:e,extensionPatterns:n,folderPatterns:r,notePatterns:o}}function O2t(t){return eh(t).join(", ")}function ty({tagPatterns:t,extensionPatterns:e,folderPatterns:n,notePatterns:r}){return[...t??[],...e??[],...r??[],...n??[]].map(i=>encodeURIComponent(i)).join(",")}function R2t(t,e){if(e.length===0)return!1;let n=app.vault.getAbstractFileByPath(t);if(n instanceof zge.TFile){let r=eg(n);if(e.some(o=>r.some(i=>i.toLowerCase()===TA(o).toLowerCase())))return!0}return!1}function L2t(t,e){if(e.length===0)return!1;let n=t.toLowerCase();return e.some(r=>{let o=r.slice(1).toLowerCase();return n.endsWith(o)})}function D2t(t,e){if(e.length===0)return!1;let n=t.replace(/\\/g,"/");return e.some(r=>{let o=r.replace(/\\/g,"/").replace(/\/$/,"");return n.startsWith(o)&&(n.length===o.length||n[o.length]==="/")})}function $2t(t,e){if(e.length===0)return!1;let n=app.vault.getAbstractFileByPath(t);return!!(n instanceof zge.TFile&&e.some(r=>r.slice(2,-2)===n.basename))}function h5e(t,e){if(!e)return!1;let{tagPatterns:n,extensionPatterns:r,folderPatterns:o,notePatterns:i}=e;return R2t(t,n??[])||L2t(t,r??[])||D2t(t,o??[])||$2t(t,i??[])}function Wge(t){let e=[];try{let n=t.vault;if(typeof n.getConfig=="function"){let r=n.getConfig("userIgnoreFilters");r&&Array.isArray(r)&&r.forEach(o=>{typeof o=="string"&&e.push(o.endsWith("/")?o.slice(0,-1):o)})}}catch(n){ee("Error getting userIgnoreFilters from Obsidian config",n)}return e}function tB(t){return`#${t}`}function KN(t){return`[[${t.basename}]]`}function Hge(t){return`*.${t}`}function F2t(){return[Ds.getLogPath()]}function U2t(){let e=(q().projectsFolder||"").trim();return e?[`${e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/\/+$/,"")}/`]:[]}function B2t(t){if(new Set(F2t()).has(t))return!0;let n=U2t();if(n.length===0)return!1;for(let r of n){if(!t.startsWith(r))continue;let o=t.slice(r.length),i=o.split("/");if(i.length===2&&i[1]==="project.md"||o.startsWith("unsupported/")||o==="unsupported")return!0}return!1}function nB(t){return B2t(t.path)}var zge,fc=C(()=>{Nf();o0();ye();Se();HS();qe();zge=require("obsidian")});var w5e={};zn(w5e,{DBOperations:()=>IC});var ny,y5e,IC,aG=C(()=>{o0();Nf();ye();Se();qe();iG();Uge();TC();ny=require("obsidian");m5e();fc();y5e=25,IC=class t{constructor(e){this.app=e;this.isInitialized=!1;this.isIndexLoaded=!1;this.hasUnsavedChanges=!1;this.filesWithoutEmbeddings=new Set;this.upsertMutex=new f0;Ho(()=>{(async()=>{try{let n=q();ny.Platform.isMobile&&n.disableIndexOnMobile?(this.isIndexLoaded=!1,this.oramaDb=void 0):ny.Platform.isMobile&&!n.disableIndexOnMobile&&!this.oramaDb&&await this.initializeDB(await is.getInstance().getEmbeddingsAPI());let r=await this.getDbPath();this.dbPath&&r!==this.dbPath&&(k("Path change detected, reinitializing database..."),this.dbPath=r,await this.initializeChunkedStorage(),await this.initializeDB(await is.getInstance().getEmbeddingsAPI()),k("Database reinitialized with new path:",r))}catch(n){z("DBOperations settings change handler failed",n)}})()})}async initializeChunkedStorage(){if(!this.app.vault.adapter)throw new Gn("Vault adapter not available. Please try again later.");let e=await this.getDbPath();this.chunkedStorage=new sG(this.app,e,this.getVaultIdentifier()),this.isInitialized=!0}async initializeDB(e){try{if(this.isInitialized||(this.dbPath=await this.getDbPath(),await this.initializeChunkedStorage()),ny.Platform.isMobile&&q().disableIndexOnMobile){this.isIndexLoaded=!1,this.oramaDb=void 0;return}if(!this.chunkedStorage)throw new Gn("Storage not initialized properly");try{if(await this.chunkedStorage.exists())return this.oramaDb=await this.chunkedStorage.loadDatabase(),k("Loaded existing chunked semantic index database from disk."),this.oramaDb}catch(r){z("Failed to load existing semantic index database, creating new one:",r)}let n=await this.createNewDb(e);return this.oramaDb=n,n}catch(n){z("Error initializing semantic index database:",n),new ny.Notice("Failed to initialize Copilot database. Some features may be limited.");return}}async saveDB(){if(!(ny.Platform.isMobile&&q().disableIndexOnMobile)){if(!this.oramaDb||!this.chunkedStorage)try{if(await this.initializeDB(await is.getInstance().getEmbeddingsAPI()),!this.oramaDb||!this.chunkedStorage)throw new Gn("Semantic index database not found.")}catch(e){throw z("Failed to initialize database during save:",e),new Gn("Failed to initialize and save database.")}try{await this.chunkedStorage.saveDatabase(this.oramaDb),this.hasUnsavedChanges=!1,q().debug&&k("Semantic index database saved successfully at:",this.dbPath)}catch(e){throw z("Error saving semantic index database:",e),e}}}async clearIndex(e){try{this.oramaDb||await this.initializeDB(e),await this.chunkedStorage?.clearStorage(),await new Promise(n=>window.setTimeout(n,100)),this.oramaDb=await this.createNewDb(e),await this.saveDB(),new ny.Notice("Local Copilot index cleared successfully."),k("Local Copilot index cleared successfully, new instance created.")}catch(n){throw z("Error clearing the local Copilot index:",n),new ny.Notice("An error occurred while clearing the local Copilot index."),n}}async removeDocs(e){if(!this.oramaDb)throw new Gn("Semantic index database not found.");try{let n=await Zu(this.oramaDb,{term:e,properties:["path"]});n.hits.length>0&&(await eB(this.oramaDb,n.hits.map(r=>r.id),500),q().debug&&k(`Deleted document from local Copilot index: ${e}`)),this.markUnsavedChanges()}catch(n){z("Error deleting document from local Copilotindex:",n)}}getDb(){return this.oramaDb||console.warn("Database not initialized. Some features may be limited."),this.oramaDb}async getIsIndexLoaded(){return this.isIndexLoaded}async waitForInitialization(){await this.initializationPromise}onunload(){this.hasUnsavedChanges&&this.saveDB().catch(e=>z("saveDB on unload failed",e))}getCurrentDbPath(){return this.dbPath}async getDbPath(){let e=this.app.vault.getRoot().path,n;if(q().enableIndexSync)n=this.app.vault.configDir;else{let r=e==="/"?"":e;n=`${r===""||r.startsWith("/")?"":"/"}${r}/.copilot-index`,await this.app.vault.adapter.exists(n)||(await this.app.vault.adapter.mkdir(n),k("Created directory:",n))}return n}getVaultIdentifier(){let e=this.app.vault.getName();return Jc(e)}markUnsavedChanges(){this.hasUnsavedChanges=!0}async createNewDb(e){if(!e)throw new Gn("Embedding instance not found.");let n=await jge(e);if(!n||n===0)throw new Gn("Invalid vector length detected. Please check if your embedding model is working.");let r=this.createDynamicSchema(n),o=jN({schema:r,components:{tokenizer:{stemmer:void 0,stopWords:void 0}}});return k(`Created new semantic index database for ${this.dbPath}. Embedding model: ${is.getModelName(e)} with vector length ${n}.`),this.isIndexLoaded=!0,o}static async getDocsByPath(e,n){if(!e)throw new Error("DB not initialized");return n?(await t.getAllDocuments(e)).filter(i=>i.path===n).map(i=>({document:i,score:1})):void 0}static async getDocsByEmbedding(e,n,r){return(await Zu(e,{mode:"vector",vector:{value:n,property:"embedding"},limit:r.limit,similarity:r.similarity,includeVectors:!0})).hits}static async getLatestFileMtime(e){if(!e)throw new Error("DB not initialized");try{let n=await Zu(e,{term:"",limit:1,sortBy:{property:"mtime",order:"DESC"}});return n.hits.length>0?n.hits[0].document.mtime:0}catch(n){return z("Error getting latest file mtime from VectorDB:",n),0}}createDynamicSchema(e){return{id:"string",title:"string",path:"string",content:"string",embedding:`vector[${e}]`,embeddingModel:"string",created_at:"number",ctime:"number",mtime:"number",tags:"string[]",extension:"string",nchars:"number"}}async upsert(e){if(!this.oramaDb)throw new Error("DB not initialized");let n=this.oramaDb;return await this.upsertMutex.runExclusive(async()=>{try{let r=this.chunkedStorage?.assignDocumentToPartition(String(e.id),q().numPartitions),o=await Zu(n,{term:String(e.id),properties:["id"],limit:1});o.hits.length>0&&await c0(n,o.hits[0].id);try{return await QU(n,e),k(`${o.hits.length>0?"Updated":"Inserted"} document ${String(e.id)} in partition ${r}`),this.markUnsavedChanges(),e}catch(i){if(z(`Failed to ${o.hits.length>0?"update":"insert"} document ${String(e.id)}:`,i),o.hits.length>0)try{await QU(n,o.hits[0].document)}catch(s){z("Failed to restore previous document version:",s)}return}}catch(r){z(`Error upserting document ${String(e.id)}:`,r);return}})}async getLatestFileMtime(){if(!this.oramaDb)throw new Error("DB not initialized");try{let e=await Zu(this.oramaDb,{term:"",limit:1,sortBy:{property:"mtime",order:"DESC"}});return e.hits.length>0?e.hits[0].document.mtime:0}catch(e){return z("Error getting latest file mtime from VectorDB:",e),0}}async checkAndHandleEmbeddingModelChange(e){if(!this.oramaDb){k("Semantic index database not loaded in memory. Checking for existing index...");try{await this.initializeDB(e)}catch(o){throw z("Failed to initialize database:",o),new Gn("Failed to initialize semantic index database. Please check your embedding model settings.")}if(!this.oramaDb)return k("No existing index found. Will create new index."),!1}let n=await Zu(this.oramaDb,{term:"",limit:1}),r;if(n.hits.length>0){let o=n.hits[0];typeof o=="object"&&o!==null&&"document"in o&&(r=o.document.embeddingModel)}if(r){let o=is.getModelName(e);if(!kAe(r,o))return new ny.Notice("New embedding model detected. Rebuilding Copilot index from scratch."),k(`Detected change in embedding model from "${r}" to "${o}". Rebuilding Copilot index from scratch.`),this.oramaDb=await this.createNewDb(e),await this.saveDB(),!0}else k("No previous embedding model found in the database.");return!1}static async getAllDocuments(e){return(await Zu(e,{term:"",limit:1e5,includeVectors:!0})).hits.map(r=>r.document)}async garbageCollect(){if(!this.oramaDb){k("Semantic index database not found during garbage collection. Attempting to initialize...");try{let e=await is.getInstance().getEmbeddingsAPI();if(!e)throw new Gn("No embedding model available.");if(await this.initializeDB(e),!this.oramaDb)throw new Gn("Failed to initialize database after attempt.")}catch(e){throw z("Failed to initialize database during garbage collection:",e),new Gn("Failed to initialize database. Please check your embedding model settings.")}}try{let e=this.app.vault.getMarkdownFiles(),n=new Set(e.map(l=>l.path)),{inclusions:r,exclusions:o}=Bo(),i=new Set(e.filter(l=>Qr(l,r,o)).map(l=>l.path)),a=(await t.getAllDocuments(this.oramaDb)).filter(l=>!n.has(l.path)||!i.has(l.path));return a.length===0?0:(k("Copilot index: Docs to remove during garbage collection:",Array.from(new Set(a.map(l=>l.path))).join(", ")),a.length===1?await c0(this.oramaDb,a[0].id):await eB(this.oramaDb,a.map(l=>l.id),500),await this.saveDB(),a.length)}catch(e){throw z("Error garbage collecting the Copilot index:",e),new Gn("Failed to garbage collect the Copilot index.")}}async getIndexedFiles(){if(!this.oramaDb)throw new Gn("Semantic index database not found.");try{let e=await t.getAllDocuments(this.oramaDb),n=new Set;return e.forEach(r=>{n.add(r.path)}),Array.from(n).sort()}catch(e){throw z("Error getting indexed files:",e),new Gn("Failed to retrieve indexed files.")}}async isIndexEmpty(){if(!this.oramaDb)return!0;try{return(await Zu(this.oramaDb,{term:"",limit:1})).hits.length===0}catch(e){throw z("Error checking if database is empty:",e),new Gn("Failed to check if database is empty.")}}async hasIndex(e){if(!this.oramaDb)return!1;let n=await t.getDocsByPath(this.oramaDb,e);return n!==void 0&&n.length>0}async hasEmbeddings(e){if(!this.oramaDb)return!1;let n=await t.getDocsByPath(this.oramaDb,e);return!n||n.length===0?!1:n.every(r=>r?.document?.embedding&&Array.isArray(r.document.embedding)&&r.document.embedding.length>0)}async getDocsJsonByPaths(e){if(!this.oramaDb)throw new Gn("Semantic index database not found.");let n={};for(let r of e){let o=await t.getDocsByPath(this.oramaDb,r);o&&o.length>0&&(n[r]=o.map(i=>i.document))}return n}markFileMissingEmbeddings(e){this.filesWithoutEmbeddings.add(e)}clearFilesMissingEmbeddings(){this.filesWithoutEmbeddings.clear()}getFilesMissingEmbeddings(){return Array.from(this.filesWithoutEmbeddings)}isFileMissingEmbeddings(e){return this.filesWithoutEmbeddings.has(e)}async checkIndexIntegrity(){if(!this.oramaDb)throw new Gn("Orama database not found.");try{let e=await this.getIndexedFiles(),n=[];for(let r=0;r<e.length;r+=1){let o=e[r];await this.hasEmbeddings(o)||(n.push(o),this.filesWithoutEmbeddings.add(o)),(r+1)%y5e===0&&await this.yieldToEventLoop()}e.length%y5e!==0&&await this.yieldToEventLoop(),n.length>0?k(`Integrity check: ${n.length} file(s) missing embeddings, marked for re-indexing:`,n.join(", ")):k("Index integrity check completed. All documents have embeddings.")}catch(e){throw z("Error checking index integrity:",e),new Gn("Failed to check index integrity.")}}async yieldToEventLoop(){await new Promise(e=>{if(typeof window<"u"){let n=window;if(n.requestIdleCallback){n.requestIdleCallback(()=>e());return}}window.setTimeout(e,0)})}}});var lG,v5e=C(()=>{aG();lG=class{constructor(e){this.dbOps=new IC(e)}async initialize(e){await this.dbOps.initializeDB(e)}async clearIndex(e){await this.dbOps.clearIndex(e)}requiresEmbeddings(){return!0}async upsert(e){return await this.dbOps.upsert(e)}async upsertBatch(e){let n=0;for(let r of e)await this.dbOps.upsert(r)&&(n+=1);return n}async removeByPath(e){await this.dbOps.removeDocs(e)}async getIndexedFiles(){return this.dbOps.getIndexedFiles()}async getLatestFileMtime(){return this.dbOps.getLatestFileMtime()}async isIndexEmpty(){return this.dbOps.isIndexEmpty()}async hasIndex(e){return this.dbOps.hasIndex(e)}async getDocumentsByPath(e){let n=this.dbOps.getDb();if(!n)throw new Error("Database is not loaded. Please restart the plugin.");let r=await IC.getDocsByPath(n,e);return r?r.map(o=>o.document):[]}async checkAndHandleEmbeddingModelChange(e){if(!e)throw new Error("Embedding instance is required to check Orama embedding model changes.");return this.dbOps.checkAndHandleEmbeddingModelChange(e)}async save(){await this.dbOps.saveDB()}async checkIndexIntegrity(){await this.dbOps.checkIndexIntegrity()}async garbageCollect(){return this.dbOps.garbageCollect()}markFileMissingEmbeddings(e){this.dbOps.markFileMissingEmbeddings(e)}clearFilesMissingEmbeddings(){this.dbOps.clearFilesMissingEmbeddings()}getFilesMissingEmbeddings(){return this.dbOps.getFilesMissingEmbeddings()}markUnsavedChanges(){this.dbOps.markUnsavedChanges()}onunload(){this.dbOps.onunload()}isRemoteBackend(){return!1}getDb(){return this.dbOps.getDb()}async reinitializeForIndexSyncChange(e){let n=await this.dbOps.getDbPath();this.dbOps.getCurrentDbPath()!==n&&await this.dbOps.initializeDB(e)}getDbOperations(){return this.dbOps}}});var qN,z2t,rB,x5e=C(()=>{Ir();Qi();ye();Se();qN=require("obsidian");fc();z2t=5e3,rB=class{constructor(e,n,r){this.app=e;this.indexOps=n;this.indexBackend=r;this.debounceTimer=null;this.lastActiveFile=null;this.lastActiveFileMtime=null;this.listenersActive=!1;this.handleActiveLeafChange=async e=>{if(!this.shouldHandleEvents()||qN.Platform.isMobile&&q().disableIndexOnMobile&&!this.indexBackend.isRemoteBackend()||ym()!=="copilot_plus")return;let r=this.lastActiveFile,o=this.lastActiveFileMtime,i=e?.view;if(this.lastActiveFile=i instanceof qN.MarkdownView?i.file:null,this.lastActiveFileMtime=this.lastActiveFile?.stat?.mtime??null,!(!r||r===this.lastActiveFile)&&!(!r?.stat?.mtime||o===null)&&r.extension==="md"){let{inclusions:s,exclusions:a}=Bo(),l=Qr(r,s,a),c=o!==null&&r.stat.mtime>o;l&&c&&this.debouncedReindexFile(r)}};this.debouncedReindexFile=e=>{this.shouldHandleEvents()&&(this.debounceTimer!==null&&window.clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout(()=>{q().debug&&k("Copilot Plus: Triggering reindex for file ",e.path),this.indexOps.reindexFile(e).catch(n=>z("reindexFile failed",n)),this.debounceTimer=null},z2t))};this.handleFileDelete=async e=>{this.shouldHandleEvents()&&e instanceof qN.TFile&&await this.indexBackend.removeByPath(e.path)};this.syncEventListeners(),Ho(()=>{this.syncEventListeners()})}shouldHandleEvents(){return q().enableSemanticSearchV3?!(this.indexBackend.isRemoteBackend()&&!this.indexBackend.requiresEmbeddings()):!1}syncEventListeners(){let e=this.shouldHandleEvents();e&&!this.listenersActive?(k("Copilot Plus: Initializing semantic index event listeners"),this.app.workspace.on("active-leaf-change",this.handleActiveLeafChange),this.app.vault.on("delete",this.handleFileDelete),this.listenersActive=!0):!e&&this.listenersActive&&this.teardownEventListeners()}teardownEventListeners(){this.listenersActive&&(this.app.workspace.off("active-leaf-change",this.handleActiveLeafChange),this.app.vault.off("delete",this.handleFileDelete),this.debounceTimer!==null&&(window.clearTimeout(this.debounceTimer),this.debounceTimer=null),this.lastActiveFile=null,this.lastActiveFileMtime=null,this.listenersActive=!1)}cleanup(){this.teardownEventListeners()}unload(){this.teardownEventListeners()}}});function qge(t){return Kge.add(t),()=>{Kge.delete(t)}}function oB(){Kge.forEach(t=>t())}var Kge,Gge=C(()=>{Kge=new Set});var cG,b5e=C(()=>{cG=class{constructor(e){this.lastRequestTime=0;this.requestsPerMin=e}setRequestsPerMin(e){this.requestsPerMin=e}getRequestsPerMin(){return this.requestsPerMin}async wait(){let n=Date.now()-this.lastRequestTime,r=Math.max(0,6e4/this.requestsPerMin-n);r>0&&await new Promise(o=>window.setTimeout(o,r)),this.lastRequestTime=Date.now()}}});var fi,Yge=C(()=>{fi=class{constructor(t){I(this,"pageContent");I(this,"metadata");I(this,"id");this.pageContent=t.pageContent!==void 0?t.pageContent.toString():"",this.metadata=t.metadata??{},this.id=t.id}}});var Zge,C5e=C(()=>{Ra();Zge=class extends gr{constructor(){super(...arguments);I(this,"lc_namespace",["langchain_core","documents","transformers"])}invoke(e,n){return this.transformDocuments(e)}}});var iv=C(()=>{$n();Yge();C5e()});var _5e,Xge,S5e=C(()=>{iv();rde();_5e=class extends Zge{constructor(e){super(e);I(this,"lc_namespace",["langchain","document_transformers","text_splitters"]);I(this,"chunkSize",1e3);I(this,"chunkOverlap",200);I(this,"keepSeparator",!1);I(this,"lengthFunction");if(this.chunkSize=e?.chunkSize??this.chunkSize,this.chunkOverlap=e?.chunkOverlap??this.chunkOverlap,this.keepSeparator=e?.keepSeparator??this.keepSeparator,this.lengthFunction=e?.lengthFunction??(n=>n.length),this.chunkOverlap>=this.chunkSize)throw new Error("Cannot have chunkOverlap >= chunkSize")}async transformDocuments(e,n={}){return this.splitDocuments(e,n)}splitOnSeparator(e,n){let r;if(n)if(this.keepSeparator){let o=n.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&");r=e.split(new RegExp(`(?=${o})`))}else r=e.split(n);else r=e.split("");return r.filter(o=>o!=="")}async createDocuments(e,n=[],r={}){let o=n.length>0?n:[...Array(e.length)].map(()=>({})),{chunkHeader:i="",chunkOverlapHeader:s="(cont'd) ",appendChunkOverlapHeader:a=!1}=r,l=new Array;for(let c=0;c<e.length;c+=1){let u=e[c],d=1,f=null,p=-1;for(let m of await this.splitText(u)){let h=i,g=u.indexOf(m,p+1);if(f===null){let x=this.numberOfNewLines(u,0,g);d+=x}else{let x=p+await this.lengthFunction(f);if(x<g){let b=this.numberOfNewLines(u,x,g);d+=b}else if(x>g){let b=this.numberOfNewLines(u,g,x);d-=b}a&&(h+=s)}let y=this.numberOfNewLines(m),w=o[c].loc&&typeof o[c].loc=="object"?{...o[c].loc}:{};w.lines={from:d,to:d+y};let v={...o[c],loc:w};h+=m,l.push(new fi({pageContent:h,metadata:v})),d+=y,f=m,p=g}}return l}numberOfNewLines(e,n,r){return(e.slice(n,r).match(/\n/g)||[]).length}async splitDocuments(e,n={}){let r=e.filter(s=>s.pageContent!==void 0),o=r.map(s=>s.pageContent),i=r.map(s=>s.metadata);return this.createDocuments(o,i,n)}joinDocs(e,n){let r=e.join(n).trim();return r===""?null:r}async mergeSplits(e,n){let r=[],o=[],i=0;for(let a of e){let l=await this.lengthFunction(a);if(i+l+o.length*n.length>this.chunkSize&&(i>this.chunkSize&&console.warn(`Created a chunk of size ${i}, +
which is longer than the specified ${this.chunkSize}`),o.length>0)){let c=this.joinDocs(o,n);for(c!==null&&r.push(c);i>this.chunkOverlap||i+l+o.length*n.length>this.chunkSize&&i>0;)i-=await this.lengthFunction(o[0]),o.shift()}o.push(a),i+=l}let s=this.joinDocs(o,n);return s!==null&&r.push(s),r}},Xge=class Jge extends _5e{constructor(n){super(n);I(this,"separators",[`

`,`
`," ",""]);this.separators=n?.separators??this.separators,this.keepSeparator=n?.keepSeparator??!0}static lc_name(){return"RecursiveCharacterTextSplitter"}async _splitText(n,r){let o=[],i=r[r.length-1],s;for(let u=0;u<r.length;u+=1){let d=r[u];if(d===""){i=d;break}if(n.includes(d)){i=d,s=r.slice(u+1);break}}let a=this.splitOnSeparator(n,i),l=[],c=this.keepSeparator?"":i;for(let u of a)if(await this.lengthFunction(u)<this.chunkSize)l.push(u);else{if(l.length){let d=await this.mergeSplits(l,c);o.push(...d),l=[]}if(!s)o.push(u);else{let d=await this._splitText(u,s);o.push(...d)}}if(l.length){let u=await this.mergeSplits(l,c);o.push(...u)}return o}async splitText(n){return this._splitText(n,this.separators)}static fromLanguage(n,r){return new Jge({...r,separators:Jge.getSeparatorsForLanguage(n)})}static getSeparatorsForLanguage(n){if(n==="cpp")return[`
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`

`,`
`," ",""];if(n==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`

`,`
`," ",""];if(n==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`

`,`
`," ",""];if(n==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`

`,`
`," ",""];if(n==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`

`,`
`," ",""];if(n==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`

`,`
`," ",""];if(n==="python")return[`
class `,`
def `,`
	def `,`

`,`
`," ",""];if(n==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`

`,`
`," ",""];if(n==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`

`,`
`," ",""];if(n==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`

`,`
`," ",""];if(n==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`

`,`
`," ",""];if(n==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`

`,`
`," ",""];if(n==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`

***

`,`

---

`,`

___

`,`

`,`
`," ",""];if(n==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`

`,`
`," ",""];if(n==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(n==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`

`,`
`," ",""];throw new Error(`Language ${n} is not supported.`)}}});var T5e=C(()=>{S5e()});var GN,p0,Qge=C(()=>{ye();Se();GN=class GN{constructor(){this.bytesUsed=0;let e=q(),n=Math.min(1e3,Math.max(20,e.lexicalSearchRamLimit||100));this.maxBytes=n*GN.MB_TO_BYTES,this.candidateLimit=Math.min(GN.DEFAULT_CANDIDATE_LIMIT,Math.floor(n*5))}getMaxBytes(){return this.maxBytes}getCandidateLimit(){return this.candidateLimit}getBytesUsed(){return this.bytesUsed}canAddContent(e){return this.bytesUsed+e<=this.maxBytes}addBytes(e){this.bytesUsed+=e}reset(){let e=this.bytesUsed;this.bytesUsed=0,k(`MemoryManager: Reset memory tracking (was using ${e} bytes, max: ${this.maxBytes} bytes)`)}getUsagePercent(){return Math.round(this.bytesUsed/this.maxBytes*100)}static getByteSize(e){return new TextEncoder().encode(e).length}};GN.DEFAULT_CANDIDATE_LIMIT=500,GN.MB_TO_BYTES=1024*1024;p0=GN});function PC(t){return eye||(eye=new tye(t)),eye}var dG,uG,tye,eye,iB=C(()=>{ye();It();dG=require("obsidian");T5e();Qge();uG={maxChars:JV,overlap:0,maxBytesTotal:10*1024*1024},tye=class{constructor(e){this.app=e;this.cache=new Map;this.memoryUsage=0}getCacheKey(e,n){return`${e}:${n.maxChars}:${n.overlap}`}createSplitter(e){return Xge.fromLanguage("markdown",{chunkSize:e.maxChars,chunkOverlap:e.overlap,separators:[`

`,`
`,". "," ",""],keepSeparator:!1})}async getChunks(e,n={}){try{if(!Array.isArray(e))return ee("ChunkManager: Invalid notePaths provided"),[];if(e.length===0)return[];e.length>1e3&&(ee("ChunkManager: Too many note paths, limiting to 1000"),e=e.slice(0,1e3));let r=e.filter(l=>!(!l||typeof l!="string"||l.startsWith("/")||l.startsWith("../")||l.includes("/../")||l.endsWith("/..")));if(r.length===0)return ee("ChunkManager: No valid note paths provided"),[];let o={...uG,...n},i=[],s=0,a=0;for(let l of r){let c=this.getCacheKey(l,o),u=this.cache.get(c);if(u&&u.length>0){let d=this.app.vault.getAbstractFileByPath(l);if(d&&d instanceof dG.TFile&&d.stat.mtime>u[0].mtime){let f=this.calculateChunkBytes(u);this.cache.delete(c),this.memoryUsage-=f,u=void 0}}if(!u&&(u=await this.generateChunksForNote(l,o),u.length>0)){let d=this.calculateChunkBytes(u);this.memoryUsage+d<=o.maxBytesTotal?(this.cache.set(c,u),this.memoryUsage+=d):(s+=1,a+=d)}i.push(...u)}if(s>0){let l=(a/1024/1024).toFixed(1);k(`ChunkManager: Cache budget reached, skipped caching ${s} notes (${l}MB total)`)}return k(`ChunkManager: Retrieved ${i.length} chunks from ${r.length} notes (${this.formatMemoryUsage()})`),i}catch(r){return ee("ChunkManager: Failed to get chunks",r),[]}}async getChunkText(e){return(await this.ensureChunkExists(e))?.content||""}async ensureChunkExists(e){let[n]=e.split("#"),o=(await this.getValidatedChunks(n)).find(i=>i.id===e);return o||ee(`ChunkManager: Chunk ${e} not found after regeneration`),o||null}async getValidatedChunks(e){let n;for(let[o,i]of this.cache.entries())if(o.startsWith(e+":")){n=i;break}if(!n&&(k(`ChunkManager: Cache miss for ${e}, regenerating...`),n=await this.regenerateChunks(e),!n||n.length===0))return ee(`ChunkManager: Failed to regenerate chunks for ${e}`),[];let r=this.app.vault.getAbstractFileByPath(e);return r&&r instanceof dG.TFile&&n.length>0&&r.stat.mtime>n[0].mtime&&(k(`ChunkManager: File ${e} modified, regenerating chunks`),n=await this.regenerateChunks(e),!n||n.length===0)?(ee(`ChunkManager: Failed to regenerate chunks after modification for ${e}`),[]):n}getChunkTextSync(e){let[n]=e.split("#");for(let[r,o]of this.cache.entries())if(r.startsWith(n+":")){let i=o.find(s=>s.id===e);if(i)return i.content}return ee(`ChunkManager: Chunk not in cache: ${e} (use async getChunkText for auto-regeneration)`),""}async regenerateChunks(e){try{let n=await this.generateChunksForNote(e,uG),r=this.getCacheKey(e,uG);if(n.length>0){let o=this.calculateChunkBytes(n);if(this.memoryUsage+o<=uG.maxBytesTotal){let i=this.cache.get(r);i&&(this.memoryUsage-=this.calculateChunkBytes(i)),this.cache.set(r,n),this.memoryUsage+=o}else k(`ChunkManager: Cannot cache regenerated chunks for ${e}, would exceed memory budget`)}return n}catch(n){return ee(`ChunkManager: Failed to regenerate chunks for ${e}`,n),[]}}clearCache(){this.cache.clear(),this.memoryUsage=0,k("ChunkManager: Cache cleared")}async generateChunksForNote(e,n){try{let r=this.app.vault.getAbstractFileByPath(e);if(!r||!(r instanceof dG.TFile))return[];let o=await this.safeReadFile(r);if(!o?.trim())return[];let i=this.app.metadataCache.getFileCache(r),s=(i?.headings||[]).slice().sort((p,m)=>p.position.start.offset-m.position.start.offset),a=[],l=0,c=this.findFrontmatterEnd(o,i?.frontmatter),u=o.substring(c),d=s.length>0?s[0].heading:"";if(`

NOTE TITLE: [[${r.basename}]]

NOTE BLOCK CONTENT:

`.length+u.length<=n.maxChars){let p=await this.processContentSection(u,d,r,l,n);return a.push(...p),a}if(s.length===0){let p=await this.processContentSection(u,"",r,l,n);return a.push(...p),a}for(let p=0;p<s.length;p++){let m=s[p],h=s[p+1],g=p===0?c:m.position.start.offset,y=h?.position.start.offset||o.length,w=o.substring(g,y),v=await this.processContentSection(w,m.heading,r,l,n);a.push(...v),l+=v.length}return a}catch(r){return ee(`ChunkManager: Failed to chunk note ${e}`,r),[]}}async processContentSection(e,n,r,o,i){let s=r.basename,a=[],l=`

NOTE TITLE: [[${s}]]

NOTE BLOCK CONTENT:

`,c=l+e;if(c.length<=i.maxChars){let u=this.generateChunkId(r.path,o),d=this.calculateContentHash(c);a.push({id:u,notePath:r.path,chunkIndex:o,content:c,contentHash:d,title:s,heading:n,mtime:r.stat.mtime})}else try{let d=await this.createSplitter(i).createDocuments([e],[],{chunkHeader:l,appendChunkOverlapHeader:i.overlap>0});this.coalesceTinySplitChunks(d.map(p=>p.pageContent),l,i.maxChars).forEach((p,m)=>{let h=o+m,g=this.generateChunkId(r.path,h),y=this.calculateContentHash(p);a.push({id:g,notePath:r.path,chunkIndex:h,content:p,contentHash:y,title:s,heading:n,mtime:r.stat.mtime})})}catch(u){ee(`ChunkManager: Failed to split section in ${r.path}`,u);let d=this.generateChunkId(r.path,o),f=this.calculateContentHash(c);a.push({id:d,notePath:r.path,chunkIndex:o,content:c,contentHash:f,title:s,heading:n,mtime:r.stat.mtime})}return a}coalesceTinySplitChunks(e,n,r){if(e.length<=1)return e;let o=[...e],i=0;for(;i<o.length-1;){if(this.isTinyStructuralChunk(o[i],n)){let s=this.mergeChunkContents(o[i],o[i+1],n);if(s.length<=r){o.splice(i,2,s);continue}}i++}if(o.length>1){let s=o.length-1;if(this.isTinyStructuralChunk(o[s],n)){let a=this.mergeChunkContents(o[s-1],o[s],n);a.length<=r&&o.splice(s-1,2,a)}}return o}isTinyStructuralChunk(e,n){let r=this.stripChunkHeader(e,n).trim();if(!r)return!0;let o=r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean);return o.length===1&&/^#{1,6}\s+\S+/.test(o[0])}mergeChunkContents(e,n,r){let o=this.stripChunkHeader(e,r).replace(/\s+$/,""),i=this.stripChunkHeader(n,r).replace(/^\s+/,"");return`${r}${o}${o&&i?`

`:""}${i}`}stripChunkHeader(e,n){return e.startsWith(n)?e.slice(n.length):e}calculateChunkBytes(e){return e.reduce((n,r)=>n+p0.getByteSize(r.content),0)}async safeReadFile(e){try{return(await this.app.vault.cachedRead(e))?.trim()||""}catch(n){return ee(`ChunkManager: Failed to read ${e.path}`,n),""}}generateChunkId(e,n){return`${e}#${n}`}calculateContentHash(e){let n=e.length.toString(16),r=e.slice(0,32).replace(/\s/g,"").substring(0,8);return n+r}formatMemoryUsage(){return`${(this.memoryUsage/1024/1024).toFixed(1)}MB`}findFrontmatterEnd(e,n){if(!n||!e.startsWith("---"))return 0;let r=e.match(/\n---(\r?\n|$)/);return r&&r.index!==void 0?r.index+r[0].length:0}},eye=null});var fG,sB,I5e=C(()=>{Ir();o0();ye();b5e();iB();Se();qe();TC();fG=require("obsidian");fc();sB=class{constructor(e,n,r){this.app=e;this.indexBackend=n;this.embeddingsManager=r;this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:0,processedFiles:new Set};this.refreshRuntimeIndexingConfig(),this.chunkManager=PC(e),Ho(()=>{this.refreshRuntimeIndexingConfig()})}refreshRuntimeIndexingConfig(){let e=q();this.rateLimiter=new cG(e.embeddingRequestsPerMin),this.embeddingBatchSize=Math.max(1,e.embeddingBatchSize),this.checkpointInterval=8*this.embeddingBatchSize}async indexVaultToVectorStore(e,n){if(!q().enableSemanticSearchV3)return ee("indexVaultToVectorStore called with semantic search disabled, skipping."),0;let r=[];qte();try{let o=this.indexBackend.requiresEmbeddings(),i=o?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(o&&!i)return z("Embedding instance not found."),Kte({isActive:!1,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:0,errors:["Embedding model not available. Please check your Copilot settings to make sure you have a working embedding model."],completionStatus:"error"}),0;(o?await this.indexBackend.checkAndHandleEmbeddingModelChange(i):!1)&&(e=!0),e?(await this.indexBackend.clearIndex(i),this.indexBackend.clearFilesMissingEmbeddings()):await this.indexBackend.garbageCollect();let a=await this.getFilesToIndex(e);if(a.length===0)return n?.userInitiated&&ul({completionStatus:"success"}),0;this.initializeIndexingState(a.length),this.indexBackend.clearFilesMissingEmbeddings();let l=o&&i?is.getModelName(i):"",c=await this.prepareAllChunks(a,l);if(c.length===0)return qte(),0;if(this.state.isIndexingCancelled||LA().isCancelled)return ul({isActive:!1,completionStatus:"cancelled"}),0;let u=new Set(c.map(f=>f.fileInfo.path)).size;this.state.totalFilesToIndex=u,ul({totalFiles:u});let d=0;for(;d<c.length&&!(this.state.isIndexingCancelled||LA().isCancelled);){await this.handlePause();let f=c.slice(d,d+this.embeddingBatchSize);try{let p=[];if(o&&i){await this.rateLimiter.wait();let g=await i.embedDocuments(f.map(y=>y.content));if(!g||g.length!==f.length)throw new Error(`Embedding model returned ${g?.length??0} embeddings for ${f.length} documents`);for(let y=0;y<f.length;y++){let w=f[y],v=g[y];if(!v||!Array.isArray(v)||v.length===0){z(`Invalid embedding for document ${String(w.fileInfo.path)}: ${JSON.stringify(v)}`),this.indexBackend.markFileMissingEmbeddings(w.fileInfo.path);continue}p.push({doc:{...w.fileInfo,id:this.getDocHash(w.content),content:w.content,embedding:v,created_at:Date.now(),nchars:w.content.length},filePath:w.fileInfo.path})}}else for(let g of f)p.push({doc:{...g.fileInfo,id:this.getDocHash(g.content),content:g.content,embedding:[],created_at:Date.now(),nchars:g.content.length},filePath:g.fileInfo.path});if(p.length>0)try{await this.indexBackend.upsertBatch(p.map(g=>g.doc)),p.forEach(g=>this.state.processedFiles.add(g.filePath))}catch(g){z("Batch upsert failed; falling back to per-document upserts.",g);for(let y of p)try{await this.indexBackend.upsert(y.doc),this.state.processedFiles.add(y.filePath)}catch(w){this.handleError(w,{filePath:y.filePath,errors:r}),o&&this.indexBackend.markFileMissingEmbeddings(y.filePath)}}this.state.indexedCount=this.state.processedFiles.size,oke(this.state.indexedCount);let m=Math.floor((this.state.indexedCount-f.length)/this.checkpointInterval);Math.floor(this.state.indexedCount/this.checkpointInterval)>m&&(await this.indexBackend.save(),k("Copilot index checkpoint save completed."))}catch(p){if(this.handleError(p,{filePath:f?.[0]?.fileInfo?.path,errors:r,batch:f}),this.isRateLimitError(p))break}d+=f.length}return this.finalizeIndexing(r),window.setTimeout(()=>{this.indexBackend.save().then(()=>{k("Copilot index final save completed."),this.indexBackend.checkIndexIntegrity().catch(f=>{z("Background integrity check failed:",f)})}).catch(f=>{z("Background save failed:",f)})},100),this.state.indexedCount}catch(o){return this.handleError(o),ul({isActive:!1,completionStatus:"error",errors:[o instanceof Error?o.message:String(o)]}),0}}async prepareAllChunks(e,n){let r=[];for(let i=0;i<e.length;i+=1e3){let a=e.slice(i,i+1e3).map(c=>c.path),l=await this.chunkManager.getChunks(a);for(let c of l){let u=this.app.vault.getAbstractFileByPath(c.notePath);if(!u||!(u instanceof fG.TFile))continue;let d=this.app.metadataCache.getFileCache(u),f={title:c.title,path:c.notePath,embeddingModel:n,ctime:u.stat.ctime,mtime:c.mtime,tags:d?.tags?.map(p=>p.tag)??[],extension:u.extension,metadata:{...d?.frontmatter??{},created:ll(new Date(u.stat.ctime)).display,modified:ll(new Date(c.mtime)).display,chunkId:c.id,heading:c.heading}};if(c.content.trim()){let p=`METADATA:${JSON.stringify(f.metadata)}

`,m=c.content.indexOf("NOTE BLOCK CONTENT:"),h=m>0?c.content.slice(0,m)+p+c.content.slice(m):c.content;r.push({content:h,chunkId:c.id,fileInfo:f})}}}return r}getDocHash(e){return Jc(e)}async getFilesToIndex(e){let{inclusions:n,exclusions:r}=Bo(),o=this.app.vault.getMarkdownFiles();if(e)return o.filter(u=>Qr(u,n,r));let i=new Set(await this.indexBackend.getIndexedFiles()),s=await this.indexBackend.getLatestFileMtime(),a=new Set(this.indexBackend.getFilesMissingEmbeddings()),l=new Set,c=new Set;for(let u of o){if(!Qr(u,n,r))continue;let d=await this.app.vault.cachedRead(u);if(!d||d.trim().length===0){c.add(u.path);continue}let f=i.has(u.path),p=a.has(u.path);(!f||p||u.stat.mtime>s)&&l.add(u)}return k([`Files to index: ${l.size}`,`Previously indexed: ${i.size}`,`Empty files skipped: ${c.size}`,`Files missing embeddings: ${a.size}`].join(`
`)),Array.from(l)}initializeIndexingState(e){this.state={isIndexingPaused:!1,isIndexingCancelled:!1,indexedCount:0,totalFilesToIndex:e,processedFiles:new Set},Kte({isActive:!0,isPaused:!1,isCancelled:!1,indexedCount:0,totalFiles:e,errors:[],completionStatus:"none"})}async handlePause(){let e=LA();if(this.state.isIndexingPaused=e.isPaused,this.state.isIndexingCancelled=e.isCancelled,this.state.isIndexingPaused){for(;this.state.isIndexingPaused&&!this.state.isIndexingCancelled;){await new Promise(r=>window.setTimeout(r,100));let n=LA();this.state.isIndexingPaused=n.isPaused,this.state.isIndexingCancelled=n.isCancelled}if(!this.state.isIndexingCancelled){this.refreshRuntimeIndexingConfig();let n=await this.getFilesToIndex();if(n.length===0){k("No files to index after filter change, stopping indexing"),await this.cancelIndexing();return}let r=Math.max(this.state.indexedCount+n.length,1);this.state.totalFilesToIndex=r,ul({totalFiles:r})}}}isStringLengthError(e){if(!e)return!1;if(e instanceof RangeError&&e.message.toLowerCase().includes("string length"))return!0;let r=(e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)??"").toLowerCase();return r.includes("string length")||r.includes("rangeerror")}handleError(e,n){let r=n?.filePath;if(r?(n.batch?console.error("Batch processing error:",{error:e,batchSize:n.batch.length||0,firstChunk:n.batch[0]?{path:n.batch[0].fileInfo?.path,contentLength:n.batch[0].content?.length,hasFileInfo:!!n.batch[0].fileInfo}:"No chunks in batch",errorType:e instanceof Error?e.constructor?.name:typeof e,errorMessage:e instanceof Error?e.message:String(e)}):console.error(`Error indexing file ${r}:`,e),n.errors?.push(r)):console.error("Fatal error during indexing:",e),this.isStringLengthError(e)){new fG.Notice("Vault is too large for 1 partition, please increase the number of partitions in your Copilot QA settings!",1e4);return}}isRateLimitError(e){return e instanceof Error&&e.message.toLowerCase().includes("rate limit")||!1}finalizeIndexing(e){if(ike(),this.state.isIndexingCancelled||LA().isCancelled){ul({isActive:!1,completionStatus:"cancelled",errors:e});return}ul({isActive:!1,completionStatus:e.length>0?"error":"success",errors:e,indexedCount:this.state.indexedCount})}async reindexFile(e){try{let n=this.indexBackend.requiresEmbeddings(),r=n?await this.embeddingsManager.getEmbeddingsAPI():void 0;if(n&&!r)return;if(await this.indexBackend.removeByPath(e.path),n&&r&&await this.indexBackend.checkAndHandleEmbeddingModelChange(r)){await this.indexVaultToVectorStore(!0);return}let o=n&&r?is.getModelName(r):"",i=await this.prepareAllChunks([e],o);if(i.length===0)return;if(n&&r){let s=await r.embedDocuments(i.map(a=>a.content));for(let a=0;a<i.length;a++){let l=i[a];await this.indexBackend.upsert({...l.fileInfo,id:this.getDocHash(l.content),content:l.content,embedding:s[a],created_at:Date.now(),nchars:l.content.length})}}else for(let s of i)await this.indexBackend.upsert({...s.fileInfo,id:this.getDocHash(s.content),content:s.content,embedding:[],created_at:Date.now(),nchars:s.content.length});this.indexBackend.markUnsavedChanges(),q().debug&&k(`Reindexed file: ${e.path}`)}catch(n){this.handleError(n,{filePath:e.path})}}async cancelIndexing(){k("Indexing cancelled by user"),this.state.isIndexingCancelled=!0,ul({isCancelled:!0,isActive:!1,completionStatus:"cancelled"}),await new Promise(e=>window.setTimeout(e,100))}}});var ji={};zn(ji,{default:()=>Cp});var aB,Cp,ei=C(()=>{Ir();Nf();ye();o0();yp();Se();aB=require("obsidian");B3e();v5e();x5e();Gge();I5e();Cp=class t{constructor(){this.embeddingsManager=is.getInstance(),this.oramaBackend=new lG(app),this.miyoBackend=new zq(app),this.activeBackendKey=this.getBackendKey(q()),this.indexBackend=this.activeBackendKey==="miyo"?this.miyoBackend:this.oramaBackend,this.indexOps=new sB(app,this.indexBackend,this.embeddingsManager),this.eventHandler=new rB(app,this.indexOps,this.indexBackend),this.initializationPromise=this.initialize(),this.setupSettingsSubscription()}static getInstance(){return t.instance||(t.instance=new t),t.instance}setupSettingsSubscription(){this.lastKnownSettings={...q()};let e=async()=>{let n=q(),r=this.lastKnownSettings;if(this.lastKnownSettings={...n},n.enableIndexSync!==r?.enableIndexSync&&this.activeBackendKey==="orama"){let o=await this.embeddingsManager.getEmbeddingsAPI();await this.oramaBackend.reinitializeForIndexSyncChange(o)}await this.refreshBackend(n,r)};Ho(()=>{this.initializationPromise=e()})}async initialize(){if(q().enableSemanticSearchV3)try{let n=3;for(;n>0;)try{let r=this.indexBackend.requiresEmbeddings()?await this.embeddingsManager.getEmbeddingsAPI():void 0;await this.indexBackend.initialize(r);break}catch(r){if(r instanceof Gn&&r.message.includes("Vault adapter not available")&&(n--,n>0)){await new Promise(o=>window.setTimeout(o,100));continue}new aB.Notice("Failed to initialize vector store. Please make sure you have a valid API key for your embedding model and restart the plugin."),console.error("Failed to initialize vector store:",r);break}}catch(n){console.error("Failed to initialize vector store:",n)}}async waitForInitialization(){await this.initializationPromise}async indexVaultToVectorStore(e,n){if(await this.waitForInitialization(),!q().enableSemanticSearchV3)return ee("indexVaultToVectorStore called with semantic search disabled, skipping."),0;if(this.activeBackendKey==="miyo")return await this.miyoBackend.requestIndexRefresh(!!e),oB(),0;if(aB.Platform.isMobile&&q().disableIndexOnMobile&&!this.indexBackend.isRemoteBackend())return new aB.Notice("Indexing is disabled on mobile devices"),0;let r=await this.indexOps.indexVaultToVectorStore(e,n);return oB(),r}async clearIndex(){await this.waitForInitialization();let e=this.indexBackend.requiresEmbeddings()?await this.embeddingsManager.getEmbeddingsAPI():void 0;await this.indexBackend.clearIndex(e),oB()}async garbageCollectVectorStore(){return await this.waitForInitialization(),this.indexBackend.garbageCollect()}async getIndexedFiles(){return await this.waitForInitialization(),this.indexBackend.getIndexedFiles()}async isIndexEmpty(){return await this.waitForInitialization(),await this.indexBackend.isIndexEmpty()}async hasIndex(e){return await this.waitForInitialization(),this.indexBackend.hasIndex(e)}async getDocumentsByPath(e){return await this.waitForInitialization(),this.indexBackend.getDocumentsByPath(e)}pauseIndexing(){ul({isPaused:!0})}resumeIndexing(){ul({isPaused:!1})}async cancelIndexing(){await this.indexOps.cancelIndexing()}shouldUseMiyo(e){return Fa(e)}getBackendKey(e){return this.shouldUseMiyo(e)?"miyo":"orama"}async refreshBackend(e,n){let r=this.getBackendKey(e);if(r!==this.activeBackendKey){if(this.activeBackendKey=r,this.indexBackend=r==="miyo"?this.miyoBackend:this.oramaBackend,this.indexOps=new sB(app,this.indexBackend,this.embeddingsManager),this.eventHandler.cleanup(),this.eventHandler=new rB(app,this.indexOps,this.indexBackend),q().debug&&k(`VectorStoreManager: switched backend to ${r}`),e.enableSemanticSearchV3){let o=this.indexBackend.requiresEmbeddings()?await this.embeddingsManager.getEmbeddingsAPI():void 0;await this.indexBackend.initialize(o)}n&&e.enableSemanticSearchV3&&e.enableMiyo!==n.enableMiyo&&k("VectorStoreManager: Miyo backend toggled; reindex recommended.")}}onunload(){this.eventHandler.cleanup(),this.indexBackend.onunload()}async getDb(){await this.waitForInitialization();let e=this.oramaBackend.getDb();if(!e)throw new Error("Database is not loaded. Please restart the plugin.");return e}async reindexFile(e){await this.waitForInitialization(),this.activeBackendKey!=="miyo"&&(await this.indexOps.reindexFile(e),oB())}}});function Qhe(){let t=q();return t.selfHostModeValidatedAt==null?!1:t.selfHostValidationCount>=YN?!0:Date.now()-t.selfHostModeValidatedAt<cB}function pc(){return q().enableSelfHostMode?Qhe():!1}function poe(t){return t.split("|")[1]==="copilot-plus"}function P5e(){let t=q();return pc()?!0:t.isPlusUser===!0}function ZN(){let t=Ht();return t.plusLicenseKey&&t.enableSelfHostMode&&t.selfHostModeValidatedAt!=null&&(t.selfHostValidationCount>=YN||Date.now()-t.selfHostModeValidatedAt<cB)?!0:t.isPlusUser}async function _p(t){return pc()?!0:q().plusLicenseKey?(await di.getInstance().validateLicenseKey(t)).isValid:(lye(),!1)}async function sye(){if(!q().plusLicenseKey)return!1;let n=(await di.getInstance().validateLicenseKey()).plan?.toLowerCase();return n!=null&&V2t.includes(n)}function E5e(){let t=Ht(),[e,n]=nye.default.useState(void 0);return nye.default.useEffect(()=>{if(!t.plusLicenseKey){t.enableSelfHostMode&&pe("enableSelfHostMode",!1),n(!1);return}sye().then(r=>{!r&&t.enableSelfHostMode&&pe("enableSelfHostMode",!1),n(r)}).catch(()=>{if(t.selfHostValidationCount>=YN){n(!0);return}if(t.selfHostModeValidatedAt!=null&&Date.now()-t.selfHostModeValidatedAt<cB){n(!0);return}n(!1)})},[t.plusLicenseKey,t.enableSelfHostMode,t.selfHostModeValidatedAt,t.selfHostValidationCount]),e}async function A5e(){let t=q();if(t.selfHostValidationCount>=YN)return pe("selfHostModeValidatedAt",Date.now()),k("Self-host mode re-enabled (permanently validated)"),!0;if(t.selfHostModeValidatedAt!=null&&Date.now()-t.selfHostModeValidatedAt<cB)return k("Self-host mode re-enabled (within grace period)"),!0;if(!await sye())return k("Self-host mode requires an eligible plan (Believer, Supporter)"),new lB.Notice("Self-host mode is only available for Believer and Supporter plan subscribers."),!1;let n=Math.max(t.selfHostValidationCount||0,1);return pe("selfHostModeValidatedAt",Date.now()),pe("selfHostValidationCount",n),k(`Self-host mode validation successful (${n}/3)`),!0}async function k5e(){let t=q();if(!(!t.enableSelfHostMode&&!t.enableMiyo)){if(t.selfHostValidationCount>=YN){k("Self-host mode permanently validated, skipping refresh");return}try{if(await sye()){let n=Date.now();if(n-(t.selfHostModeValidatedAt||0)>=cB){let i=(t.selfHostValidationCount||0)+1;pe("selfHostModeValidatedAt",n),pe("selfHostValidationCount",i),i>=YN?(k("Self-host mode permanently validated (3/3)"),new lB.Notice("Self-host mode is now permanently enabled!")):k(`Self-host mode validation refreshed (${i}/3)`)}else k("Self-host mode validated (waiting for 15-day interval to increment count)")}else pe("enableSelfHostMode",!1),pe("enableMiyo",!1),pe("selfHostModeValidatedAt",null),pe("selfHostValidationCount",0),k("Self-host mode disabled - user is no longer on an eligible plan"),new lB.Notice("Self-host mode has been disabled. An eligible plan is required.")}catch(e){k("Could not refresh self-host mode validation (offline?):",e)}}}function M5e(){let t=j2t,e=iye,n=q().embeddingModelKey;k("applyPlusSettings: Changing embedding model",{from:n,to:e,changed:n!==e}),ZAe(t),XAe("copilot_plus"),Ls({defaultModelKey:t,embeddingModelKey:e,defaultChainType:"copilot_plus"}),n!==e?(k("applyPlusSettings: Embedding model changed, triggering indexing"),Promise.resolve().then(()=>(ei(),ji)).then(async r=>{await r.default.getInstance().indexVaultToVectorStore()}).catch(r=>{z("Failed to trigger indexing after Plus settings applied:",r),new lB.Notice("Failed to update Copilot index. Please try force reindexing from the command palette.")})):k("applyPlusSettings: No embedding model change, skipping indexing")}function aye(t){return`https://www.obsidiancopilot.com?utm_source=obsidian&utm_medium=${t}`}function hT(t){window.open(aye(t),"_blank")}function N5e(){pe("isPlusUser",!0)}function lye(){let t=q().isPlusUser;pe("isPlusUser",!1),t&&new x6(app).open()}var lB,nye,rye,j2t,oye,iye,cB,YN,V2t,ns=C(()=>{Ir();Qi();ULe();It();Zg();ye();Se();lB=require("obsidian"),nye=N(U()),rye="copilot-plus-flash",j2t=rye+"|"+"copilot-plus",oye="copilot-plus-small",iye=oye+"|"+"copilot-plus",cB=15*24*60*60*1e3,YN=3,V2t=["believer","supporter"]});function EC(t){return O5e.Buffer.from(t).toString("base64")}var O5e,pG=C(()=>{O5e=N(uD())});async function W2t(t){let e=`----CopilotBoundary${Math.random().toString(16).slice(2)}${Date.now().toString(16)}`,n=new TextEncoder,r=[];for(let[a,l]of t.entries())if(r.push(n.encode(`--${e}\r
`)),l instanceof Blob){let c=l instanceof File?l.name:"blob",u=l.type||"application/octet-stream";r.push(n.encode(`Content-Disposition: form-data; name="${a}"; filename="${c}"\r
Content-Type: ${u}\r
\r
`));let d=await l.arrayBuffer();r.push(new Uint8Array(d)),r.push(n.encode(`\r
`))}else r.push(n.encode(`Content-Disposition: form-data; name="${a}"\r
\r
`)),r.push(n.encode(String(l))),r.push(n.encode(`\r
`));r.push(n.encode(`--${e}--\r
`));let o=r.reduce((a,l)=>a+l.byteLength,0),i=new Uint8Array(o),s=0;for(let a of r)i.set(a,s),s+=a.byteLength;return{body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),contentType:`multipart/form-data; boundary=${e}`}}function R5e(t,e){let n=t.json;if(typeof n=="string")try{n=JSON.parse(n)}catch{}if(t.status<200||t.status>=300){let r=n?.detail;if(r?.reason){let o=new Error(r.reason);return r.error&&(o.name=r.error),{data:null,error:o}}return{data:null,error:new Error(`HTTP error: ${t.status}`)}}return k(`[API ${e} request]:`,n),{data:n}}var cye,di,Zg=C(()=>{It();Su();Nf();ye();ns();Se();pG();cye=require("obsidian");di=class t{constructor(){this.pluginVersion="Unknown"}static getInstance(){return t.instance||(t.instance=new t),t.instance}checkLicenseKey(){if(!q().plusLicenseKey)throw new DS("Copilot Plus license key not found. Please enter your license key in the settings.")}setPluginVersion(e){this.pluginVersion=e}async makeRequest(e,n,r="POST",o=!1,i=!1){i||this.checkLicenseKey(),n.user_id=q().userId;let s=new URL(`${XQ}${e}`);r==="GET"&&Object.entries(n).forEach(([c,u])=>{s.searchParams.append(c,u)});let a={"Content-Type":"application/json","X-Client-Version":this.pluginVersion};o||(a.Authorization=`Bearer ${await pn(q().plusLicenseKey)}`);let l=await(0,cye.requestUrl)({url:s.toString(),method:r,headers:a,...r==="POST"&&{body:JSON.stringify(n)},throw:!1});return R5e(l,e)}async makeFormDataRequest(e,n,r=!1){r||this.checkLicenseKey(),n.append("user_id",q().userId);let o=new URL(`${XQ}${e}`);try{let{body:i,contentType:s}=await W2t(n),a=await(0,cye.requestUrl)({url:o.toString(),method:"POST",headers:{"Content-Type":s,Authorization:`Bearer ${await pn(q().plusLicenseKey)}`,"X-Client-Version":this.pluginVersion},body:i,throw:!1});return R5e(a,`${e} form-data`)}catch(i){return{data:null,error:i instanceof Error?i:new Error(String(i))}}}async validateLicenseKey(e){let n={license_key:await pn(q().plusLicenseKey)};if(e&&typeof e=="object"){let i=Object.fromEntries(Object.entries(e).filter(([a,l])=>l!=null)),s=new Set(["license_key","user_id"]);for(let a of s)a in i&&delete i[a];Object.assign(n,i)}let{data:r,error:o}=await this.makeRequest("/license",n,"POST",!0,!0);return o?o.message==="Invalid license key"?(lye(),{isValid:!1}):{isValid:void 0}:(N5e(),{isValid:!0,plan:r?.plan})}async rerank(e,n){let{data:r,error:o}=await this.makeRequest("/rerank",{query:e,documents:n,model:"rerank-2"});if(o)throw o;if(!r)throw new Error("No data returned from rerank");return r}async url4llm(e){let{data:n,error:r}=await this.makeRequest("/url4llm",{url:e});if(r)throw r;if(!n)throw new Error("No data returned from url4llm");return n}async pdf4llm(e){let n=EC(e),{data:r,error:o}=await this.makeRequest("/pdf4llm",{pdf:n});if(o)throw o;if(!r)throw new Error("No data returned from pdf4llm");return r}async docs4llm(e,n){let r=new FormData,o=this.getMimeTypeFromExtension(n),i=new Blob([e],{type:o}),s=`file.${n}`,a=new File([i],s,{type:o});r.append("files",a),r.append("file_type",n);let{data:l,error:c}=await this.makeFormDataRequest("/docs4llm",r);if(c)throw c;if(!l)throw new Error("No data returned from docs4llm");return l}getMimeTypeFromExtension(e){return{pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",epub:"application/epub+zip",txt:"text/plain",rtf:"application/rtf",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",bmp:"image/bmp",svg:"image/svg+xml",tiff:"image/tiff",webp:"image/webp",html:"text/html",htm:"text/html",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xls:"application/vnd.ms-excel",csv:"text/csv",mp3:"audio/mpeg",mp4:"video/mp4",wav:"audio/wav",webm:"video/webm"}[e.toLowerCase()]||"application/octet-stream"}async webSearch(e){let{data:n,error:r}=await this.makeRequest("/websearch",{query:e});if(r)throw r;if(!n)throw new Error("No data returned from websearch");return n}async youtube4llm(e){let{data:n,error:r}=await this.makeRequest("/youtube4llm",{url:e});if(r)throw r;if(!n)throw new Error("No data returned from youtube4llm");return n}async twitter4llm(e){let{data:n,error:r}=await this.makeRequest("/twitter4llm",{url:e});if(r)throw r;if(!n)throw new Error("No data returned from twitter4llm");return n}}});var K5e={};zn(K5e,{isInVaultCache:()=>P0,listMarkdownFiles:()=>dB,patchFrontmatter:()=>LC,readFrontmatterViaAdapter:()=>oy,resolveFileByPath:()=>I0,trashFile:()=>Qc});async function Qc(t,e){await t.fileManager.trashFile(e)}async function I0(t,e){let n=t.vault.getAbstractFileByPath(e);return n instanceof nO.TFile?n:await t.vault.adapter.exists(e)?H5e(t,e):null}function P0(t,e){return t.vault.getAbstractFileByPath(e)!=null}async function dB(t,e){let n=t.vault.getAbstractFileByPath(e);if(n instanceof nO.TFolder)return t.vault.getMarkdownFiles().filter(r=>r.path.startsWith(n.path));if(await t.vault.adapter.exists(e)){let o=(await t.vault.adapter.list(e)).files.filter(s=>s.endsWith(".md")),i=[];for(let s of o)i.push(await H5e(t,s));return i}return[]}async function LC(t,e,n){let r=t.vault.getAbstractFileByPath(e);if(r instanceof nO.TFile&&t.fileManager?.processFrontMatter){await t.fileManager.processFrontMatter(r,a=>{for(let[l,c]of Object.entries(n))a[l]=c});return}if(!await t.vault.adapter.exists(e))return;let o=await t.vault.adapter.read(e),i=o.includes(`\r
`)?`\r
`:`
`,s=o.replace(/^(\uFEFF?---\r?\n[\s\S]*?\r?\n)(---)/,(a,l,c)=>{let u=l;for(let[d,f]of Object.entries(n)){let p=typeof f=="string"?`"${f.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:String(f),m=new RegExp(`^${d}:\\s*.+`,"m");m.test(u)?u=u.replace(m,`${d}: ${p}`):u+=`${d}: ${p}${i}`}return u+c});s!==o&&await t.vault.adapter.write(e,s)}async function oy(t,e){let o=(await t.vault.adapter.read(e)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1];if(!o)return null;let i={};for(let s of o.split(/\r?\n/)){let a=s.match(/^([\w-]+):\s*(.+)/);a&&(i[a[1]]=a[2].trim().replace(/^["']|["']$/g,""))}return i}async function H5e(t,e){let n=await t.vault.adapter.stat(e),r=e.split("/").pop()??"",o=Object.create(nO.TFile.prototype);return Object.assign(o,{path:e,name:r,basename:r.replace(/\.md$/,""),extension:"md",stat:n??{ctime:Date.now(),mtime:Date.now(),size:0},vault:t.vault,parent:null}),o}var nO,av=C(()=>{nO=require("obsidian")});var uqe={};zn(uqe,{createToolCallMarker:()=>sUt,parseToolCallMarkers:()=>gye,updateToolCallMarker:()=>aUt});function cqe(t){try{return`ENC:${encodeURIComponent(t)}`}catch{return t}}function oUt(t){if(typeof t!="string"||!t.startsWith("ENC:"))return t;try{return decodeURIComponent(t.slice(4))}catch{return t}}function iUt(t){return`Tool '${t}' ${rUt}`}function hye(t,e=0,n=""){let r=[],o=/<errorChunk>([\s\S]*?)<\/errorChunk>/g,i=0,s;for(;(s=o.exec(t))!==null;){s.index>i&&r.push({type:"text",content:t.slice(i,s.index)});let[a,l]=s,c=e+s.index,u=n?`${n}-error-${c}`:`error-${c}`;r.push({type:"error",content:l,error:{id:u,errorContent:l,startIndex:c,endIndex:e+s.index+a.length}}),i=s.index+a.length}return i<t.length&&r.push({type:"text",content:t.slice(i)}),r.length===0&&r.push({type:"text",content:t}),r}function gye(t,e){let n=[],r=/<!--TOOL_CALL_START:([^:]+):([^:]+):([^:]+):([^:]+):([^:]*):([^:]+)-->([\s\S]*?)<!--TOOL_CALL_END:\1:([\s\S]*?)-->/g,o=0,i;for(;(i=r.exec(t))!==null;){if(i.index>o){let v=t.slice(o,i.index);hye(v,o,e).forEach(b=>{b.type==="text"&&b.content.trim()?n.push({type:"text",content:b.content}):b.type==="error"&&b.error&&n.push({type:"error",content:b.content,error:b.error})})}let[s,a,l,c,u,d,f,p,m]=i,g=oUt(typeof m=="string"?m:""),w=(typeof g=="string"?g.length:0)>5e3?iUt(l):g??void 0;n.push({type:"toolCall",content:p,toolCall:{id:a,toolName:l,displayName:c,emoji:u,confirmationMessage:d||void 0,isExecuting:f==="true",result:w,startIndex:i.index,endIndex:i.index+s.length}}),o=i.index+s.length}if(o<t.length){let s=t.slice(o);hye(s,o,e).forEach(l=>{l.type==="text"&&l.content.trim()?n.push({type:"text",content:l.content}):l.type==="error"&&l.error&&n.push({type:"error",content:l.content,error:l.error})})}return n.length===0&&hye(t,0,e).forEach(a=>{a.type==="text"?n.push({type:"text",content:a.content}):a.type==="error"&&a.error&&n.push({type:"error",content:a.content,error:a.error})}),{segments:n}}function sUt(t,e,n,r,o="",i=!0,s="",a=""){let l=a&&cqe(a);return`<!--TOOL_CALL_START:${t}:${e}:${n}:${r}:${o}:${i}-->${s}<!--TOOL_CALL_END:${t}:${l}-->`}function aUt(t,e,n){let r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(<!--TOOL_CALL_START:${r}:[^:]+:[^:]+:[^:]+:[^:]*:)true(-->[\\s\\S]*?<!--TOOL_CALL_END:${r}:)[\\s\\S]*?-->`,"g"),i=cqe(n);return t.replace(o,`$1false$2${i}-->`)}var rUt,yye=C(()=>{rUt=`Result omitted to keep the UI responsive (payload exceeded ${5e3.toLocaleString()} characters).`});var ay,lO=C(()=>{$n();Hb();Ng();Ra();ay=class extends gr{constructor(e){super(e);I(this,"callbacks");I(this,"tags");I(this,"metadata");I(this,"verbose");this.callbacks=e?.callbacks,this.tags=e?.tags??[],this.metadata=e?.metadata??{},this.verbose=e?.verbose??!1}_getRelevantDocuments(e,n){throw new Error("Not implemented!")}async invoke(e,n){let r=fr(Wb(n)),o=await(await Ws.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}))?.handleRetrieverStart(this.toJSON(),e,r.runId,void 0,void 0,void 0,r.runName);try{let i=await this._getRelevantDocuments(e,o);return await o?.handleRetrieverEnd(i),i}catch(i){throw await o?.handleRetrieverError(i),i}}}});var hUt,xqe,bqe,Tl,gB,cO,gUt,Cqe,yB,OG,Tye,bye,yUt,_qe,Sqe,Eye,Aye,Tqe,wUt,wB,Cye,vUt,xUt,bUt,CUt,_ye,gqe,_Ut,Iye,Pye,Sye,SUt,yqe,wqe,vqe,MG,NG,Iqe,TUt,Pqe=C(()=>{hUt="ENTRIES",xqe="KEYS",bqe="VALUES",Tl="",gB=class{constructor(e,n){let r=e._tree,o=Array.from(r.keys());this.set=e,this._type=n,this._path=o.length>0?[{node:r,keys:o}]:[]}next(){let e=this.dive();return this.backtrack(),e}dive(){if(this._path.length===0)return{done:!0,value:void 0};let{node:e,keys:n}=cO(this._path);if(cO(n)===Tl)return{done:!1,value:this.result()};let r=e.get(cO(n));return this._path.push({node:r,keys:Array.from(r.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;let e=cO(this._path).keys;e.pop(),!(e.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:e})=>cO(e)).filter(e=>e!==Tl).join("")}value(){return cO(this._path).node.get(Tl)}result(){switch(this._type){case bqe:return this.value();case xqe:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}},cO=t=>t[t.length-1],gUt=(t,e,n)=>{let r=new Map;if(e===void 0)return r;let o=e.length+1,i=o+n,s=new Uint8Array(i*o).fill(n+1);for(let a=0;a<o;++a)s[a]=a;for(let a=1;a<i;++a)s[a*o]=a;return Cqe(t,e,n,r,s,1,o,""),r},Cqe=(t,e,n,r,o,i,s,a)=>{let l=i*s;e:for(let c of t.keys())if(c===Tl){let u=o[l-1];u<=n&&r.set(a,[t.get(c),u])}else{let u=i;for(let d=0;d<c.length;++d,++u){let f=c[d],p=s*u,m=p-s,h=o[p],g=Math.max(0,u-n-1),y=Math.min(s-1,u+n);for(let w=g;w<y;++w){let v=f!==e[w],x=o[m+w]+ +v,b=o[m+w+1]+1,_=o[p+w]+1,T=o[p+w+1]=Math.min(x,b,_);T<h&&(h=T)}if(h>n)continue e}Cqe(t.get(c),e,n,r,o,u,s,a+c)}},yB=class t{constructor(e=new Map,n=""){this._size=void 0,this._tree=e,this._prefix=n}atPrefix(e){if(!e.startsWith(this._prefix))throw new Error("Mismatched prefix");let[n,r]=OG(this._tree,e.slice(this._prefix.length));if(n===void 0){let[o,i]=Eye(r);for(let s of o.keys())if(s!==Tl&&s.startsWith(i)){let a=new Map;return a.set(s.slice(i.length),o.get(s)),new t(a,e)}}return new t(n,e)}clear(){this._size=void 0,this._tree.clear()}delete(e){return this._size=void 0,yUt(this._tree,e)}entries(){return new gB(this,hUt)}forEach(e){for(let[n,r]of this)e(n,r,this)}fuzzyGet(e,n){return gUt(this._tree,e,n)}get(e){let n=Tye(this._tree,e);return n!==void 0?n.get(Tl):void 0}has(e){let n=Tye(this._tree,e);return n!==void 0&&n.has(Tl)}keys(){return new gB(this,xqe)}set(e,n){if(typeof e!="string")throw new Error("key must be a string");return this._size=void 0,bye(this._tree,e).set(Tl,n),this}get size(){if(this._size)return this._size;this._size=0;let e=this.entries();for(;!e.next().done;)this._size+=1;return this._size}update(e,n){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let r=bye(this._tree,e);return r.set(Tl,n(r.get(Tl))),this}fetch(e,n){if(typeof e!="string")throw new Error("key must be a string");this._size=void 0;let r=bye(this._tree,e),o=r.get(Tl);return o===void 0&&r.set(Tl,o=n()),o}values(){return new gB(this,bqe)}[Symbol.iterator](){return this.entries()}static from(e){let n=new t;for(let[r,o]of e)n.set(r,o);return n}static fromObject(e){return t.from(Object.entries(e))}},OG=(t,e,n=[])=>{if(e.length===0||t==null)return[t,n];for(let r of t.keys())if(r!==Tl&&e.startsWith(r))return n.push([t,r]),OG(t.get(r),e.slice(r.length),n);return n.push([t,e]),OG(void 0,"",n)},Tye=(t,e)=>{if(e.length===0||t==null)return t;for(let n of t.keys())if(n!==Tl&&e.startsWith(n))return Tye(t.get(n),e.slice(n.length))},bye=(t,e)=>{let n=e.length;e:for(let r=0;t&&r<n;){for(let i of t.keys())if(i!==Tl&&e[r]===i[0]){let s=Math.min(n-r,i.length),a=1;for(;a<s&&e[r+a]===i[a];)++a;let l=t.get(i);if(a===i.length)t=l;else{let c=new Map;c.set(i.slice(a),l),t.set(e.slice(r,r+a),c),t.delete(i),t=c}r+=a;continue e}let o=new Map;return t.set(e.slice(r),o),o}return t},yUt=(t,e)=>{let[n,r]=OG(t,e);if(n!==void 0){if(n.delete(Tl),n.size===0)_qe(r);else if(n.size===1){let[o,i]=n.entries().next().value;Sqe(r,o,i)}}},_qe=t=>{if(t.length===0)return;let[e,n]=Eye(t);if(e.delete(n),e.size===0)_qe(t.slice(0,-1));else if(e.size===1){let[r,o]=e.entries().next().value;r!==Tl&&Sqe(t.slice(0,-1),r,o)}},Sqe=(t,e,n)=>{if(t.length===0)return;let[r,o]=Eye(t);r.set(o+e,n),r.delete(o)},Eye=t=>t[t.length-1],Aye="or",Tqe="and",wUt="and_not",wB=class t{constructor(e){if(e?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');let n=e.autoVacuum==null||e.autoVacuum===!0?Sye:e.autoVacuum;this._options={..._ye,...e,autoVacuum:n,searchOptions:{...gqe,...e.searchOptions||{}},autoSuggestOptions:{..._Ut,...e.autoSuggestOptions||{}}},this._index=new yB,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=Pye,this.addFields(this._options.fields)}add(e){let{extractField:n,stringifyField:r,tokenize:o,processTerm:i,fields:s,idField:a}=this._options,l=n(e,a);if(l==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);if(this._idToShortId.has(l))throw new Error(`MiniSearch: duplicate ID ${l}`);let c=this.addDocumentId(l);this.saveStoredFields(c,e);for(let u of s){let d=n(e,u);if(d==null)continue;let f=o(r(d,u),u),p=this._fieldIds[u],m=new Set(f).size;this.addFieldLength(c,p,this._documentCount-1,m);for(let h of f){let g=i(h,u);if(Array.isArray(g))for(let y of g)this.addTerm(p,c,y);else g&&this.addTerm(p,c,g)}}}addAll(e){for(let n of e)this.add(n)}addAllAsync(e,n={}){let{chunkSize:r=10}=n,o={chunk:[],promise:Promise.resolve()},{chunk:i,promise:s}=e.reduce(({chunk:a,promise:l},c,u)=>(a.push(c),(u+1)%r===0?{chunk:[],promise:l.then(()=>new Promise(d=>setTimeout(d,0))).then(()=>this.addAll(a))}:{chunk:a,promise:l}),o);return s.then(()=>this.addAll(i))}remove(e){let{tokenize:n,processTerm:r,extractField:o,stringifyField:i,fields:s,idField:a}=this._options,l=o(e,a);if(l==null)throw new Error(`MiniSearch: document does not have ID field "${a}"`);let c=this._idToShortId.get(l);if(c==null)throw new Error(`MiniSearch: cannot remove document with ID ${l}: it is not in the index`);for(let u of s){let d=o(e,u);if(d==null)continue;let f=n(i(d,u),u),p=this._fieldIds[u],m=new Set(f).size;this.removeFieldLength(c,p,this._documentCount,m);for(let h of f){let g=r(h,u);if(Array.isArray(g))for(let y of g)this.removeTerm(p,c,y);else g&&this.removeTerm(p,c,g)}}this._storedFields.delete(c),this._documentIds.delete(c),this._idToShortId.delete(l),this._fieldLength.delete(c),this._documentCount-=1}removeAll(e){if(e)for(let n of e)this.remove(n);else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new yB,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}}discard(e){let n=this._idToShortId.get(e);if(n==null)throw new Error(`MiniSearch: cannot discard document with ID ${e}: it is not in the index`);this._idToShortId.delete(e),this._documentIds.delete(n),this._storedFields.delete(n),(this._fieldLength.get(n)||[]).forEach((r,o)=>{this.removeFieldLength(n,o,this._documentCount,r)}),this._fieldLength.delete(n),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;let{minDirtFactor:e,minDirtCount:n,batchSize:r,batchWait:o}=this._options.autoVacuum;this.conditionalVacuum({batchSize:r,batchWait:o},{minDirtCount:n,minDirtFactor:e})}discardAll(e){let n=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(let r of e)this.discard(r)}finally{this._options.autoVacuum=n}this.maybeAutoVacuum()}replace(e){let{idField:n,extractField:r}=this._options,o=r(e,n);this.discard(o),this.add(e)}vacuum(e={}){return this.conditionalVacuum(e)}conditionalVacuum(e,n){return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&n,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(()=>{let r=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=Pye,this.performVacuuming(e,r)}),this._enqueuedVacuum)):this.vacuumConditionsMet(n)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(e),this._currentVacuum)}async performVacuuming(e,n){let r=this._dirtCount;if(this.vacuumConditionsMet(n)){let o=e.batchSize||Iye.batchSize,i=e.batchWait||Iye.batchWait,s=1;for(let[a,l]of this._index){for(let[c,u]of l)for(let[d]of u)this._documentIds.has(d)||(u.size<=1?l.delete(c):u.delete(d));this._index.get(a).size===0&&this._index.delete(a),s%o===0&&await new Promise(c=>setTimeout(c,i)),s+=1}this._dirtCount-=r}await null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null}vacuumConditionsMet(e){if(e==null)return!0;let{minDirtCount:n,minDirtFactor:r}=e;return n=n||Sye.minDirtCount,r=r||Sye.minDirtFactor,this.dirtCount>=n&&this.dirtFactor>=r}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(e){return this._idToShortId.has(e)}getStoredFields(e){let n=this._idToShortId.get(e);if(n!=null)return this._storedFields.get(n)}search(e,n={}){let{searchOptions:r}=this._options,o={...r,...n},i=this.executeQuery(e,n),s=[];for(let[a,{score:l,terms:c,match:u}]of i){let d=c.length||1,f={id:this._documentIds.get(a),score:l*d,terms:Object.keys(u),queryTerms:c,match:u};Object.assign(f,this._storedFields.get(a)),(o.filter==null||o.filter(f))&&s.push(f)}return e===t.wildcard&&o.boostDocument==null||s.sort(wqe),s}autoSuggest(e,n={}){n={...this._options.autoSuggestOptions,...n};let r=new Map;for(let{score:i,terms:s}of this.search(e,n)){let a=s.join(" "),l=r.get(a);l!=null?(l.score+=i,l.count+=1):r.set(a,{score:i,terms:s,count:1})}let o=[];for(let[i,{score:s,terms:a,count:l}]of r)o.push({suggestion:i,terms:a,score:s/l});return o.sort(wqe),o}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(e,n){if(n==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(e),n)}static async loadJSONAsync(e,n){if(n==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJSAsync(JSON.parse(e),n)}static getDefault(e){if(_ye.hasOwnProperty(e))return Cye(_ye,e);throw new Error(`MiniSearch: unknown option "${e}"`)}static loadJS(e,n){let{index:r,documentIds:o,fieldLength:i,storedFields:s,serializationVersion:a}=e,l=this.instantiateMiniSearch(e,n);l._documentIds=MG(o),l._fieldLength=MG(i),l._storedFields=MG(s);for(let[c,u]of l._documentIds)l._idToShortId.set(u,c);for(let[c,u]of r){let d=new Map;for(let f of Object.keys(u)){let p=u[f];a===1&&(p=p.ds),d.set(parseInt(f,10),MG(p))}l._index.set(c,d)}return l}static async loadJSAsync(e,n){let{index:r,documentIds:o,fieldLength:i,storedFields:s,serializationVersion:a}=e,l=this.instantiateMiniSearch(e,n);l._documentIds=await NG(o),l._fieldLength=await NG(i),l._storedFields=await NG(s);for(let[u,d]of l._documentIds)l._idToShortId.set(d,u);let c=0;for(let[u,d]of r){let f=new Map;for(let p of Object.keys(d)){let m=d[p];a===1&&(m=m.ds),f.set(parseInt(p,10),await NG(m))}++c%1e3===0&&await Iqe(0),l._index.set(u,f)}return l}static instantiateMiniSearch(e,n){let{documentCount:r,nextId:o,fieldIds:i,averageFieldLength:s,dirtCount:a,serializationVersion:l}=e;if(l!==1&&l!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");let c=new t(n);return c._documentCount=r,c._nextId=o,c._idToShortId=new Map,c._fieldIds=i,c._avgFieldLength=s,c._dirtCount=a||0,c._index=new yB,c}executeQuery(e,n={}){if(e===t.wildcard)return this.executeWildcardQuery(n);if(typeof e!="string"){let f={...n,...e,queries:void 0},p=e.queries.map(m=>this.executeQuery(m,f));return this.combineResults(p,f.combineWith)}let{tokenize:r,processTerm:o,searchOptions:i}=this._options,s={tokenize:r,processTerm:o,...i,...n},{tokenize:a,processTerm:l}=s,d=a(e).flatMap(f=>l(f)).filter(f=>!!f).map(CUt(s)).map(f=>this.executeQuerySpec(f,s));return this.combineResults(d,s.combineWith)}executeQuerySpec(e,n){let r={...this._options.searchOptions,...n},o=(r.fields||this._options.fields).reduce((h,g)=>({...h,[g]:Cye(r.boost,g)||1}),{}),{boostDocument:i,weights:s,maxFuzzy:a,bm25:l}=r,{fuzzy:c,prefix:u}={...gqe.weights,...s},d=this._index.get(e.term),f=this.termResults(e.term,e.term,1,e.termBoost,d,o,i,l),p,m;if(e.prefix&&(p=this._index.atPrefix(e.term)),e.fuzzy){let h=e.fuzzy===!0?.2:e.fuzzy,g=h<1?Math.min(a,Math.round(e.term.length*h)):h;g&&(m=this._index.fuzzyGet(e.term,g))}if(p)for(let[h,g]of p){let y=h.length-e.term.length;if(!y)continue;m?.delete(h);let w=u*h.length/(h.length+.3*y);this.termResults(e.term,h,w,e.termBoost,g,o,i,l,f)}if(m)for(let h of m.keys()){let[g,y]=m.get(h);if(!y)continue;let w=c*h.length/(h.length+y);this.termResults(e.term,h,w,e.termBoost,g,o,i,l,f)}return f}executeWildcardQuery(e){let n=new Map,r={...this._options.searchOptions,...e};for(let[o,i]of this._documentIds){let s=r.boostDocument?r.boostDocument(i,"",this._storedFields.get(o)):1;n.set(o,{score:s,terms:[],match:{}})}return n}combineResults(e,n=Aye){if(e.length===0)return new Map;let r=n.toLowerCase(),o=vUt[r];if(!o)throw new Error(`Invalid combination operator: ${n}`);return e.reduce(o)||new Map}toJSON(){let e=[];for(let[n,r]of this._index){let o={};for(let[i,s]of r)o[i]=Object.fromEntries(s);e.push([n,o])}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:e,serializationVersion:2}}termResults(e,n,r,o,i,s,a,l,c=new Map){if(i==null)return c;for(let u of Object.keys(s)){let d=s[u],f=this._fieldIds[u],p=i.get(f);if(p==null)continue;let m=p.size,h=this._avgFieldLength[f];for(let g of p.keys()){if(!this._documentIds.has(g)){this.removeTerm(f,g,n),m-=1;continue}let y=a?a(this._documentIds.get(g),n,this._storedFields.get(g)):1;if(!y)continue;let w=p.get(g),v=this._fieldLength.get(g)[f],x=bUt(w,m,this._documentCount,v,h,l),b=r*o*d*y*x,_=c.get(g);if(_){_.score+=b,SUt(_.terms,e);let T=Cye(_.match,n);T?T.push(u):_.match[n]=[u]}else c.set(g,{score:b,terms:[e],match:{[n]:[u]}})}}return c}addTerm(e,n,r){let o=this._index.fetch(r,vqe),i=o.get(e);if(i==null)i=new Map,i.set(n,1),o.set(e,i);else{let s=i.get(n);i.set(n,(s||0)+1)}}removeTerm(e,n,r){if(!this._index.has(r)){this.warnDocumentChanged(n,e,r);return}let o=this._index.fetch(r,vqe),i=o.get(e);i==null||i.get(n)==null?this.warnDocumentChanged(n,e,r):i.get(n)<=1?i.size<=1?o.delete(e):i.delete(n):i.set(n,i.get(n)-1),this._index.get(r).size===0&&this._index.delete(r)}warnDocumentChanged(e,n,r){for(let o of Object.keys(this._fieldIds))if(this._fieldIds[o]===n){this._options.logger("warn",`MiniSearch: document with ID ${this._documentIds.get(e)} has changed before removal: term "${r}" was not present in field "${o}". Removing a document after it has changed can corrupt the index!`,"version_conflict");return}}addDocumentId(e){let n=this._nextId;return this._idToShortId.set(e,n),this._documentIds.set(n,e),this._documentCount+=1,this._nextId+=1,n}addFields(e){for(let n=0;n<e.length;n++)this._fieldIds[e[n]]=n}addFieldLength(e,n,r,o){let i=this._fieldLength.get(e);i==null&&this._fieldLength.set(e,i=[]),i[n]=o;let a=(this._avgFieldLength[n]||0)*r+o;this._avgFieldLength[n]=a/(r+1)}removeFieldLength(e,n,r,o){if(r===1){this._avgFieldLength[n]=0;return}let i=this._avgFieldLength[n]*r-o;this._avgFieldLength[n]=i/(r-1)}saveStoredFields(e,n){let{storeFields:r,extractField:o}=this._options;if(r==null||r.length===0)return;let i=this._storedFields.get(e);i==null&&this._storedFields.set(e,i={});for(let s of r){let a=o(n,s);a!==void 0&&(i[s]=a)}}};wB.wildcard=Symbol("*");Cye=(t,e)=>Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0,vUt={[Aye]:(t,e)=>{for(let n of e.keys()){let r=t.get(n);if(r==null)t.set(n,e.get(n));else{let{score:o,terms:i,match:s}=e.get(n);r.score=r.score+o,r.match=Object.assign(r.match,s),yqe(r.terms,i)}}return t},[Tqe]:(t,e)=>{let n=new Map;for(let r of e.keys()){let o=t.get(r);if(o==null)continue;let{score:i,terms:s,match:a}=e.get(r);yqe(o.terms,s),n.set(r,{score:o.score+i,terms:o.terms,match:Object.assign(o.match,a)})}return n},[wUt]:(t,e)=>{for(let n of e.keys())t.delete(n);return t}},xUt={k:1.2,b:.7,d:.5},bUt=(t,e,n,r,o,i)=>{let{k:s,b:a,d:l}=i;return Math.log(1+(n-e+.5)/(e+.5))*(l+t*(s+1)/(t+s*(1-a+a*r/o)))},CUt=t=>(e,n,r)=>{let o=typeof t.fuzzy=="function"?t.fuzzy(e,n,r):t.fuzzy||!1,i=typeof t.prefix=="function"?t.prefix(e,n,r):t.prefix===!0,s=typeof t.boostTerm=="function"?t.boostTerm(e,n,r):1;return{term:e,fuzzy:o,prefix:i,termBoost:s}},_ye={idField:"id",extractField:(t,e)=>t[e],stringifyField:(t,e)=>t.toString(),tokenize:t=>t.split(TUt),processTerm:t=>t.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(t,e)=>{typeof console?.[t]=="function"&&console[t](e)},autoVacuum:!0},gqe={combineWith:Aye,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:xUt},_Ut={combineWith:Tqe,prefix:(t,e,n)=>e===n.length-1},Iye={batchSize:1e3,batchWait:10},Pye={minDirtFactor:.1,minDirtCount:20},Sye={...Iye,...Pye},SUt=(t,e)=>{t.includes(e)||t.push(e)},yqe=(t,e)=>{for(let n of e)t.includes(n)||t.push(n)},wqe=({score:t},{score:e})=>e-t,vqe=()=>new Map,MG=t=>{let e=new Map;for(let n of Object.keys(t))e.set(parseInt(n,10),t[n]);return e},NG=async t=>{let e=new Map,n=0;for(let r of Object.keys(t))e.set(parseInt(r,10),t[r]),++n%1e3===0&&await Iqe(0);return e},Iqe=t=>new Promise(e=>setTimeout(e,t)),TUt=/[\n\r\p{Z}\p{P}]+/u});var LG,Wi,RG,Eqe=C(()=>{ye();It();Pqe();LG=require("obsidian");iB();Qge();Wi=class Wi{constructor(e,n){this.app=e;this.index=null;this.indexedChunks=new Set;this.memoryManager=new p0,this.chunkManager=n||PC(e)}createIndex(){return new wB({fields:["title","heading","path","tags","body"],storeFields:["id","notePath","title","heading","chunkIndex"],tokenize:this.tokenizeMixed.bind(this),searchOptions:{boost:{title:Wi.FIELD_WEIGHTS.title,heading:Wi.FIELD_WEIGHTS.heading,path:Wi.FIELD_WEIGHTS.path,tags:Wi.FIELD_WEIGHTS.tags,body:Wi.FIELD_WEIGHTS.body},prefix:!0,fuzzy:!1,combineWith:"OR"}})}tokenizeMixed(e){if(!e)return[];let n=new Set,r=e.toLowerCase(),o=r,i=null;try{i=r.match(/#[\p{L}\p{N}_/-]+/gu)}catch{i=r.match(/#[a-z0-9_/-]+/g)}if(i)for(let c of i){n.add(c);let u=c.slice(1);if(!u)continue;n.add(u);let d=u.split("/").filter(p=>p.length>0);if(d.length>0){let p="";for(let m of d)p=p?`${p}/${m}`:m,n.add(p),n.add(`#${p}`),n.add(m)}let f=c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");o=o.replace(new RegExp(f,"gu")," ")}(o.match(/[a-z0-9_]+/g)||[]).forEach(c=>n.add(c));let a=/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]+/g,l=e.match(a)||[];for(let c of l){c.length===1&&n.add(c);for(let u=0;u<c.length-1;u++)n.add(c.slice(u,u+2))}return Array.from(n)}async buildFromCandidates(e){k(`FullTextEngine: [CHUNKS] Starting with ${e.length} candidate notes`),this.indexedChunks.clear(),this.memoryManager.reset(),await new Promise(c=>window.setTimeout(c,0));let n=Date.now();this.index=this.createIndex();let r=Date.now()-n;k(`FullTextEngine: MiniSearch index created in ${r}ms`);let o={maxChars:JV,overlap:0,maxBytesTotal:this.memoryManager.getMaxBytes()*Wi.CHUNK_MEMORY_PERCENTAGE},i=await this.chunkManager.getChunks(e,o);if(i.length===0)return k("FullTextEngine: No chunks generated"),0;k(`FullTextEngine: Generated ${i.length} chunks from ${e.length} notes`);let s=0,a=Wi.BATCH_SIZE,l=new Map;for(let c=0;c<i.length;c++){let u=i[c],d=p0.getByteSize(u.content);if(!this.memoryManager.canAddContent(d)){k(`FullTextEngine: Memory limit reached at ${s} chunks`);break}let f=u.notePath.replace(/\.md$/,"").split("/").join(" "),p=l.get(u.notePath);if(!p){let h=this.app.vault.getAbstractFileByPath(u.notePath);if(h instanceof LG.TFile){let g=this.app.metadataCache.getFileCache(h),y=g?.frontmatter??{},w=g?(0,LG.getAllTags)(g)??[]:[],v=this.extractFrontmatterTags(y),x=this.normalizeTagList([...w,...v]),b=this.app.metadataCache.resolvedLinks[h.path]??{},_=this.app.metadataCache.getBacklinksForFile(h)?.data??{},T=Object.keys(b),S=Object.keys(_),P=[...T,...S],A=this.extractPropertyValues(y);p={tags:x,links:P,props:A},l.set(u.notePath,p)}else p={tags:[],links:[],props:[]}}let m=[u.content,...p.props].join(" ");this.index.add({id:u.id,title:u.title,heading:u.heading,path:f,body:m,tags:p.tags.join(" "),notePath:u.notePath,chunkIndex:u.chunkIndex}),this.memoryManager.addBytes(d),this.indexedChunks.add(u.id),s++,c>0&&c%a===0&&await new Promise(h=>window.setTimeout(h,0))}return k(`FullTextEngine: [CHUNKS] Indexed ${s}/${i.length} chunks (${this.memoryManager.getUsagePercent()}% memory)`),s}extractPropertyValues(e){let n=[];if(e&&typeof e=="object")for(let r of Object.values(e))this.extractPrimitiveValues(r,n,Wi.MAX_EXTRACTION_DEPTH);return n}extractFrontmatterTags(e){if(!e||typeof e!="object")return[];let n=[],r=["tags","tag"],o=i=>{let s=i.trim();s.length>0&&n.push(s)};for(let i of r){let s=e[i];if(s)if(Array.isArray(s))for(let a of s)typeof a=="string"&&o(a);else typeof s=="string"&&s.split(/[,\s]+/g).map(a=>a.trim()).filter(a=>a.length>0).forEach(o)}return n}normalizeTagList(e){let n=new Set;for(let r of e){if(typeof r!="string")continue;let o=r.trim();if(o.length===0)continue;let i=o.replace(/^#+/,"");if(i.length===0)continue;let s=i.toLowerCase();n.add(`#${s}`),n.add(s);let a=s.split("/").filter(l=>l.length>0);if(a.length>1){let l="";for(let c of a)l=l?`${l}/${c}`:c,n.add(`#${l}`),n.add(l),n.add(c)}else a.length===1&&(n.add(`#${a[0]}`),n.add(a[0]))}return Array.from(n)}extractPrimitiveValues(e,n,r){if(!(r<=0||e==null))if(typeof e=="string"){let o=e.trim();o&&n.push(o)}else typeof e=="number"||typeof e=="boolean"?n.push(String(e)):e instanceof Date?n.push(e.toISOString()):Array.isArray(e)&&e.slice(0,Wi.MAX_ARRAY_ITEMS).forEach(o=>{if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"){let i=typeof o=="string"?o.trim():String(o);i&&n.push(i)}})}search(e,n=30,r=[],o){if(!this.index)return[];let i=r.length>0?r.join(" "):o||e[0]||"";if(!i.trim())return[];let s={boost:{title:Wi.FIELD_WEIGHTS.title,heading:Wi.FIELD_WEIGHTS.heading,path:Wi.FIELD_WEIGHTS.path,tags:Wi.FIELD_WEIGHTS.tags,body:Wi.FIELD_WEIGHTS.body},prefix:!0,fuzzy:!1,combineWith:"OR"};try{let a=this.index.search(i,s);return k(`FullText: Search found ${a.length} results for "${i.substring(0,50)}..."`),a.slice(0,n).map(l=>({id:l.id,score:l.score,engine:"fulltext",explanation:{lexicalMatches:this.extractLexicalMatches(l),baseScore:l.score,finalScore:l.score}}))}catch(a){return ee(`FullText: Search failed for "${i}": ${a}`),[]}}extractLexicalMatches(e){let n=[];if(e.match)for(let[r,o]of Object.entries(e.match))for(let i of o)n.push({field:r,query:i,weight:this.getFieldWeight(r)});return n}getFieldWeight(e){return Wi.FIELD_WEIGHTS[e]||1}clear(){try{this.index=null,this.indexedChunks.clear(),this.memoryManager.reset(),k("FullTextEngine: Cleanup completed successfully")}catch(e){ee(`FullTextEngine: Cleanup error: ${e}`)}}getStats(){return{documentsIndexed:this.indexedChunks.size,memoryUsed:this.memoryManager.getBytesUsed(),memoryPercent:this.memoryManager.getUsagePercent()}}};Wi.BATCH_SIZE=10,Wi.CHUNK_MEMORY_PERCENTAGE=.35,Wi.MAX_ARRAY_ITEMS=10,Wi.MAX_EXTRACTION_DEPTH=2,Wi.FIELD_WEIGHTS={title:5,heading:2.5,headings:1.5,path:1.5,tags:4,props:1.5,links:1.5,body:1};RG=Wi});function uO(t){if(!t)return[];let e=null;try{e=t.match(/#[\p{L}\p{N}_/-]+/gu)}catch{e=t.match(/#[a-zA-Z0-9_/-]+/g)}if(!e)return[];let n=new Set;for(let r of e){let o=r.trim();o.length<=1||n.add(o.toLowerCase())}return Array.from(n)}var kye=C(()=>{});var $G,DG,Aqe=C(()=>{It();Nf();ye();kye();qe();$G=class $G{constructor(e={}){this.options=e;this.cache=new Map;this.config={maxVariants:e.maxVariants??2,timeout:e.timeout??QV,cacheSize:e.cacheSize??100,minTermLength:2}}async expand(e){if(!e?.trim())return{queries:[],salientTerms:[],originalQuery:"",expandedQueries:[]};let n=this.cache.get(e);if(n)return this.cache.delete(e),this.cache.set(e,n),k(`QueryExpander: Using cached expansion for "${e}"`),n;try{let r=await this.expandWithTimeout(e);return this.cacheResult(e,r),r}catch(r){return ee(`QueryExpander: Failed to expand query "${e}":`,r),this.fallbackExpansion(e)}}async expandWithTimeout(e){try{return await jAe(n=>this.expandWithLLM(e,n),this.config.timeout,"Query expansion")}catch(n){if(n instanceof dD)return k(`QueryExpander: Timeout reached for "${e}"`),this.fallbackExpansion(e);throw n}}async expandWithLLM(e,n){try{if(!this.options.getChatModel)return k("QueryExpander: No chat model getter provided"),this.fallbackExpansion(e);let r=await this.options.getChatModel();if(!r)return k("QueryExpander: No chat model available"),this.fallbackExpansion(e);let o=$G.PROMPT_TEMPLATE.replace("{count}",this.config.maxVariants.toString()).replace("{query}",e),i=await Nc(async()=>await r.invoke(o,n?{signal:n}:void 0));if(!i)return this.fallbackExpansion(e);let s=this.extractContent(i);if(!s)return this.fallbackExpansion(e);let a=this.parseXMLResponse(s,e);return k(`QueryExpander: Expanded "${e}" to ${a.queries.length} queries and ${a.salientTerms.length} terms`),a}catch(r){return z("QueryExpander: LLM expansion failed:",r),this.fallbackExpansion(e)}}extractContent(e){let n=e,r=n?.content??n?.text??"";return typeof e=="string"?e:(typeof r=="string"?r:typeof r=="number"?String(r):"").trim()||null}extractSalientTermsFromOriginal(e){let n=this.extractTermsFromQueries([e]),r=uO(e);return this.combineBaseAndTagTerms(n,r,e)}parseXMLResponse(e,n){let r=[n],o=new Set,i=/<query>(.*?)<\/query>/g,s;for(;(s=i.exec(e))!==null;){let f=s[1]?.trim();f&&f!==n&&r.length<=this.config.maxVariants&&r.push(f)}let a=e.match(/<salient>([\s\S]*?)<\/salient>/);if(a){let f=/<term>(.*?)<\/term>/g,p;for(;(p=f.exec(a[1]))!==null;){let m=p[1]?.trim().toLowerCase();m&&this.isValidTerm(m)&&o.add(m)}}if(!(r.length>1||o.size>0||/<term>/.test(e)))return this.fallbackExpansion(n);let c=uO(n),u=o.size>0?Array.from(new Set([...o,...c])):this.extractSalientTermsFromOriginal(n),d=r.slice(1);return{queries:r.slice(0,this.config.maxVariants+1),salientTerms:u,originalQuery:n,expandedQueries:d.slice(0,this.config.maxVariants)}}fallbackExpansion(e){let n=this.extractTermsFromQueries([e]),r=uO(e),o=this.combineBaseAndTagTerms(n,r,e);return{queries:[e],salientTerms:o,originalQuery:e,expandedQueries:[]}}extractTermsFromQueries(e){let n=new Set;for(let r of e){let o=r.toLowerCase().replace(/[^\w\s-]/g," ").split(/\s+/);for(let i of o)this.isValidTerm(i)&&(n.add(i),i.includes("-")&&i.split("-").forEach(s=>{this.isValidTerm(s)&&n.add(s)}))}return Array.from(n)}isValidTerm(e){if(e.length<this.config.minTermLength)return!1;if(e.startsWith("#"))try{return/^#[\p{L}\p{N}_/-]+$/u.test(e)}catch{return/^#[A-Za-z0-9_/-]+$/.test(e)}try{return/^[\p{L}\p{N}_-]+$/u.test(e)}catch{return/^[A-Za-z0-9_-]+$/.test(e)}}combineBaseAndTagTerms(e,n,r){let o=new Set([...e,...n]);if(n.length===0)return Array.from(o);let i=this.collectStandaloneTerms(r);for(let s of n){let a=s.slice(1);a.length>0&&!i.has(a)&&o.delete(a)}return Array.from(o)}collectStandaloneTerms(e){let n=new Set;if(!e)return n;let r=e.toLowerCase(),o=this.findTagRanges(r),i=[/[\p{L}\p{N}_-]+/gu,/[a-z0-9_-]+/g];for(let s of i)try{for(let a of r.matchAll(s)){if(a.index===void 0)continue;let l=a.index,c=l+a[0].length;if(o.some(({start:f,end:p})=>l>=f&&c<=p))continue;let d=a[0];this.isValidTerm(d)&&!d.startsWith("#")&&(n.add(d),d.includes("-")&&d.split("-").forEach(f=>{this.isValidTerm(f)&&!f.startsWith("#")&&n.add(f)}))}break}catch{continue}return n}findTagRanges(e){let n=[],r=[/#[\p{L}\p{N}_/-]+/gu,/#[a-z0-9_/-]+/g];for(let o of r)try{for(let i of e.matchAll(o))i.index!==void 0&&n.push({start:i.index,end:i.index+i[0].length});break}catch{continue}return n}cacheResult(e,n){if(this.cache.size>=this.config.cacheSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(e,n)}clearCache(){this.cache.clear(),k("QueryExpander: Cache cleared")}getCacheSize(){return this.cache.size}};$G.PROMPT_TEMPLATE=`Analyze this search query and provide:
1. SALIENT TERMS from the original query (for ranking)
2. Alternative queries and related terms (for finding more results)

Query: "{query}"

Instructions:

SALIENT TERMS (for ranking - ONLY from original query):
- Extract meaningful words FROM THE ORIGINAL QUERY ONLY
- Include: nouns, proper nouns, technical terms, domain concepts
- Exclude: action verbs (find, search, get), pronouns (my, your), articles (the, a), prepositions (in, on, for), conjunctions (and, or)
- These terms determine search ranking - must be from original query

ALTERNATIVE QUERIES (for recall - specific alternative phrasings):
- Alternative phrasings of the query (specific enough to be useful for search)

Example: "find my piano notes"
- Salient (from original): piano, notes
- Queries: "piano lesson notes", "piano practice sheets"

Example: "\u67E5\u627E\u6211\u7684\u5B66\u4E60\u7B14\u8BB0"
- Salient (from original): \u5B66\u4E60, \u7B14\u8BB0
- Queries: "\u4E2A\u4EBA\u7B14\u8BB0\u6587\u6863"

Format:
<salient>
<term>word_from_original_query</term>
</salient>
<queries>
<query>alternative query</query>
</queries>`;DG=$G});var dO,FG,kqe=C(()=>{ye();fc();dO=class dO{constructor(e){this.app=e}async batchCachedReadGrep(e,n){let{inclusions:r,exclusions:o}=Bo(),s=this.app.vault.getMarkdownFiles().filter(h=>Qr(h,r,o)),a=dO.CONFIG.BATCH_SIZE,l=e.map(h=>h.toLowerCase()).filter(h=>this.isGrepWorthy(h)),c=[],u=dO.CONFIG.YIELD_INTERVAL;for(let h=0;h<s.length;h++){let g=s[h],y=g.path.toLowerCase(),w=0;for(let v of l)y.includes(v)&&w++;w>0&&c.push({path:g.path,matchCount:w}),h>0&&h%u===0&&await new Promise(v=>window.setTimeout(v,0))}c.sort((h,g)=>g.matchCount-h.matchCount);let d=new Set(c.map(h=>h.path)),f=Math.max(0,n-d.size),p=new Set;if(f>0)for(let h=0;h<s.length&&p.size<f;h+=a){let g=s.slice(h,h+a);await Promise.all(g.map(async y=>{if(!(p.size>=f)&&!d.has(y.path))try{let v=(await this.app.vault.cachedRead(y)).toLowerCase();for(let x of l)if(v.includes(x)){p.add(y.path);break}}catch(w){k(`GrepScanner: Skipping file ${y.path}: ${w}`)}})),h%dO.CONFIG.YIELD_INTERVAL===0&&await new Promise(y=>window.setTimeout(y,0))}let m=[...d,...p].slice(0,n);if(m.length>0){let h=Math.min(d.size,n),g=m.length-h;k(`  Grep: ${m.length} files match (${h} path, ${g} content) [${e.slice(0,3).join(", ")}${e.length>3?"...":""}]`)}return m}async grep(e,n=200){return this.batchCachedReadGrep([e],n)}isGrepWorthy(e){return!(!e||e.length<=1)}async fileContainsAny(e,n){try{let r=e.path.toLowerCase(),o=0;for(let a of n)r.includes(a.toLowerCase())&&o++;if(o>0)return!0;let s=(await this.app.vault.cachedRead(e)).toLowerCase();return n.some(a=>s.includes(a.toLowerCase()))}catch{return!1}}};dO.CONFIG={BATCH_SIZE:30,YIELD_INTERVAL:100};FG=dO});function oh(t){let e=t.lastIndexOf("#");return e===-1?t:t.substring(0,e)}var UG=C(()=>{});var IUt,BG,Mqe=C(()=>{ye();UG();IUt={enabled:!0,minDocsForBoost:2,maxBoostFactor:1.15,minRelevanceRatio:.4},BG=class{constructor(e){this.config=IUt;this.app=e||null}setConfig(e){this.config={...this.config,...e}}applyBoosts(e){if(!this.config.enabled||e.length===0)return e;let n=this.calculateFolderStats(e);return this.logBoostedFolders(n),e.map(r=>{let o=oh(r.id),i=this.extractFolder(o),s=n.get(i);if(s){let a=r.score*s.boostFactor;return{...r,score:a,explanation:r.explanation?{...r.explanation,folderBoost:{folder:s.folderPath,documentCount:s.documentCount,totalDocsInFolder:s.totalDocsInFolder,relevanceRatio:s.relevanceRatio,boostFactor:s.boostFactor},finalScore:a}:void 0}}return r})}calculateFolderStats(e){let n=new Map;for(let s of e){let a=oh(s.id),l=this.extractFolder(a);n.has(l)||n.set(l,new Set),n.get(l).add(a)}let r=new Map;for(let[s,a]of n.entries())r.set(s,a.size);let o=this.getTotalDocsPerFolder(),i=new Map;for(let[s,a]of r.entries()){let l=o.get(s)||a,c=a/l;if(a>=this.config.minDocsForBoost&&c>=this.config.minRelevanceRatio){let d=1+(1+Math.log2(a+1)-1)*Math.sqrt(c),f=Math.min(d,this.config.maxBoostFactor);i.set(s,{folderPath:s,documentCount:a,totalDocsInFolder:l,relevanceRatio:c,boostFactor:f})}}return i}getTotalDocsPerFolder(){let e=new Map;if(!this.app)return e;let n=this.app.vault.getMarkdownFiles();for(let r of n){let o=this.extractFolder(r.path);e.set(o,(e.get(o)||0)+1)}return e}extractFolder(e){return e.substring(0,e.lastIndexOf("/"))||""}logBoostedFolders(e){let n=Array.from(e.values()).sort((r,o)=>o.relevanceRatio-r.relevanceRatio);n.length>0&&(k(`Folder boost: Boosting ${n.length} folders with significant relevance`),n.slice(0,5).forEach(r=>{let o=(r.relevanceRatio*100).toFixed(1);k(`  ${r.folderPath||"(root)"}: ${r.documentCount}/${r.totalDocsInFolder} docs (${o}% relevant, ${r.boostFactor.toFixed(2)}x boost)`)}))}getFolderBoosts(e){return this.config.enabled?this.calculateFolderStats(e):new Map}}});var Nqe,PUt,zG,Oqe=C(()=>{ye();Nqe=require("obsidian");UG();PUt={enabled:!0,maxCandidates:10,backlinkWeight:1,coCitationWeight:.5,sharedTagWeight:.3,boostStrength:.1,maxBoostMultiplier:1.2},zG=class{constructor(e,n={}){this.metadataCache=e.metadataCache,this.config={...PUt,...n}}applyBoost(e){if(!this.config.enabled||e.length===0)return e;let n=this.filterCandidates(e);if(n.length<2)return e;let r=new Set(n.map(a=>oh(a.id))),o=new Map;for(let a of r){let l=this.calculateConnections(a,r);o.set(a,l)}let i=e.map(a=>{let l=oh(a.id),c=o.get(l);return!c||c.boostMultiplier===1?a:{...a,score:a.score*c.boostMultiplier,explanation:a.explanation?{...a.explanation,graphConnections:{backlinks:c.backlinks.length,coCitations:c.coCitations.length,sharedTags:c.sharedTags.length,score:c.connectionScore,boostMultiplier:c.boostMultiplier}}:void 0}}),s=i.filter(a=>{let l=oh(a.id),c=o.get(l);return c&&c.boostMultiplier>1});return s.length>0&&k(`GraphBoostCalculator: Boosted ${s.length} notes based on connections`),i}calculateConnections(e,n){let r=this.findBacklinks(e,n),o=this.findCoCitations(e,n),i=this.findSharedTags(e,n),s=r.length*this.config.backlinkWeight+o.length*this.config.coCitationWeight+i.length*this.config.sharedTagWeight,a=1;return s>0&&(a=1+this.config.boostStrength*Math.log(1+s),a=Math.min(a,this.config.maxBoostMultiplier)),{backlinks:r,coCitations:o,sharedTags:i,connectionScore:s,boostMultiplier:a}}resolveFile(e){let n=this.metadataCache.getFirstLinkpathDest(e,"");return n instanceof Nqe.TFile?n:null}findBacklinks(e,n){let r=[],o=this.resolveFile(e);if(!o)return r;let i=this.metadataCache.getBacklinksForFile(o);if(!i)return r;for(let[s]of i.data)n.has(s)&&s!==e&&r.push(s);return r}findCoCitations(e,n){let r=[],o=new Set,i=this.resolveFile(e);if(!i)return r;let s=this.metadataCache.getBacklinksForFile(i);if(!s)return r;for(let[a]of s.data)o.add(a);if(o.size===0)return r;for(let a of n){if(a===e)continue;let l=this.resolveFile(a);if(!l)continue;let c=this.metadataCache.getBacklinksForFile(l);if(c){for(let[u]of c.data)if(o.has(u)){r.push(a);break}}}return r}findSharedTags(e,n){let r=[],o=this.resolveFile(e);if(!o)return r;let i=this.metadataCache.getFileCache(o);if(!i||!i.tags||i.tags.length===0)return r;let s=new Set(i.tags.map(a=>a.tag));for(let a of n){if(a===e)continue;let l=this.resolveFile(a);if(!l)continue;let c=this.metadataCache.getFileCache(l);if(!c||!c.tags)continue;c.tags.some(d=>s.has(d.tag))&&r.push(a)}return r}filterCandidates(e){let n=new Map;for(let i of e){let s=oh(i.id);n.has(s)||n.set(s,i)}let r=Array.from(n.values()),o=r.length;return r=r.slice(0,this.config.maxCandidates),o>this.config.maxCandidates&&k(`GraphBoost: Limited to top ${this.config.maxCandidates} note candidates (from ${o} unique notes)`),r}setConfig(e){this.config={...this.config,...e}}}});function Rqe(t,e={}){let n={...EUt,...e};if(t.length===0)return{results:[],cutoffScore:null,uniqueNotes:0,totalBefore:0};let r=[...t].sort((c,u)=>u.score-c.score),o=r[0].score,i=Math.max(o*n.relativeThreshold,n.absoluteMinScore),s;n.ensureDiversity?s=kUt(r,i,n):s=AUt(r,i,n);let a=new Set(s.map(c=>oh(c.id))).size,l=s.length<r.length?i:null;return k(`AdaptiveCutoff: ${s.length}/${r.length} results kept (${a} unique notes, threshold=${i.toFixed(3)})`),{results:s,cutoffScore:l,uniqueNotes:a,totalBefore:r.length}}function AUt(t,e,n){let r=[];for(let o of t){if(r.length>=n.ceiling||r.length>=n.floor&&o.score<e)break;r.push(o)}return r}function kUt(t,e,n){let r=[],o=new Set,i=[];for(let s of t){let a=oh(s.id);if(!o.has(a)&&(r.length<n.floor||s.score>=e)){if(o.add(a),r.push(s),r.length>=n.ceiling)break;continue}i.push(s)}if(r.length<n.ceiling)for(let s of i){if(r.length>=n.ceiling||s.score<e&&r.length>=n.floor)break;r.push(s)}return r.sort((s,a)=>a.score-s.score),r}var EUt,Lqe=C(()=>{ye();UG();EUt={floor:3,ceiling:30,relativeThreshold:.3,absoluteMinScore:.01,ensureDiversity:!0}});var jG,Dqe=C(()=>{jG=class{constructor(e={}){this.config={method:"zscore-tanh",tanhScale:2.5,clipMin:.02,clipMax:.98};this.config={...this.config,...e}}updateExplanation(e,n,r){if(e)return{...e,baseScore:n,finalScore:r}}normalize(e){if(e.length===0)return e;switch(this.config.method){case"zscore-tanh":return this.normalizeZScoreTanh(e);case"minmax":return this.normalizeMinMax(e);case"percentile":return this.normalizePercentile(e);default:return e}}normalizeZScoreTanh(e){let n=e.map(c=>c.score),r=n.reduce((c,u)=>c+u,0)/n.length,o=n.reduce((c,u)=>c+Math.pow(u-r,2),0)/n.length,i=Math.sqrt(o);if(i===0)return e.map(c=>({...c,score:.5,explanation:this.updateExplanation(c.explanation,c.score,.5)}));let s=this.config.tanhScale||2.5,a=this.config.clipMin||.02,l=this.config.clipMax||.98;return e.map(c=>{let u=(c.score-r)/i,d=.5+.5*Math.tanh(u/s),f=Math.max(a,Math.min(l,d));return{...c,score:f,explanation:this.updateExplanation(c.explanation,c.score,f)}})}normalizeMinMax(e){let n=e.map(l=>l.score),r=Math.min(...n),o=Math.max(...n);if(o===r)return e.map(l=>({...l,score:.5,explanation:this.updateExplanation(l.explanation,l.score,.5)}));let i=this.config.clipMin||.02,s=this.config.clipMax||.98;return e.map(l=>{let c=(l.score-r)/(o-r),u=i+c*(s-i);return{...l,score:u,explanation:this.updateExplanation(l.explanation,l.score,u)}})}normalizePercentile(e){let n=e.length,r=this.config.clipMin||.02,o=this.config.clipMax||.98,i=[...e].sort((a,l)=>a.score-l.score),s=new Map;return i.forEach((a,l)=>{let c=l/(n-1),u=r+c*(o-r);s.set(a.id,u)}),e.map(a=>{let l=s.get(a.id)||.5;return{...a,score:l,explanation:this.updateExplanation(a.explanation,a.score,l)}})}getStatistics(e){if(e.length===0)return{mean:0,std:0,min:0,max:0,median:0};let n=e.map(u=>u.score),r=[...n].sort((u,d)=>u-d),o=n.reduce((u,d)=>u+d,0)/n.length,i=n.reduce((u,d)=>u+Math.pow(d-o,2),0)/n.length,s=Math.sqrt(i),a=r[0],l=r[r.length-1],c=r[Math.floor(r.length/2)];return{mean:o,std:s,min:a,max:l,median:c}}}});function MUt(t,e){return t.length<=e?t:Rqe(t,{floor:0,ceiling:e,relativeThreshold:0,absoluteMinScore:0,ensureDiversity:!0}).results}var Mye,ni,VG,N0=C(()=>{It();ye();iB();Eqe();Aqe();kqe();Mqe();Oqe();Lqe();Dqe();Mye=3,ni=100,VG=class{constructor(e,n){this.app=e;this.getChatModel=n;this.grepScanner=new FG(e),this.chunkManager=PC(e),this.fullTextEngine=new RG(e,this.chunkManager),this.queryExpander=new DG({getChatModel:this.getChatModel,maxVariants:3,timeout:QV}),this.folderBoostCalculator=new BG(e),this.graphBoostCalculator=new zG(e,{enabled:!0,maxCandidates:20,boostStrength:.1,maxBoostMultiplier:1.15}),this.scoreNormalizer=new jG({method:"minmax",clipMin:.02,clipMax:.98})}async retrieve(e,n={}){let r={queries:[],salientTerms:[],originalQuery:e||"",expandedQueries:[]};if(!e||typeof e!="string")return ee("SearchCore: Invalid query provided"),{results:[],queryExpansion:r};let o=e.trim();if(o.length===0)return ee("SearchCore: Empty query provided"),{results:[],queryExpansion:r};o.length>1e3?(ee("SearchCore: Query too long, truncating"),e=o.substring(0,1e3)):e=o;let i=!!n.returnAll,s=i?ni:Math.min(Math.max(1,n.maxResults||30),100),a=i?ni:Math.min(Math.max(10,n.candidateLimit||200),1e3),l=!!(n.enableLexicalBoosts??!0);try{k(`SearchCore: Searching for "${e}"`);let c;n.preExpandedQuery?(k("SearchCore: Using pre-expanded query data (skipping QueryExpander)"),c={queries:n.preExpandedQuery.queries||[e],salientTerms:n.preExpandedQuery.salientTerms||[],originalQuery:n.preExpandedQuery.originalQuery||e,expandedQueries:n.preExpandedQuery.expandedQueries||[]}):c=await this.queryExpander.expand(e);let u=c.queries,d=n.salientTerms?[...new Set([...c.salientTerms,...n.salientTerms])]:c.salientTerms,f=[],p=new Set,m=x=>{if(!x)return;let b=x.toLowerCase();b.length===0||p.has(b)||(p.add(b),f.push(b))};u.forEach(m),d.forEach(m),(u.length>1||d.length>0)&&k(`Query expansion: variants=${JSON.stringify(u)}, salient=${JSON.stringify(d)}`);let h=i?ni:200,g=await this.grepScanner.batchCachedReadGrep(f,h),y=g.slice(0,a);k(`SearchCore: ${y.length} candidates (from ${g.length} grep hits)`);let v=await this.executeLexicalSearch(y,f,d,s,c.originalQuery,i);if(l&&(v=this.folderBoostCalculator.applyBoosts(v),v=this.graphBoostCalculator.applyBoost(v)),v=this.scoreNormalizer.normalize(v),this.fullTextEngine.clear(),v.length>s&&(v=MUt(v,s)),v.length>0){let x=this.app.vault.getAbstractFileByPath(v[0].id);k(`SearchCore: ${v.length} results found (top: ${x?.name||v[0].id})`)}else k("SearchCore: No results found");return{results:v,queryExpansion:c}}catch(c){z("SearchCore: Retrieval failed",c);try{return{results:await this.fallbackSearch(e,s),queryExpansion:r}}catch(u){return z("SearchCore: Fallback search also failed",u),{results:[],queryExpansion:r}}}}async fallbackSearch(e,n){try{return(await this.grepScanner.grep(e,n)).map((o,i)=>({id:o,score:1/(i+1),engine:"grep"}))}catch(r){return z("SearchCore: Fallback search failed",r),[]}}getStats(){return{fullTextStats:this.fullTextEngine.getStats()}}getChunkManager(){return this.chunkManager}clear(){this.fullTextEngine.clear(),this.queryExpander.clearCache(),k("SearchCore: Cleared all caches")}async executeLexicalSearch(e,n,r,o,i,s=!1){try{let a=Date.now(),l=await this.fullTextEngine.buildFromCandidates(e),c=Date.now()-a,u=Date.now(),d=s?ni:Number.isFinite(o)?Math.min(o,1e3):e.length||30,f=s?ni*Mye:Math.max(d*Mye,Mye),p=this.fullTextEngine.search(n,f,r,i),m=Date.now()-u;return k(`Full-text: ${l} docs indexed (${c}ms), ${p.length} results (${m}ms)`),p}catch(a){return z("Full-text search failed",a),[]}}}});var $qe={};zn($qe,{HybridRetriever:()=>vB});var vB,Nye=C(()=>{Zg();o0();ye();ei();Se();qe();iv();lO();iG();vB=class extends ay{constructor(n){super();this.options=n;this.lc_namespace=["hybrid_retriever"]}async getRelevantDocuments(n){return Nc(async()=>{let r=Df(n,app.vault),o=r.map(p=>p.basename),i=[...new Set([...this.options.salientTerms,...o])],s=await this.getExplicitChunks(r),a=await this.getOramaChunks(n,i,this.options.textWeight),l=this.filterAndFormatChunks(a,s),c=l;if(l.length===0)return q().debug&&k("No chunks found for query:",n),c;let u=l.reduce((p,m)=>{let h=m.metadata.score;return typeof h=="number"&&!isNaN(h)?Math.max(p,h):p},0),d=l.every(p=>typeof p.metadata.score!="number"||isNaN(p.metadata.score)),f=this.options.useRerankerThreshold&&(u<this.options.useRerankerThreshold||d);return f&&(c=(await di.getInstance().rerank(n,l.map(m=>m.pageContent.slice(0,3e3)))).response.data.map(m=>({...l[m.index],metadata:{...l[m.index].metadata,rerank_score:m.relevance_score}}))),q().debug&&(k("*** HYBRID RETRIEVER DEBUG INFO: ***"),k(`
Explicit Chunks: `,s),k("Orama Chunks: ",a),k("Combined Chunks: ",l),k("Max Orama Score: ",u),f?k("Reranked Chunks: ",c):k("No reranking applied.")),c})}async getExplicitChunks(n){let r=[];for(let o of n){let i=await Cp.getInstance().getDocumentsByPath(o.path);if(i.length===0)continue;let s=i.map(a=>new fi({pageContent:a.content,metadata:{...a.metadata,score:1,path:a.path,mtime:a.mtime,ctime:a.ctime,title:a.title,id:a.id,embeddingModel:a.embeddingModel,tags:a.tags,extension:a.extension,created_at:a.created_at,nchars:a.nchars,chunkId:a.metadata?.chunkId}}));r.push(...s)}return r}async getOramaChunks(n,r,o){let i;try{i=await this.convertQueryToVector(n)}catch(c){throw console.error("Error in convertQueryToVector, please ensure your embedding model is working and has an adequate context length:",c,`
Query:`,n),c}let s=await Cp.getInstance().getDb(),a={similarity:this.options.minSimilarityScore,limit:this.options.maxK,includeVectors:!0};if(r.length>0){let c;o||(o=.5),c=1-o;let u=!0;for(let d of r)if(!d.startsWith("#")){u=!1;break}u&&(q().debug&&k("Tag only query detected, setting textWeight to 1 and vectorWeight to 0."),o=1,c=0),a.mode="hybrid",a.term=r.join(" "),a.vector={value:i,property:"embedding"},a.hybridWeights={text:o,vector:c}}else a.mode="vector",a.vector={value:i,property:"embedding"};if(this.options.timeRange){let{startTime:c,endTime:u}=this.options.timeRange,d=this.generateDailyNoteDateRange(c,u);k("Daily note date range:",d[0],d[d.length-1]);let f=Df(d.join(", "),app.vault),m=(await this.getExplicitChunks(f)).map(v=>({...v,metadata:{...v.metadata,includeInContext:!0}}));k("Modified time range:",c,u),a.where={mtime:{between:[c,u]}};let g=(await Zu(s,a)).hits.map(v=>new fi({pageContent:v.document.content,metadata:{...v.document.metadata,score:v.score,path:v.document.path,mtime:v.document.mtime,ctime:v.document.ctime,title:v.document.title,id:v.document.id,embeddingModel:v.document.embeddingModel,tags:v.document.tags,extension:v.document.extension,created_at:v.document.created_at,nchars:v.document.nchars,chunkId:v.document.metadata?.chunkId}})),y=[...m,...g];return Array.from(new Set(y.map(v=>v.metadata.id))).map(v=>y.find(x=>x.metadata.id===v)).filter(v=>v!==void 0)}k(`Orama search params:
`,a);let l=await Zu(s,a);return!l||!l.hits?(console.warn("Search results or hits are undefined"),[]):l.hits.map(c=>!c||!c.document?(console.warn("Invalid hit or document in search results"),null):((typeof c.score!="number"||isNaN(c.score))&&console.warn("NaN/invalid score detected:",{score:c.score,path:c.document.path,title:c.document.title}),new fi({pageContent:c.document.content||"",metadata:{...c.document.metadata||{},score:c.score,path:c.document.path||"",mtime:c.document.mtime,ctime:c.document.ctime,title:c.document.title||"",id:c.document.id,embeddingModel:c.document.embeddingModel,tags:c.document.tags||[],extension:c.document.extension,created_at:c.document.created_at,nchars:c.document.nchars,chunkId:c.document.metadata?.chunkId}}))).filter(c=>c!==null)}async convertQueryToVector(n){let o=await(await is.getInstance().getEmbeddingsAPI()).embedQuery(n);if(o.length===0)throw new Error("Query embedding returned an empty vector");return o}generateDailyNoteDateRange(n,r){let o=[],i=new Date(n),s=new Date(r),a=new Date(i);for(;a<=s;)o.push(`[[${a.toLocaleDateString("en-CA")}]]`),a.setDate(a.getDate()+1);return o}filterAndFormatChunks(n,r){let o=this.options.minSimilarityScore,i=n.filter(l=>{let c=l.metadata.score;return typeof c!="number"||isNaN(c)?!0:c>=o}),s=new Set(r.map(l=>l.pageContent)),a=[...r];for(let l of i){let c=l.pageContent;s.has(c)||(s.add(c),a.push(l))}return a.map(l=>({...l,metadata:{...l.metadata,includeInContext:!0}}))}}});function Oye(t){let e=[];for(let n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}var Fqe,Rye=C(()=>{Bd();Uw();Fqe=class extends aM{constructor(e){super(e);I(this,"lc_namespace",["langchain","anthropic","output_parsers"]);I(this,"returnId",!1);I(this,"keyName");I(this,"returnSingle",!1);I(this,"zodSchema");I(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema,this.serializableSchema=e.serializableSchema}static lc_name(){return"AnthropicToolsOutputParser"}async _validateResult(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch(o){throw new lc(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(o.message)}`,e)}else n=e;if(this.serializableSchema!==void 0){let o=await this.serializableSchema["~standard"].validate(n);if(o.issues)throw new lc(`Failed to parse. Text: "${JSON.stringify(n,null,2)}". Error: ${JSON.stringify(o.issues)}`,JSON.stringify(n,null,2));return o.value}if(this.zodSchema===void 0)return n;let r=await kT(this.zodSchema,n);if(r.success)return r.data;throw new lc(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(r.error.issues)}`,JSON.stringify(n,null,2))}async parseResult(e){let n=e.flatMap(o=>{let{message:i}=o;return Array.isArray(i.content)?Oye(i.content)[0]:[]});if(n[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");let[r]=n;return await this._validateResult(r.args)}}});function Uqe(t){if(t)return t==="any"||t==="required"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}var Bqe,Lye,zqe=C(()=>{tv();Bqe=Yme({cache_control:rhe().optional().nullable(),defer_loading:yq().optional(),input_examples:MN(QI()).optional(),allowed_callers:MN(QI()).optional()}),Lye={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"}});function jqe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function Vqe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function HG(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="compaction"}function Wqe(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Hqe(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}var Kqe,Dye=C(()=>{Kr();Kqe={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){let e=Bc({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){let e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}}});var qqe,Gqe=C(()=>{qqe=t=>t()});function NUt(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function OUt(t){function*e(){for(let n of t)NUt(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function xB(t){return typeof t=="string"?t:RUt(t)}function RUt(t){let e=[];for(let n=0,{length:r}=t;n<r;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function $ye(t){return(t??"").split(";")[0].toLowerCase()}function bB(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function fO(t,e){let n=bB(e,"cache_control");n!==void 0&&(t.cache_control=n);let r=bB(e,"citations");r!==void 0&&(t.citations=r);let o=bB(e,"context");o!==void 0&&(t.context=o);let i=bB(e,"title");return i!==void 0&&(t.title=i),t}function Fye(t,e){let n=bB(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function Yqe(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function Zqe(t){let e=[],n=t.response_metadata,r="model_provider"in n&&n?.model_provider==="anthropic";for(let o of t.contentBlocks)if(o.type==="text")o.annotations?e.push({type:"text",text:o.text,citations:OUt(o.annotations)}):e.push({type:"text",text:o.text});else if(o.type==="tool_call")e.push({type:"tool_use",id:o.id??"",name:o.name,input:o.args});else if(o.type==="tool_call_chunk"){let i=qqe(()=>{if(typeof o.args!="string")return o.args;try{return JSON.parse(o.args)}catch{return{}}});e.push({type:"tool_use",id:o.id??"",name:o.name??"",input:i})}else if(o.type==="reasoning"&&r)e.push({type:"thinking",thinking:o.reasoning,signature:String(o.signature)});else if(o.type==="server_tool_call"&&r)o.name==="web_search"?e.push({type:"server_tool_use",name:o.name,id:o.id??"",input:o.args}):o.name==="code_execution"&&e.push({type:"server_tool_use",name:o.name,id:o.id??"",input:o.args});else if(o.type==="server_tool_call_result"&&r)if(o.name==="web_search"&&Array.isArray(o.output.urls)){let i=o.output.urls.map(s=>({type:"web_search_result",title:"",encrypted_content:"",url:s}));e.push({type:"web_search_tool_result",tool_use_id:o.toolCallId??"",content:i})}else o.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:o.toolCallId??"",content:o.output}):o.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:o.toolCallId??"",content:o.output});else{if(o.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(o.type==="file"){let i=o.metadata;if(o.fileId){e.push(fO({type:"document",source:{type:"file",file_id:o.fileId}},i));continue}if(o.url){let s=$ye(o.mimeType);if(s==="application/pdf"||s===""){e.push(fO({type:"document",source:{type:"url",url:o.url}},i));continue}}if(o.data){let s=$ye(o.mimeType);if(s===""||s==="application/pdf")e.push(fO({type:"document",source:{type:"base64",data:xB(o.data),media_type:"application/pdf"}},i));else if(s==="text/plain")e.push(fO({type:"document",source:{type:"text",data:xB(o.data),media_type:"text/plain"}},i));else if(Yqe(s))e.push(fO({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:xB(o.data),media_type:s}}]}},i));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${s}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(o.type==="image"){let i=o.metadata;if(o.fileId){e.push(Fye({type:"image",source:{type:"file",file_id:o.fileId}},i));continue}if(o.url){e.push(Fye({type:"image",source:{type:"url",url:o.url}},i));continue}if(o.data){let s=$ye(o.mimeType)||"image/png";Yqe(s)&&e.push(Fye({type:"image",source:{type:"base64",data:xB(o.data),media_type:s}},i));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else o.type==="video"||(o.type==="text-plain"?o.data&&e.push(fO({type:"document",source:{type:"text",data:xB(o.data),media_type:"text/plain"}},o.metadata)):o.type==="non_standard"&&r&&e.push(o.value))}return e}var Jqe=C(()=>{Gqe()});function Uye(t){let e=Bc({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`

`))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`

`))}function LUt(t){let e=[];for(let n of t)if(n._getType()==="tool")if(typeof n.content=="string"){let r=e[e.length-1];r?._getType()==="human"&&Array.isArray(r.content)&&"type"in r.content[0]&&r.content[0].type==="tool_result"?r.content.push({type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}):e.push(new Zo({content:[{type:"tool_result",content:n.content,tool_use_id:n.tool_call_id}]}))}else e.push(new Zo({content:[{type:"tool_result",...n.content!=null?{content:zye(n)}:{},tool_use_id:n.tool_call_id}]}));else e.push(n);return e}function Bye(t){if(t.id===void 0)throw new Error('Anthropic requires all tool calls to have an "id".');return{type:"tool_use",id:t.id,name:t.name,input:t.args}}function*DUt(t,e){let n=["bash_code_execution_tool_result","input_json_delta","server_tool_use","text_editor_code_execution_tool_result","tool_result","tool_use","web_search_result","web_search_tool_result"],r=["text","text_delta"];for(let o of t){tc(o)&&(yield kw(o,Kqe));let i="cache_control"in o?o.cache_control:void 0;if(o.type==="image_url"){let s;typeof o.image_url=="string"?s=Uye(o.image_url):typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"&&(s=Uye(o.image_url.url)),s&&(yield{type:"image",source:s,...i?{cache_control:i}:{}})}else if(Hqe(o))yield o;else if(o.type==="image"){let s;"url"in o&&typeof o.url=="string"?s=Uye(o.url):"data"in o&&(typeof o.data=="string"||o.data instanceof Uint8Array)?s={type:"base64",media_type:"mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:"image/jpeg",data:typeof o.data=="string"?o.data:Buffer.from(o.data).toString("base64")}:"fileId"in o&&typeof o.fileId=="string"&&(s={type:"file",file_id:o.fileId}),s&&(yield{type:"image",source:s,...i?{cache_control:i}:{}})}else if(o.type==="file"){let s;"url"in o&&typeof o.url=="string"?s={type:"url",url:o.url}:"data"in o&&(typeof o.data=="string"||o.data instanceof Uint8Array)?s={type:"base64",media_type:"mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:"application/pdf",data:typeof o.data=="string"?o.data:Buffer.from(o.data).toString("base64")}:"fileId"in o&&typeof o.fileId=="string"&&(s={type:"file",file_id:o.fileId}),s&&(yield{type:"document",source:s,...i?{cache_control:i}:{}})}else if(o.type==="document")yield{...o,...i?{cache_control:i}:{}};else if(jqe(o))yield{type:"thinking",thinking:o.thinking,signature:o.signature,...i?{cache_control:i}:{}};else if(Vqe(o))yield{type:"redacted_thinking",data:o.data,...i?{cache_control:i}:{}};else if(HG(o))yield{type:"compaction",content:o.content,...i?{cache_control:i}:{}};else if(Wqe(o))yield{type:"search_result",title:o.title,source:o.source,..."cache_control"in o&&o.cache_control?{cache_control:o.cache_control}:{},..."citations"in o&&o.citations?{citations:o.citations}:{},content:o.content};else if(r.find(s=>s===o.type)&&"text"in o)yield{type:"text",text:o.text,...i?{cache_control:i}:{},..."citations"in o&&o.citations?{citations:o.citations}:{}};else if(n.find(s=>s===o.type)){let s={...o};if(s.type==="input_json_delta")continue;if(s.type==="tool_use"&&typeof s.input=="string"){let a=e?.find(l=>l.id===s.id);a?s.input=a.args:s.input=t.filter(l=>l.index===s.index&&l.type==="input_json_delta"&&typeof l.input=="string").reduce((l,c)=>l+c.input,s.input)}if("index"in s&&delete s.index,"input"in s&&typeof s.input=="string")try{s.input=JSON.parse(s.input)}catch{s.input={}}yield{...s,...i?{cache_control:i}:{}}}else o.type==="container_upload"&&(yield{...o,...i?{cache_control:i}:{}})}}function zye(t,e){let{content:n}=t;return typeof n=="string"?n:Array.from(DUt(n,e))}function CB(t){let e=LUt(t),n;return e.length>0&&e[0]._getType()==="system"&&(n=t[0].content),{messages:$Ut((n!==void 0?e.slice(1):e).map(r=>{let o;if(r._getType()==="human")o="user";else if(r._getType()==="ai")o="assistant";else if(r._getType()==="tool")o="user";else throw r._getType()==="system"?new Error("System messages are only permitted as the first passed message."):new Error(`Message type "${r.type}" is not supported.`);if(kn.isInstance(r)&&r.response_metadata?.output_version==="v1")return{role:o,content:Zqe(r)};if(kn.isInstance(r)&&r.tool_calls?.length){if(typeof r.content=="string")return r.content===""?{role:o,content:r.tool_calls.map(Bye)}:{role:o,content:[{type:"text",text:r.content},...r.tool_calls.map(Bye)]};{let{content:i}=r,s=zye(r,r.tool_calls),a=Array.isArray(s)?s:[{type:"text",text:s}],l=r.tool_calls.filter(c=>!i.find(u=>(u.type==="tool_use"||u.type==="input_json_delta"||u.type==="server_tool_use")&&u.id===c.id));return{role:o,content:[...a,...l.map(Bye)]}}}else return{role:o,content:zye(r,kn.isInstance(r)?r.tool_calls:void 0)}})),system:n}}function $Ut(t){if(!t||t.length<=1)return t;let e=[],n=t[0],r=i=>typeof i=="string"?[{type:"text",text:i}]:i,o=i=>i.role!=="user"||typeof i.content=="string"?!1:Array.isArray(i.content)&&i.content.every(s=>s.type==="tool_result");for(let i=1;i<t.length;i+=1){let s=t[i];o(n)&&o(s)?n={...n,content:[...r(n.content),...r(s.content)]}:(e.push(n),n=s)}return e.push(n),e}var jye=C(()=>{Dye();Jqe();Kr()});function Xqe(t){return t.type==="enabled"||t.type==="adaptive"}function Vye(t){return t?.startsWith("claude-opus-4-7")??!1}function Qqe(t,e){let n=e&&typeof e=="object"&&"task_budget"in e&&e.task_budget!=null;return Vye(t)&&n?["task-budgets-2026-03-13"]:[]}function eGe(t){let{model:e,thinking:n,topK:r,topP:o,temperature:i}=t,s=Vye(e);if(s&&n.type==="enabled")throw new Error('thinking.type="enabled" is not supported for claude-opus-4-7; use thinking.type="adaptive" instead');if(s&&typeof n=="object"&&n!=null&&"budget_tokens"in n)throw new Error("thinking.budget_tokens is not supported for claude-opus-4-7; use outputConfig.effort instead");if(s){if(r!==void 0)throw new Error("topK is not supported for claude-opus-4-7; omit topK/topP/temperature or use model prompting instead");if(o!==void 0&&o!==1)throw new Error("topP is not supported for claude-opus-4-7 when set to non-default values");if(i!==void 0&&i!==1)throw new Error("temperature is not supported for claude-opus-4-7 when set to non-default values")}if(Xqe(n)){if(r!==void 0)throw new Error("topK is not supported when thinking is enabled");if(o!==void 0)throw new Error("topP is not supported when thinking is enabled");if(i!==void 0&&i!==1)throw new Error("temperature is not supported when thinking is enabled")}}function tGe(t){let{model:e,thinking:n,topK:r,topP:o,temperature:i}=t,s={};return Xqe(n)||Vye(e)||(i!==void 0&&(s.temperature=i),r!==void 0&&(s.top_k=r),o!==void 0&&(s.top_p=o)),s}var nGe=C(()=>{});function rGe(t,e){let n={model_provider:"anthropic"};if(t.type==="message_start"){let{content:r,usage:o,...i}=t.message,s={};for(let[d,f]of Object.entries(i))f!=null&&(s[d]=f);let{input_tokens:a,output_tokens:l,...c}=o??{},u=iGe(o);return{chunk:new Yt({content:e.coerceContentToString?"":[],additional_kwargs:s,usage_metadata:e.streamUsage?u:void 0,response_metadata:{...n,usage:{...c}},id:t.message.id})}}else if(t.type==="message_delta"){let r={input_tokens:0,output_tokens:t.usage.output_tokens,total_tokens:t.usage.output_tokens},o="context_management"in t.delta?{context_management:t.delta.context_management}:void 0;return{chunk:new Yt({content:e.coerceContentToString?"":[],response_metadata:o,additional_kwargs:{...t.delta},usage_metadata:e.streamUsage?r:void 0})}}else if(t.type==="content_block_start"&&["tool_use","document","server_tool_use","web_search_tool_result"].includes(t.content_block.type)){let r=t.content_block,o;return r.type==="tool_use"?o=[{id:r.id,index:t.index,name:r.name,args:""}]:o=[],{chunk:new Yt({content:e.coerceContentToString?"":[{index:t.index,...t.content_block,input:r.type==="server_tool_use"||r.type==="tool_use"?"":void 0}],response_metadata:n,additional_kwargs:{},tool_call_chunks:o})}}else if(t.type==="content_block_delta"&&["text_delta","citations_delta","thinking_delta","signature_delta"].includes(t.delta.type)){if(e.coerceContentToString&&"text"in t.delta)return{chunk:new Yt({content:t.delta.text})};{let r=t.delta;return"citation"in r&&(r.citations=[r.citation],delete r.citation),r.type==="thinking_delta"||r.type==="signature_delta"?{chunk:new Yt({content:[{index:t.index,...r,type:"thinking"}],response_metadata:n})}:{chunk:new Yt({content:[{index:t.index,...r,type:"text"}],response_metadata:n})}}}else{if(t.type==="content_block_delta"&&t.delta.type==="input_json_delta")return{chunk:new Yt({content:e.coerceContentToString?"":[{index:t.index,input:t.delta.partial_json,type:t.delta.type}],response_metadata:n,additional_kwargs:{},tool_call_chunks:[{index:t.index,args:t.delta.partial_json}]})};if(t.type==="content_block_start"&&t.content_block.type==="text"){let r=t.content_block?.text;if(r!==void 0)return{chunk:new Yt({content:e.coerceContentToString?r:[{index:t.index,...t.content_block}],response_metadata:n,additional_kwargs:{}})}}else{if(t.type==="content_block_start"&&t.content_block.type==="redacted_thinking")return{chunk:new Yt({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_start"&&t.content_block.type==="thinking"){let r=t.content_block.thinking;return{chunk:new Yt({content:e.coerceContentToString?r:[{index:t.index,...t.content_block}],response_metadata:n})}}else{if(t.type==="content_block_start"&&HG(t.content_block))return{chunk:new Yt({content:e.coerceContentToString?"":[{index:t.index,...t.content_block}],response_metadata:n})};if(t.type==="content_block_delta"&&t.delta.type==="compaction_delta")return{chunk:new Yt({content:e.coerceContentToString?"":[{index:t.index,...t.delta,type:"compaction"}],response_metadata:n})}}}}return null}function oGe(t,e){let n={...e,model_provider:"anthropic"},r=e.usage,o=r!=null?iGe(r):void 0;return t.length===1&&t[0].type==="text"?[{text:t[0].text,message:new kn({content:t[0].text,additional_kwargs:e,usage_metadata:o,response_metadata:n,id:e.id})}]:[{text:"",message:new kn({content:t,additional_kwargs:e,tool_calls:Oye(t),usage_metadata:o,response_metadata:n,id:e.id})}]}function iGe(t){let e=t.cache_creation_input_tokens??0,n=t.cache_read_input_tokens??0,r=t.input_tokens+e+n;return{input_tokens:r,output_tokens:t.output_tokens,total_tokens:r+t.output_tokens,input_token_details:{cache_creation:e,cache_read:n}}}var sGe=C(()=>{Rye();Dye();Kr()});function _B(t,e){return t.lc_error_code=e,t.message=`${t.message}

Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
`,t}function Wye(t){let e;return t.status===400&&typeof t.message=="string"&&t.message.includes("prompt is too long")?e=_B(VFe.fromError(t),"CONTEXT_OVERFLOW"):t.status===400&&t.message.includes("tool")?e=_B(t,"INVALID_TOOL_RESULTS"):t.status===401?e=_B(t,"MODEL_AUTHENTICATION"):t.status===404?e=_B(t,"MODEL_NOT_FOUND"):t.status===429?e=_B(t,"MODEL_RATE_LIMIT"):e=t,e}var aGe=C(()=>{JT()});var lGe,cGe=C(()=>{lGe={"claude-3-sonnet-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5-20251101":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-opus-20240229":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20241022":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-7":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-haiku-20240307":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5-20250929":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-haiku-latest":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-0":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-5-sonnet-20240620":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-1-20250805":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-haiku-4-5-20251001":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-6":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-3-7-sonnet-20250219":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-sonnet-4-5":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0},"claude-opus-4-20250514":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0}}});async function*uGe(t,e={}){let n=e.streamUsage??!0,r=new Map,o,i=null;for await(let s of t)switch(s.type){case"message_start":{let{usage:a,id:l,model:c}=s.message;a&&n&&(o=UUt(a)),yield{event:"message-start",id:l,...o?{usage:o}:{}},yield{event:"provider",provider:"anthropic",name:"message_start",payload:{model:c,id:l}};break}case"message_delta":i=s.delta.stop_reason,n&&s.usage&&(o?o={...o,output_tokens:o.output_tokens+s.usage.output_tokens,total_tokens:o.input_tokens+o.output_tokens+s.usage.output_tokens}:o={input_tokens:0,output_tokens:s.usage.output_tokens,total_tokens:s.usage.output_tokens},yield{event:"usage",usage:o}),"context_management"in s.delta&&s.delta.context_management&&(yield{event:"provider",provider:"anthropic",name:"context_management",payload:s.delta.context_management});break;case"message_stop":yield{event:"message-finish",reason:FUt(i),...o?{usage:o}:{},metadata:{model_provider:"anthropic"}};break;case"content_block_start":{let{index:a,content_block:l}=s,c=BUt(l,a);r.set(a,{...c}),yield{event:"content-block-start",index:a,content:c};break}case"content_block_delta":{let{index:a,delta:l}=s,c=r.get(a);if(!c)break;let{contentDelta:u,accumulated:d}=zUt(c,l);r.set(a,d),yield{event:"content-block-delta",index:a,delta:u};break}case"content_block_stop":{let{index:a}=s,l=r.get(a);if(!l)break;yield{event:"content-block-finish",index:a,content:jUt(l)},r.delete(a);break}default:yield{event:"provider",provider:"anthropic",name:s.type,payload:s};break}}function FUt(t){switch(t){case"end_turn":case"stop_sequence":return"stop";case"tool_use":return"tool_use";case"max_tokens":return"length";default:return"stop"}}function UUt(t){let e=t.cache_creation_input_tokens??0,n=t.cache_read_input_tokens??0,r=t.input_tokens+e+n;return{input_tokens:r,output_tokens:t.output_tokens,total_tokens:r+t.output_tokens,input_token_details:{cache_creation:e,cache_read:n}}}function BUt(t,e){switch(t.type){case"text":return{type:"text",text:t.text??"",index:e};case"thinking":return{type:"reasoning",reasoning:t.thinking??"",index:e};case"redacted_thinking":return{type:"non_standard",value:{...t},index:e};case"tool_use":return{type:"tool_call_chunk",id:t.id,name:t.name,args:"",index:e};case"server_tool_use":return{type:"server_tool_call_chunk",id:t.id,name:t.name,args:"",index:e};default:return{type:"non_standard",value:{...t},index:e}}}function zUt(t,e){switch(e.type){case"text_delta":return{contentDelta:{type:"text-delta",text:e.text},accumulated:{...t,text:(t.text??"")+e.text}};case"thinking_delta":return{contentDelta:{type:"reasoning-delta",reasoning:e.thinking},accumulated:{...t,reasoning:(t.reasoning??"")+e.thinking}};case"input_json_delta":{let n=(t.args??"")+e.partial_json;return{contentDelta:{type:"block-delta",fields:{type:t.type,args:n}},accumulated:{...t,args:n}}}case"citations_delta":{let n=[...t.annotations??[],e.citation];return{contentDelta:{type:"block-delta",fields:{type:t.type,annotations:n}},accumulated:{...t,annotations:n}}}case"signature_delta":return{contentDelta:{type:"block-delta",fields:{type:t.type,signature:e.signature}},accumulated:{...t,signature:e.signature}};case"compaction_delta":return{contentDelta:{type:"block-delta",fields:{type:"non_standard",value:{...t.value??{},compaction:e}}},accumulated:{...t,value:{...t.value??{},compaction:e}}};default:return{contentDelta:{type:"block-delta",fields:{type:t.type,...e}},accumulated:t}}}function jUt(t){if(t.type==="tool_call_chunk"||t.type==="server_tool_call_chunk"){let r=t.type==="tool_call_chunk"?"tool_call":"server_tool_call",o;try{o=JSON.parse(t.args||"{}")}catch{return{type:"invalid_tool_call",id:t.id,name:t.name,args:t.args,error:"Failed to parse tool call arguments as JSON"}}return{type:r,id:t.id,name:t.name,args:o}}let{index:e,...n}=t;return n}var dGe=C(()=>{});function at(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n}function ue(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}var dv=C(()=>{});var Hye,Kye=C(()=>{Hye=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Hye=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))}});function fv(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var SB,pO=C(()=>{SB=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)}});var Ut,Va,Il,BC,mO,hO,gO,yO,wO,vO,xO,bO,CO,tu=C(()=>{pO();Ut=class extends Error{},Va=class t extends Ut{constructor(e,n,r,o,i){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=o,this.requestID=o?.get("request-id"),this.error=n,this.type=i??null}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new BC({message:r,cause:SB(n)});let i=n,s=i?.error?.type;return e===400?new hO(e,i,r,o,s):e===401?new gO(e,i,r,o,s):e===403?new yO(e,i,r,o,s):e===404?new wO(e,i,r,o,s):e===409?new vO(e,i,r,o,s):e===422?new xO(e,i,r,o,s):e===429?new bO(e,i,r,o,s):e>=500?new CO(e,i,r,o,s):new t(e,i,r,o,s)}},Il=class extends Va{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},BC=class extends Va{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},mO=class extends BC{constructor({message:e}={}){super({message:e??"Request timed out."})}},hO=class extends Va{},gO=class extends Va{},yO=class extends Va{},wO=class extends Va{},vO=class extends Va{},xO=class extends Va{},bO=class extends Va{},CO=class extends Va{}});function KG(t){return typeof t!="object"?{}:t??{}}function Yye(t){if(!t)return!0;for(let e in t)return!1;return!0}function pGe(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var WUt,fGe,qye,Gye,mGe,qG,nu,zC=C(()=>{tu();WUt=/^[a-z][a-z0-9+.-]*:/i,fGe=t=>WUt.test(t),qye=t=>(qye=Array.isArray,qye(t)),Gye=qye;mGe=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Ut(`${t} must be an integer`);if(e<0)throw new Ut(`${t} must be a positive integer`);return e},qG=t=>{try{return JSON.parse(t)}catch{return}},nu=(t,e)=>{let n=t[e];return delete t[e],n}});var hGe,Zye=C(()=>{hGe=t=>new Promise(e=>setTimeout(e,t))});var jC,Jye=C(()=>{jC="0.91.1"});function HUt(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}function qUt(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}var vGe,KUt,gGe,yGe,wGe,xGe,Xye=C(()=>{Jye();vGe=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";KUt=()=>{let t=HUt();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":jC,"X-Stainless-OS":yGe(Deno.build.os),"X-Stainless-Arch":gGe(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":jC,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":jC,"X-Stainless-OS":yGe(globalThis.process.platform??"unknown"),"X-Stainless-Arch":gGe(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=qUt();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":jC,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":jC,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};gGe=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",yGe=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),xGe=()=>wGe??(wGe=KUt())});function bGe(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Qye(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function GG(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Qye({start(){},async pull(n){let{done:r,value:o}=await e.next();r?n.close():n.enqueue(o)},async cancel(){await e.return?.()}})}function TB(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function CGe(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),n=e.cancel();e.releaseLock(),await n}var _O=C(()=>{});var _Ge,SGe=C(()=>{_Ge=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)})});function TGe(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new Ut(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}var ewe=C(()=>{tu()});function EGe(t){let e=0;for(let o of t)e+=o.length;let n=new Uint8Array(e),r=0;for(let o of t)n.set(o,r),r+=o.length;return n}function SO(t){let e;return(IGe??(e=new globalThis.TextEncoder,IGe=e.encode.bind(e)))(t)}function twe(t){let e;return(PGe??(e=new globalThis.TextDecoder,PGe=e.decode.bind(e)))(t)}var IGe,PGe,YG=C(()=>{});function ZUt(t,e){for(let o=e??0;o<t.length;o++){if(t[o]===10)return{preceding:o,index:o+1,carriage:!1};if(t[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function AGe(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}var sf,af,pv,nwe=C(()=>{dv();YG();pv=class{constructor(){sf.set(this,void 0),af.set(this,void 0),at(this,sf,new Uint8Array,"f"),at(this,af,null,"f")}decode(e){if(e==null)return[];let n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?SO(e):e;at(this,sf,EGe([ue(this,sf,"f"),n]),"f");let r=[],o;for(;(o=ZUt(ue(this,sf,"f"),ue(this,af,"f")))!=null;){if(o.carriage&&ue(this,af,"f")==null){at(this,af,o.index,"f");continue}if(ue(this,af,"f")!=null&&(o.index!==ue(this,af,"f")+1||o.carriage)){r.push(twe(ue(this,sf,"f").subarray(0,ue(this,af,"f")-1))),at(this,sf,ue(this,sf,"f").subarray(ue(this,af,"f")),"f"),at(this,af,null,"f");continue}let i=ue(this,af,"f")!==null?o.preceding-1:o.preceding,s=twe(ue(this,sf,"f").subarray(0,i));r.push(s),at(this,sf,ue(this,sf,"f").subarray(o.index),"f"),at(this,af,null,"f")}return r}flush(){return ue(this,sf,"f").length?this.decode(`
`):[]}};sf=new WeakMap,af=new WeakMap;pv.NEWLINE_CHARS=new Set([`
`,"\r"]);pv.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function IB(){}function ZG(t,e,n){return!e||JG[t]>JG[n]?IB:e[t].bind(e)}function Wa(t){let e=t.logger,n=t.logLevel??"off";if(!e)return JUt;let r=kGe.get(e);if(r&&r[0]===n)return r[1];let o={error:ZG("error",e,n),warn:ZG("warn",e,n),info:ZG("info",e,n),debug:ZG("debug",e,n)};return kGe.set(e,[n,o]),o}var JG,rwe,JUt,kGe,mv,PB=C(()=>{zC();JG={off:0,error:200,warn:300,info:400,debug:500},rwe=(t,e,n)=>{if(t){if(pGe(JG,t))return t;Wa(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(JG))}`)}};JUt={error:IB,warn:IB,info:IB,debug:IB},kGe=new WeakMap;mv=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t)});async function*XUt(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ut("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Ut("Attempted to iterate over a response with no body");let n=new owe,r=new pv,o=TB(t.body);for await(let i of QUt(o))for(let s of r.decode(i)){let a=n.decode(s);a&&(yield a)}for(let i of r.flush()){let s=n.decode(i);s&&(yield s)}}async function*QUt(t){let e=new Uint8Array;for await(let n of t){if(n==null)continue;let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?SO(n):n,o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length),e=o;let i;for(;(i=AGe(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}function eBt(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}var EB,ly,owe,iwe=C(()=>{dv();tu();_O();nwe();_O();pO();zC();YG();PB();tu();ly=class t{constructor(e,n,r){this.iterator=e,EB.set(this,void 0),this.controller=n,at(this,EB,r,"f")}static fromSSEResponse(e,n,r){let o=!1,i=r?Wa(r):console;async function*s(){if(o)throw new Ut("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of XUt(e,n)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop"||l.event==="message"||l.event==="user.message"||l.event==="user.interrupt"||l.event==="user.tool_confirmation"||l.event==="user.custom_tool_result"||l.event==="agent.message"||l.event==="agent.thinking"||l.event==="agent.tool_use"||l.event==="agent.tool_result"||l.event==="agent.mcp_tool_use"||l.event==="agent.mcp_tool_result"||l.event==="agent.custom_tool_use"||l.event==="agent.thread_context_compacted"||l.event==="session.status_running"||l.event==="session.status_idle"||l.event==="session.status_rescheduled"||l.event==="session.status_terminated"||l.event==="session.error"||l.event==="session.deleted"||l.event==="span.model_request_start"||l.event==="span.model_request_end")try{yield JSON.parse(l.data)}catch(c){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),c}if(l.event!=="ping"&&l.event==="error"){let c=qG(l.data)??l.data,u=c?.error?.type;throw new Va(void 0,c,void 0,e.headers,u)}}a=!0}catch(l){if(fv(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}static fromReadableStream(e,n,r){let o=!1;async function*i(){let a=new pv,l=TB(e);for await(let c of l)for(let u of a.decode(c))yield u;for(let c of a.flush())yield c}async function*s(){if(o)throw new Ut("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(fv(l))return;throw l}finally{a||n.abort()}}return new t(s,n,r)}[(EB=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller,ue(this,EB,"f")),new t(()=>o(n),this.controller,ue(this,EB,"f"))]}toReadableStream(){let e=this,n;return Qye({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{let{value:o,done:i}=await n.next();if(i)return r.close();let s=SO(JSON.stringify(o)+`
`);r.enqueue(s)}catch(o){r.error(o)}},async cancel(){await n.return?.()}})}};owe=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=eBt(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}}});async function XG(t,e){let{response:n,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s=await(async()=>{if(e.options.stream)return Wa(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller):ly.fromSSEResponse(n,e.controller);if(n.status===204)return null;if(e.options.__binaryResponse)return n;let l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){if(n.headers.get("content-length")==="0")return;let f=await n.json();return swe(f,n)}return await n.text()})();return Wa(t).debug(`[${r}] response parsed`,mv({retryOfRequestLogID:o,url:n.url,status:n.status,body:s,durationMs:Date.now()-i})),s}function swe(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var awe=C(()=>{iwe();PB()});var AB,O0,QG=C(()=>{dv();awe();O0=class t extends Promise{constructor(e,n,r=XG){super(o=>{o(null)}),this.responsePromise=n,this.parseResponse=r,AB.set(this,void 0),at(this,AB,e,"f")}_thenUnwrap(e){return new t(ue(this,AB,"f"),this.responsePromise,async(n,r)=>swe(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(ue(this,AB,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};AB=new WeakMap});var e8,t8,kB,Pp,io,Hi=C(()=>{dv();tu();awe();QG();zC();t8=class{constructor(e,n,r,o){e8.set(this,void 0),at(this,e8,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new Ut("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await ue(this,e8,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(e8=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},kB=class extends O0{constructor(e,n,r){super(e,n,async(o,i)=>new r(o,i.response,await XG(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},Pp=class extends t8{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.first_id=r.first_id||null,this.last_id=r.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let n=this.first_id;return n?{...this.options,query:{...KG(this.options.query),before_id:n}}:null}let e=this.last_id;return e?{...this.options,query:{...KG(this.options.query),after_id:e}}:null}},io=class extends t8{constructor(e,n,r,o){super(e,n,r,o),this.data=r.data||[],this.next_page=r.next_page||null}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){let e=this.next_page;return e?{...this.options,query:{...KG(this.options.query),page:e}}:null}}});function R0(t,e,n){return cwe(),new File(t,e??"unknown_file",n)}function MB(t,e){let n=typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"";return e?n.split(/[\\/]/).pop()||void 0:n}function nBt(t){let e=typeof t=="function"?t:t.fetch,n=MGe.get(e);if(n)return n;let r=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return MGe.set(e,r),r}var cwe,uwe,TO,MGe,rBt,oBt,lwe,IO=C(()=>{_O();cwe=()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};uwe=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",TO=async(t,e,n=!0)=>({...t,body:await rBt(t.body,e,n)}),MGe=new WeakMap;rBt=async(t,e,n=!0)=>{if(!await nBt(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([o,i])=>lwe(r,o,i,n))),r},oBt=t=>t instanceof Blob&&"name"in t,lwe=async(t,e,n,r)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response){let o={},i=n.headers.get("Content-Type");i&&(o={type:i}),t.append(e,R0([await n.blob()],MB(n,r),o))}else if(uwe(n))t.append(e,R0([await new Response(GG(n)).blob()],MB(n,r)));else if(oBt(n))t.append(e,R0([n],MB(n,r),{type:n.type}));else if(Array.isArray(n))await Promise.all(n.map(o=>lwe(t,e+"[]",o,r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([o,i])=>lwe(t,`${e}[${o}]`,i,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}});async function n8(t,e,n){if(cwe(),t=await t,e||(e=MB(t,!0)),iBt(t))return t instanceof File&&e==null&&n==null?t:R0([await t.arrayBuffer()],e??t.name,{type:t.type,lastModified:t.lastModified,...n});if(sBt(t)){let o=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),R0(await dwe(o),e,n)}let r=await dwe(t);if(!n?.type){let o=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof o=="string"&&(n={...n,type:o})}return R0(r,e,n)}async function dwe(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(NGe(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(uwe(t))for await(let n of t)e.push(...await dwe(n));else{let n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${aBt(t)}`)}return e}function aBt(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}var NGe,iBt,sBt,OGe=C(()=>{IO();IO();NGe=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",iBt=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&NGe(t),sBt=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function"});var fwe=C(()=>{OGe()});var RGe=C(()=>{});var Mn,pi=C(()=>{Mn=class{constructor(e){this._client=e}}});function*cBt(t){if(!t)return;if(LGe in t){let{values:r,nulls:o}=t;yield*r.entries();for(let i of o)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Gye(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){let o=r[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let i=Gye(r[1])?r[1]:[r[1]],s=!1;for(let a of i)a!==void 0&&(e&&!s&&(s=!0,yield[o,null]),yield[o,a])}}var LGe,_e,ri=C(()=>{zC();LGe=Symbol.for("brand.privateNullableHeaders");_e=t=>{let e=new Headers,n=new Set;for(let r of t){let o=new Set;for(let[i,s]of cBt(r)){let a=i.toLowerCase();o.has(a)||(e.delete(i),o.add(a)),s===null?(e.delete(i),n.add(a)):(e.append(i,s),n.delete(a))}}return{[LGe]:!0,values:e,nulls:n}}});function $Ge(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var DGe,uBt,et,Ts=C(()=>{tu();DGe=Object.freeze(Object.create(null)),uBt=(t=$Ge)=>function(n,...r){if(n.length===1)return n[0];let o=!1,i=[],s=n.reduce((u,d,f)=>{/[?#]/.test(d)&&(o=!0);let p=r[f],m=(o?encodeURIComponent:t)(""+p);return f!==r.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??DGe)??DGe)?.toString)&&(m=p+"",i.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),u+d+(f===r.length?"":m)},""),a=s.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=l.exec(a))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(i.sort((u,d)=>u.start-d.start),i.length>0){let u=0,d=i.reduce((f,p)=>{let m=" ".repeat(p.start-u),h="^".repeat(p.length);return u=p.start+p.length,f+m+h},"");throw new Ut(`Path parameters result in path with invalid segments:
${i.map(f=>f.error).join(`
`)}
${s}
${d}`)}return s},et=uBt($Ge)});var PO,pwe=C(()=>{pi();Hi();ri();Ts();PO=class extends Mn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/environments?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/environments/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/environments/${e}?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/environments?beta=true",io,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(et`/v1/environments/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(et`/v1/environments/${e}/archive?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});function r8(t){return typeof t=="object"&&t!==null&&NB in t}function mwe(t,e){let n=new Set;if(t)for(let r of t)r8(r)&&n.add(r[NB]);if(e){for(let r of e)if(r8(r)&&n.add(r[NB]),Array.isArray(r.content))for(let o of r.content)r8(o)&&n.add(o[NB])}return Array.from(n)}function o8(t,e){let n=mwe(t,e);return n.length===0?{}:{"x-stainless-helper":n.join(", ")}}function FGe(t){return r8(t)?{"x-stainless-helper":t[NB]}:{}}var NB,OB=C(()=>{NB=Symbol("anthropic.sdk.stainlessHelper")});var EO,hwe=C(()=>{pi();Hi();ri();OB();IO();Ts();EO=class extends Mn{list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/files?beta=true",Pp,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(et`/v1/files/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},r?.headers])})}download(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/files/${e}/content?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}retrieveMetadata(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/files/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"files-api-2025-04-14"].toString()},r?.headers])})}upload(e,n){let{betas:r,...o}=e;return this._client.post("/v1/files?beta=true",TO({body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},FGe(o.file),n?.headers])},this._client))}}});var AO,gwe=C(()=>{pi();Hi();ri();Ts();AO=class extends Mn{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/models/${e}?beta=true`,{...r,headers:_e([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models?beta=true",Pp,{query:o,...n,headers:_e([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}}});var kO,ywe=C(()=>{pi();Hi();ri();Ts();kO=class extends Mn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/user_profiles?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/user_profiles/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/user_profiles/${e}?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/user_profiles?beta=true",io,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"user-profiles-2026-03-24"].toString()},n?.headers])})}createEnrollmentURL(e,n={},r){let{betas:o}=n??{};return this._client.post(et`/v1/user_profiles/${e}/enrollment_url?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"user-profiles-2026-03-24"].toString()},r?.headers])})}}});var MO,wwe=C(()=>{pi();Hi();ri();Ts();MO=class extends Mn{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(et`/v1/agents/${e}/versions?beta=true`,io,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var L0,vwe=C(()=>{pi();wwe();wwe();Hi();ri();Ts();L0=class extends Mn{constructor(){super(...arguments),this.versions=new MO(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/agents?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o,...i}=n??{};return this._client.get(et`/v1/agents/${e}?beta=true`,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/agents/${e}?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/agents?beta=true",io,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(et`/v1/agents/${e}/archive?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};L0.Versions=MO});var NO,xwe=C(()=>{pi();Hi();ri();Ts();NO=class extends Mn{create(e,n,r){let{view:o,betas:i,...s}=n;return this._client.post(et`/v1/memory_stores/${e}/memories?beta=true`,{query:{view:o},body:s,...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,n,r){let{memory_store_id:o,betas:i,...s}=n;return this._client.get(et`/v1/memory_stores/${o}/memories/${e}?beta=true`,{query:s,...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{memory_store_id:o,view:i,betas:s,...a}=n;return this._client.post(et`/v1/memory_stores/${o}/memories/${e}?beta=true`,{query:{view:i},body:a,...r,headers:_e([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(et`/v1/memory_stores/${e}/memories?beta=true`,io,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{memory_store_id:o,expected_content_sha256:i,betas:s}=n;return this._client.delete(et`/v1/memory_stores/${o}/memories/${e}?beta=true`,{query:{expected_content_sha256:i},...r,headers:_e([{"anthropic-beta":[...s??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var OO,bwe=C(()=>{pi();Hi();ri();Ts();OO=class extends Mn{retrieve(e,n,r){let{memory_store_id:o,betas:i,...s}=n;return this._client.get(et`/v1/memory_stores/${o}/memory_versions/${e}?beta=true`,{query:s,...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(et`/v1/memory_stores/${e}/memory_versions?beta=true`,io,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}redact(e,n,r){let{memory_store_id:o,betas:i}=n;return this._client.post(et`/v1/memory_stores/${o}/memory_versions/${e}/redact?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var VC,Cwe=C(()=>{pi();xwe();xwe();bwe();bwe();Hi();ri();Ts();VC=class extends Mn{constructor(){super(...arguments),this.memories=new NO(this._client),this.memoryVersions=new OO(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/memory_stores?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/memory_stores/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/memory_stores/${e}?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/memory_stores?beta=true",io,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(et`/v1/memory_stores/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(et`/v1/memory_stores/${e}/archive?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};VC.Memories=NO;VC.MemoryVersions=OO});var RO=C(()=>{tu()});var i8,_we=C(()=>{i8={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192}});function UGe(t){return t?.output_format??t?.output_config?.format}function Swe(t,e,n){let r=UGe(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(o=>{if(o.type==="text"){let i=Object.defineProperty({...o},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(i,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return o}),parsed_output:null}:Twe(t,e,n)}function Twe(t,e,n){let r=null,o=t.content.map(i=>{if(i.type==="text"){let s=xBt(e,i.text);r===null&&(r=s);let a=Object.defineProperty({...i},"parsed_output",{value:s,enumerable:!1});return Object.defineProperty(a,"parsed",{get(){return n.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),s},enumerable:!1})}return i});return{...t,content:o,parsed_output:r}}function xBt(t,e){let n=UGe(t);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new Ut(`Failed to parse structured output: ${r}`)}}var Iwe=C(()=>{tu()});var bBt,LO,CBt,_Bt,s8,Pwe=C(()=>{bBt=t=>{let e=0,n=[];for(;e<t.length;){let r=t[e];if(r==="\\"){e++;continue}if(r==="{"){n.push({type:"brace",value:"{"}),e++;continue}if(r==="}"){n.push({type:"brace",value:"}"}),e++;continue}if(r==="["){n.push({type:"paren",value:"["}),e++;continue}if(r==="]"){n.push({type:"paren",value:"]"}),e++;continue}if(r===":"){n.push({type:"separator",value:":"}),e++;continue}if(r===","){n.push({type:"delimiter",value:","}),e++;continue}if(r==='"'){let a="",l=!1;for(r=t[++e];r!=='"';){if(e===t.length){l=!0;break}if(r==="\\"){if(e++,e===t.length){l=!0;break}a+=r+t[e],r=t[++e]}else a+=r,r=t[++e]}r=t[++e],l||n.push({type:"string",value:a});continue}if(r&&/\s/.test(r)){e++;continue}let i=/[0-9]/;if(r&&i.test(r)||r==="-"||r==="."){let a="";for(r==="-"&&(a+=r,r=t[++e]);r&&i.test(r)||r===".";)a+=r,r=t[++e];n.push({type:"number",value:a});continue}let s=/[a-z]/i;if(r&&s.test(r)){let a="";for(;r&&s.test(r)&&e!==t.length;)a+=r,r=t[++e];if(a=="true"||a=="false"||a==="null")n.push({type:"name",value:a});else{e++;continue}continue}e++}return n},LO=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),LO(t);break;case"number":let n=e.value[e.value.length-1];if(n==="."||n==="-")return t=t.slice(0,t.length-1),LO(t);case"string":let r=t[t.length-2];if(r?.type==="delimiter")return t=t.slice(0,t.length-1),LO(t);if(r?.type==="brace"&&r.value==="{")return t=t.slice(0,t.length-1),LO(t);break;case"delimiter":return t=t.slice(0,t.length-1),LO(t);break}return t},CBt=t=>{let e=[];return t.map(n=>{n.type==="brace"&&(n.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),n.type==="paren"&&(n.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(n=>{n==="}"?t.push({type:"brace",value:"}"}):n==="]"&&t.push({type:"paren",value:"]"})}),t},_Bt=t=>{let e="";return t.map(n=>{switch(n.type){case"string":e+='"'+n.value+'"';break;default:e+=n.value;break}}),e},s8=t=>JSON.parse(_Bt(CBt(LO(bBt(t)))))});var Ewe=C(()=>{iwe()});function VGe(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var Ep,WC,DO,RB,a8,LB,DB,l8,$B,hv,FB,c8,u8,D0,d8,f8,UB,Awe,BGe,p8,kwe,Mwe,Nwe,zGe,jGe,m8,WGe=C(()=>{dv();Pwe();RO();pO();Ewe();Iwe();jGe="__json_buf";m8=class t{constructor(e,n){Ep.add(this),this.messages=[],this.receivedMessages=[],WC.set(this,void 0),DO.set(this,null),this.controller=new AbortController,RB.set(this,void 0),a8.set(this,()=>{}),LB.set(this,()=>{}),DB.set(this,void 0),l8.set(this,()=>{}),$B.set(this,()=>{}),hv.set(this,{}),FB.set(this,!1),c8.set(this,!1),u8.set(this,!1),D0.set(this,!1),d8.set(this,void 0),f8.set(this,void 0),UB.set(this,void 0),p8.set(this,r=>{if(at(this,c8,!0,"f"),fv(r)&&(r=new Il),r instanceof Il)return at(this,u8,!0,"f"),this._emit("abort",r);if(r instanceof Ut)return this._emit("error",r);if(r instanceof Error){let o=new Ut(r.message);return o.cause=r,this._emit("error",o)}return this._emit("error",new Ut(String(r)))}),at(this,RB,new Promise((r,o)=>{at(this,a8,r,"f"),at(this,LB,o,"f")}),"f"),at(this,DB,new Promise((r,o)=>{at(this,l8,r,"f"),at(this,$B,o,"f")}),"f"),ue(this,RB,"f").catch(()=>{}),ue(this,DB,"f").catch(()=>{}),at(this,DO,e,"f"),at(this,UB,n?.logger??console,"f")}get response(){return ue(this,d8,"f")}get request_id(){return ue(this,f8,"f")}async withResponse(){at(this,D0,!0,"f");let e=await ue(this,RB,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:o}={}){let i=new t(n,{logger:o});for(let s of n.messages)i._addMessageParam(s);return at(i,DO,{...n,stream:!0},"f"),i._run(()=>i._createMessage(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},ue(this,p8,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){let o=r?.signal,i;o&&(o.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),o.addEventListener("abort",i));try{ue(this,Ep,"m",kwe).call(this);let{response:s,data:a}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)ue(this,Ep,"m",Mwe).call(this,l);if(a.controller.signal?.aborted)throw new Il;ue(this,Ep,"m",Nwe).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(at(this,d8,e,"f"),at(this,f8,e?.headers.get("request-id"),"f"),ue(this,a8,"f").call(this,e),this._emit("connect"))}get ended(){return ue(this,FB,"f")}get errored(){return ue(this,c8,"f")}get aborted(){return ue(this,u8,"f")}abort(){this.controller.abort()}on(e,n){return(ue(this,hv,"f")[e]||(ue(this,hv,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=ue(this,hv,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(ue(this,hv,"f")[e]||(ue(this,hv,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{at(this,D0,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){at(this,D0,!0,"f"),await ue(this,DB,"f")}get currentMessage(){return ue(this,WC,"f")}async finalMessage(){return await this.done(),ue(this,Ep,"m",Awe).call(this)}async finalText(){return await this.done(),ue(this,Ep,"m",BGe).call(this)}_emit(e,...n){if(ue(this,FB,"f"))return;e==="end"&&(at(this,FB,!0,"f"),ue(this,l8,"f").call(this));let r=ue(this,hv,"f")[e];if(r&&(ue(this,hv,"f")[e]=r.filter(o=>!o.once),r.forEach(({listener:o})=>o(...n))),e==="abort"){let o=n[0];!ue(this,D0,"f")&&!r?.length&&Promise.reject(o),ue(this,LB,"f").call(this,o),ue(this,$B,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=n[0];!ue(this,D0,"f")&&!r?.length&&Promise.reject(o),ue(this,LB,"f").call(this,o),ue(this,$B,"f").call(this,o),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",ue(this,Ep,"m",Awe).call(this))}async _fromReadableStream(e,n){let r=n?.signal,o;r&&(r.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),r.addEventListener("abort",o));try{ue(this,Ep,"m",kwe).call(this),this._connected(null);let i=ly.fromReadableStream(e,this.controller);for await(let s of i)ue(this,Ep,"m",Mwe).call(this,s);if(i.controller.signal?.aborted)throw new Il;ue(this,Ep,"m",Nwe).call(this)}finally{r&&o&&r.removeEventListener("abort",o)}}[(WC=new WeakMap,DO=new WeakMap,RB=new WeakMap,a8=new WeakMap,LB=new WeakMap,DB=new WeakMap,l8=new WeakMap,$B=new WeakMap,hv=new WeakMap,FB=new WeakMap,c8=new WeakMap,u8=new WeakMap,D0=new WeakMap,d8=new WeakMap,f8=new WeakMap,UB=new WeakMap,p8=new WeakMap,Ep=new WeakSet,Awe=function(){if(this.receivedMessages.length===0)throw new Ut("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},BGe=function(){if(this.receivedMessages.length===0)throw new Ut("stream ended without producing a Message with role=assistant");let n=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(n.length===0)throw new Ut("stream ended without producing a content block with type=text");return n.join(" ")},kwe=function(){this.ended||at(this,WC,void 0,"f")},Mwe=function(n){if(this.ended)return;let r=ue(this,Ep,"m",zGe).call(this,n);switch(this._emit("streamEvent",n,r),n.type){case"content_block_delta":{let o=r.content.at(-1);switch(n.delta.type){case"text_delta":{o.type==="text"&&this._emit("text",n.delta.text,o.text||"");break}case"citations_delta":{o.type==="text"&&this._emit("citation",n.delta.citation,o.citations??[]);break}case"input_json_delta":{VGe(o)&&o.input&&this._emit("inputJson",n.delta.partial_json,o.input);break}case"thinking_delta":{o.type==="thinking"&&this._emit("thinking",n.delta.thinking,o.thinking);break}case"signature_delta":{o.type==="thinking"&&this._emit("signature",o.signature);break}case"compaction_delta":{o.type==="compaction"&&o.content&&this._emit("compaction",o.content);break}default:n.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(Swe(r,ue(this,DO,"f"),{logger:ue(this,UB,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{at(this,WC,r,"f");break}case"content_block_start":case"message_delta":break}},Nwe=function(){if(this.ended)throw new Ut("stream has ended, this shouldn't happen");let n=ue(this,WC,"f");if(!n)throw new Ut("request ended without sending any chunks");return at(this,WC,void 0,"f"),Swe(n,ue(this,DO,"f"),{logger:ue(this,UB,"f")})},zGe=function(n){let r=ue(this,WC,"f");if(n.type==="message_start"){if(r)throw new Ut(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!r)throw new Ut(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return r;case"message_delta":return r.container=n.delta.container,r.stop_reason=n.delta.stop_reason,r.stop_sequence=n.delta.stop_sequence,r.usage.output_tokens=n.usage.output_tokens,r.context_management=n.context_management,n.usage.input_tokens!=null&&(r.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(r.usage.server_tool_use=n.usage.server_tool_use),n.usage.iterations!=null&&(r.usage.iterations=n.usage.iterations),r;case"content_block_start":return r.content.push(n.content_block),r;case"content_block_delta":{let o=r.content.at(n.index);switch(n.delta.type){case"text_delta":{o?.type==="text"&&(r.content[n.index]={...o,text:(o.text||"")+n.delta.text});break}case"citations_delta":{o?.type==="text"&&(r.content[n.index]={...o,citations:[...o.citations??[],n.delta.citation]});break}case"input_json_delta":{if(o&&VGe(o)){let i=o[jGe]||"";i+=n.delta.partial_json;let s={...o};if(Object.defineProperty(s,jGe,{value:i,enumerable:!1,writable:!0}),i)try{s.input=s8(i)}catch(a){let l=new Ut(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${i}`);ue(this,p8,"f").call(this,l)}r.content[n.index]=s}break}case"thinking_delta":{o?.type==="thinking"&&(r.content[n.index]={...o,thinking:o.thinking+n.delta.thinking});break}case"signature_delta":{o?.type==="thinking"&&(r.content[n.index]={...o,signature:n.delta.signature});break}case"compaction_delta":{o?.type==="compaction"&&(r.content[n.index]={...o,content:(o.content||"")+n.delta.content});break}default:n.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("streamEvent",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ly(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var $0,h8=C(()=>{$0=class extends Error{constructor(e){let n=typeof e=="string"?e:e.map(r=>r.type==="text"?r.text:`[${r.type}]`).join(" ");super(n),this.name="ToolError",this.content=e}}});var HGe,KGe=C(()=>{HGe=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`});function GGe(){let t,e;return{promise:new Promise((r,o)=>{t=r,e=o}),resolve:t,reject:e}}async function TBt(t,e=t.messages.at(-1),n){if(!e||e.role!=="assistant"||!e.content||typeof e.content=="string")return null;let r=e.content.filter(i=>i.type==="tool_use");return r.length===0?null:{role:"user",content:await Promise.all(r.map(async i=>{let s=t.tools.find(a=>("name"in a?a.name:a.mcp_server_name)===i.name);if(!s||!("run"in s))return{type:"tool_result",tool_use_id:i.id,content:`Error: Tool '${i.name}' not found`,is_error:!0};try{let a=i.input;"parse"in s&&s.parse&&(a=s.parse(a));let l=await s.run(a,{toolUseBlock:i,signal:n?.signal});return{type:"tool_result",tool_use_id:i.id,content:l}}catch(a){return{type:"tool_result",tool_use_id:i.id,content:a instanceof $0?a.content:`Error: ${a instanceof Error?a.message:String(a)}`,is_error:!0}}}))}}var BB,$O,F0,Ys,Qu,lf,gv,HC,zB,qGe,Owe,FO,Rwe=C(()=>{dv();h8();tu();ri();KGe();OB();FO=class{constructor(e,n,r){BB.add(this),this.client=e,$O.set(this,!1),F0.set(this,!1),Ys.set(this,void 0),Qu.set(this,void 0),lf.set(this,void 0),gv.set(this,void 0),HC.set(this,void 0),zB.set(this,0),at(this,Ys,{params:{...n,messages:structuredClone(n.messages)}},"f");let i=["BetaToolRunner",...mwe(n.tools,n.messages)].join(", ");at(this,Qu,{...r,headers:_e([{"x-stainless-helper":i},r?.headers])},"f"),at(this,HC,GGe(),"f"),n.compactionControl?.enabled&&console.warn('Anthropic: The `compactionControl` parameter is deprecated and will be removed in a future version. Use server-side compaction instead by passing `edits: [{ type: "compact_20260112" }]` in the params passed to `toolRunner()`. See https://platform.claude.com/docs/en/build-with-claude/compaction')}async*[($O=new WeakMap,F0=new WeakMap,Ys=new WeakMap,Qu=new WeakMap,lf=new WeakMap,gv=new WeakMap,HC=new WeakMap,zB=new WeakMap,BB=new WeakSet,qGe=async function(){let n=ue(this,Ys,"f").params.compactionControl;if(!n||!n.enabled)return!1;let r=0;if(ue(this,lf,"f")!==void 0)try{let c=await ue(this,lf,"f");r=c.usage.input_tokens+(c.usage.cache_creation_input_tokens??0)+(c.usage.cache_read_input_tokens??0)+c.usage.output_tokens}catch{return!1}let o=n.contextTokenThreshold??1e5;if(r<o)return!1;let i=n.model??ue(this,Ys,"f").params.model,s=n.summaryPrompt??HGe,a=ue(this,Ys,"f").params.messages;if(a[a.length-1].role==="assistant"){let c=a[a.length-1];if(Array.isArray(c.content)){let u=c.content.filter(d=>d.type!=="tool_use");u.length===0?a.pop():c.content=u}}let l=await this.client.beta.messages.create({model:i,messages:[...a,{role:"user",content:[{type:"text",text:s}]}],max_tokens:ue(this,Ys,"f").params.max_tokens},{signal:ue(this,Qu,"f").signal,headers:_e([ue(this,Qu,"f").headers,{"x-stainless-helper":"compaction"}])});if(l.content[0]?.type!=="text")throw new Ut("Expected text response for compaction");return ue(this,Ys,"f").params.messages=[{role:"user",content:l.content}],!0},Symbol.asyncIterator)](){var e;if(ue(this,$O,"f"))throw new Ut("Cannot iterate over a consumed stream");at(this,$O,!0,"f"),at(this,F0,!0,"f"),at(this,gv,void 0,"f");try{for(;;){let n;try{if(ue(this,Ys,"f").params.max_iterations&&ue(this,zB,"f")>=ue(this,Ys,"f").params.max_iterations)break;at(this,F0,!1,"f"),at(this,gv,void 0,"f"),at(this,zB,(e=ue(this,zB,"f"),e++,e),"f"),at(this,lf,void 0,"f");let{max_iterations:r,compactionControl:o,...i}=ue(this,Ys,"f").params;if(i.stream?(n=this.client.beta.messages.stream({...i},ue(this,Qu,"f")),at(this,lf,n.finalMessage(),"f"),ue(this,lf,"f").catch(()=>{}),yield n):(at(this,lf,this.client.beta.messages.create({...i,stream:!1},ue(this,Qu,"f")),"f"),yield ue(this,lf,"f")),!await ue(this,BB,"m",qGe).call(this)){if(!ue(this,F0,"f")){let{role:l,content:c}=await ue(this,lf,"f");ue(this,Ys,"f").params.messages.push({role:l,content:c})}let a=await ue(this,BB,"m",Owe).call(this,ue(this,Ys,"f").params.messages.at(-1));if(a)ue(this,Ys,"f").params.messages.push(a);else if(!ue(this,F0,"f"))break}}finally{n&&n.abort()}}if(!ue(this,lf,"f"))throw new Ut("ToolRunner concluded without a message from the server");ue(this,HC,"f").resolve(await ue(this,lf,"f"))}catch(n){throw at(this,$O,!1,"f"),ue(this,HC,"f").promise.catch(()=>{}),ue(this,HC,"f").reject(n),at(this,HC,GGe(),"f"),n}}setMessagesParams(e){typeof e=="function"?ue(this,Ys,"f").params=e(ue(this,Ys,"f").params):ue(this,Ys,"f").params=e,at(this,F0,!0,"f"),at(this,gv,void 0,"f")}setRequestOptions(e){typeof e=="function"?at(this,Qu,e(ue(this,Qu,"f")),"f"):at(this,Qu,{...ue(this,Qu,"f"),...e},"f")}async generateToolResponse(e=ue(this,Qu,"f").signal){let n=await ue(this,lf,"f")??this.params.messages.at(-1);return n?ue(this,BB,"m",Owe).call(this,n,e):null}done(){return ue(this,HC,"f").promise}async runUntilDone(){if(!ue(this,$O,"f"))for await(let e of this);return this.done()}get params(){return ue(this,Ys,"f").params}pushMessages(...e){this.setMessagesParams(n=>({...n,messages:[...n.messages,...e]}))}then(e,n){return this.runUntilDone().then(e,n)}};Owe=async function(e,n=ue(this,Qu,"f").signal){return ue(this,gv,"f")!==void 0?ue(this,gv,"f"):(at(this,gv,TBt(ue(this,Ys,"f").params,e,{...ue(this,Qu,"f"),signal:n}),"f"),ue(this,gv,"f"))}});var UO,Lwe=C(()=>{tu();_O();nwe();UO=class t{constructor(e,n){this.iterator=e,this.controller=n}async*decoder(){let e=new pv;for await(let n of this.iterator)for(let r of e.decode(n))yield JSON.parse(r);for(let n of e.flush())yield JSON.parse(n)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,n){if(!e.body)throw n.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Ut("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Ut("Attempted to iterate over a response with no body");return new t(TB(e.body),n)}}});var BO,Dwe=C(()=>{pi();Hi();ri();Lwe();RO();Ts();BO=class extends Mn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/messages/batches?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/messages/batches/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Pp,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(et`/v1/messages/batches/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},r?.headers])})}cancel(e,n={},r){let{betas:o}=n??{};return this._client.post(et`/v1/messages/batches/${e}/cancel?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"message-batches-2024-09-24"].toString()},r?.headers])})}async results(e,n={},r){let o=await this.retrieve(e);if(!o.results_url)throw new Ut(`No batch \`results_url\`; Has it finished processing? ${o.processing_status} - ${o.id}`);let{betas:i}=n??{};return this._client.get(o.results_url,{...r,headers:_e([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},r?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,a)=>UO.fromResponse(a.response,a.controller))}}});function ZGe(t){if(!t.output_format)return t;if(t.output_config?.format)throw new Ut("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:e,...n}=t;return{...n,output_config:{...t.output_config,format:e}}}var YGe,PBt,yv,$we=C(()=>{RO();pi();_we();ri();OB();Iwe();WGe();Rwe();h8();Dwe();Dwe();Rwe();h8();YGe={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"},PBt=["claude-mythos-preview","claude-opus-4-6"],yv=class extends Mn{constructor(){super(...arguments),this.batches=new BO(this._client)}create(e,n){let r=ZGe(e),{betas:o,...i}=r;i.model in YGe&&console.warn(`The model '${i.model}' is deprecated and will reach end-of-life on ${YGe[i.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),PBt.includes(i.model)&&i.thinking&&i.thinking.type==="enabled"&&console.warn(`Using Claude with ${i.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let s=this._client._options.timeout;if(!i.stream&&s==null){let l=i8[i.model]??void 0;s=this._client.calculateNonstreamingTimeout(i.max_tokens,l)}let a=o8(i.tools,i.messages);return this._client.post("/v1/messages?beta=true",{body:i,timeout:s??6e5,...n,headers:_e([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},a,n?.headers]),stream:r.stream??!1})}parse(e,n){return n={...n,headers:_e([{"anthropic-beta":[...e.betas??[],"structured-outputs-2025-12-15"].toString()},n?.headers])},this.create(e,n).then(r=>Twe(r,e,{logger:this._client.logger??console}))}stream(e,n){return m8.createMessage(this,e,n)}countTokens(e,n){let r=ZGe(e),{betas:o,...i}=r;return this._client.post("/v1/messages/count_tokens?beta=true",{body:i,...n,headers:_e([{"anthropic-beta":[...o??[],"token-counting-2024-11-01"].toString()},n?.headers])})}toolRunner(e,n){return new FO(this._client,e,n)}};yv.Batches=BO;yv.BetaToolRunner=FO;yv.ToolError=$0});var zO,Fwe=C(()=>{pi();Hi();ri();Ts();zO=class extends Mn{list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(et`/v1/sessions/${e}/events?beta=true`,io,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}send(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/sessions/${e}/events?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}stream(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/sessions/${e}/events/stream?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers]),stream:!0})}}});var jO,Uwe=C(()=>{pi();Hi();ri();Ts();jO=class extends Mn{retrieve(e,n,r){let{session_id:o,betas:i}=n;return this._client.get(et`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{session_id:o,betas:i,...s}=n;return this._client.post(et`/v1/sessions/${o}/resources/${e}?beta=true`,{body:s,...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(et`/v1/sessions/${e}/resources?beta=true`,io,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{session_id:o,betas:i}=n;return this._client.delete(et`/v1/sessions/${o}/resources/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}add(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/sessions/${e}/resources?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var KC,Bwe=C(()=>{pi();Fwe();Fwe();Uwe();Uwe();Hi();ri();Ts();KC=class extends Mn{constructor(){super(...arguments),this.events=new zO(this._client),this.resources=new jO(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/sessions?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/sessions/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/sessions/${e}?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/sessions?beta=true",io,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(et`/v1/sessions/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(et`/v1/sessions/${e}/archive?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};KC.Events=zO;KC.Resources=jO});var VO,zwe=C(()=>{pi();Hi();ri();IO();Ts();VO=class extends Mn{create(e,n={},r){let{betas:o,...i}=n??{};return this._client.post(et`/v1/skills/${e}/versions?beta=true`,TO({body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])},this._client))}retrieve(e,n,r){let{skill_id:o,betas:i}=n;return this._client.get(et`/v1/skills/${o}/versions/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(et`/v1/skills/${e}/versions?beta=true`,io,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}delete(e,n,r){let{skill_id:o,betas:i}=n;return this._client.delete(et`/v1/skills/${o}/versions/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"skills-2025-10-02"].toString()},r?.headers])})}}});var U0,jwe=C(()=>{pi();zwe();zwe();Hi();ri();IO();Ts();U0=class extends Mn{constructor(){super(...arguments),this.versions=new VO(this._client)}create(e={},n){let{betas:r,...o}=e??{};return this._client.post("/v1/skills?beta=true",TO({body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])},this._client,!1))}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/skills/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/skills?beta=true",io,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"skills-2025-10-02"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(et`/v1/skills/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"skills-2025-10-02"].toString()},r?.headers])})}};U0.Versions=VO});var WO,Vwe=C(()=>{pi();Hi();ri();Ts();WO=class extends Mn{create(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/vaults/${e}/credentials?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}retrieve(e,n,r){let{vault_id:o,betas:i}=n;return this._client.get(et`/v1/vaults/${o}/credentials/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{vault_id:o,betas:i,...s}=n;return this._client.post(et`/v1/vaults/${o}/credentials/${e}?beta=true`,{body:s,...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e,n={},r){let{betas:o,...i}=n??{};return this._client.getAPIList(et`/v1/vaults/${e}/credentials?beta=true`,io,{query:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}delete(e,n,r){let{vault_id:o,betas:i}=n;return this._client.delete(et`/v1/vaults/${o}/credentials/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n,r){let{vault_id:o,betas:i}=n;return this._client.post(et`/v1/vaults/${o}/credentials/${e}/archive?beta=true`,{...r,headers:_e([{"anthropic-beta":[...i??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}}});var B0,Wwe=C(()=>{pi();Vwe();Vwe();Hi();ri();Ts();B0=class extends Mn{constructor(){super(...arguments),this.credentials=new WO(this._client)}create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/vaults?beta=true",{body:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/vaults/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}update(e,n,r){let{betas:o,...i}=n;return this._client.post(et`/v1/vaults/${e}?beta=true`,{body:i,...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/vaults?beta=true",io,{query:o,...n,headers:_e([{"anthropic-beta":[...r??[],"managed-agents-2026-04-01"].toString()},n?.headers])})}delete(e,n={},r){let{betas:o}=n??{};return this._client.delete(et`/v1/vaults/${e}?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}archive(e,n={},r){let{betas:o}=n??{};return this._client.post(et`/v1/vaults/${e}/archive?beta=true`,{...r,headers:_e([{"anthropic-beta":[...o??[],"managed-agents-2026-04-01"].toString()},r?.headers])})}};B0.Credentials=WO});var Pl,Hwe=C(()=>{pi();pwe();pwe();hwe();hwe();gwe();gwe();ywe();ywe();vwe();vwe();Cwe();Cwe();$we();$we();Bwe();Bwe();jwe();jwe();Wwe();Wwe();Pl=class extends Mn{constructor(){super(...arguments),this.models=new AO(this._client),this.messages=new yv(this._client),this.agents=new L0(this._client),this.environments=new PO(this._client),this.sessions=new KC(this._client),this.vaults=new B0(this._client),this.memoryStores=new VC(this._client),this.files=new EO(this._client),this.skills=new U0(this._client),this.userProfiles=new kO(this._client)}};Pl.Models=AO;Pl.Messages=yv;Pl.Agents=L0;Pl.Environments=PO;Pl.Sessions=KC;Pl.Vaults=B0;Pl.MemoryStores=VC;Pl.Files=EO;Pl.Skills=U0;Pl.UserProfiles=kO});var z0,Kwe=C(()=>{pi();ri();z0=class extends Mn{create(e,n){let{betas:r,...o}=e;return this._client.post("/v1/complete",{body:o,timeout:this._client._options.timeout??6e5,...n,headers:_e([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers]),stream:e.stream??!1})}}});function JGe(t){return t?.output_config?.format}function qwe(t,e,n){let r=JGe(e);return!e||!("parse"in(r??{}))?{...t,content:t.content.map(o=>o.type==="text"?Object.defineProperty({...o},"parsed_output",{value:null,enumerable:!1}):o),parsed_output:null}:Gwe(t,e,n)}function Gwe(t,e,n){let r=null,o=t.content.map(i=>{if(i.type==="text"){let s=DBt(e,i.text);return r===null&&(r=s),Object.defineProperty({...i},"parsed_output",{value:s,enumerable:!1})}return i});return{...t,content:o,parsed_output:r}}function DBt(t,e){let n=JGe(t);if(n?.type!=="json_schema")return null;try{return"parse"in n?n.parse(e):JSON.parse(e)}catch(r){throw new Ut(`Failed to parse structured output: ${r}`)}}var Ywe=C(()=>{tu()});function t8e(t){return t.type==="tool_use"||t.type==="server_tool_use"}var Ap,qC,HO,jB,g8,VB,WB,y8,HB,wv,KB,w8,v8,j0,x8,b8,qB,Zwe,XGe,Jwe,Xwe,Qwe,eve,QGe,e8e,C8,n8e=C(()=>{dv();pO();RO();Ewe();Pwe();Ywe();e8e="__json_buf";C8=class t{constructor(e,n){Ap.add(this),this.messages=[],this.receivedMessages=[],qC.set(this,void 0),HO.set(this,null),this.controller=new AbortController,jB.set(this,void 0),g8.set(this,()=>{}),VB.set(this,()=>{}),WB.set(this,void 0),y8.set(this,()=>{}),HB.set(this,()=>{}),wv.set(this,{}),KB.set(this,!1),w8.set(this,!1),v8.set(this,!1),j0.set(this,!1),x8.set(this,void 0),b8.set(this,void 0),qB.set(this,void 0),Jwe.set(this,r=>{if(at(this,w8,!0,"f"),fv(r)&&(r=new Il),r instanceof Il)return at(this,v8,!0,"f"),this._emit("abort",r);if(r instanceof Ut)return this._emit("error",r);if(r instanceof Error){let o=new Ut(r.message);return o.cause=r,this._emit("error",o)}return this._emit("error",new Ut(String(r)))}),at(this,jB,new Promise((r,o)=>{at(this,g8,r,"f"),at(this,VB,o,"f")}),"f"),at(this,WB,new Promise((r,o)=>{at(this,y8,r,"f"),at(this,HB,o,"f")}),"f"),ue(this,jB,"f").catch(()=>{}),ue(this,WB,"f").catch(()=>{}),at(this,HO,e,"f"),at(this,qB,n?.logger??console,"f")}get response(){return ue(this,x8,"f")}get request_id(){return ue(this,b8,"f")}async withResponse(){at(this,j0,!0,"f");let e=await ue(this,jB,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let n=new t(null);return n._run(()=>n._fromReadableStream(e)),n}static createMessage(e,n,r,{logger:o}={}){let i=new t(n,{logger:o});for(let s of n.messages)i._addMessageParam(s);return at(i,HO,{...n,stream:!0},"f"),i._run(()=>i._createMessage(e,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},ue(this,Jwe,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,n=!0){this.receivedMessages.push(e),n&&this._emit("message",e)}async _createMessage(e,n,r){let o=r?.signal,i;o&&(o.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),o.addEventListener("abort",i));try{ue(this,Ap,"m",Xwe).call(this);let{response:s,data:a}=await e.create({...n,stream:!0},{...r,signal:this.controller.signal}).withResponse();this._connected(s);for await(let l of a)ue(this,Ap,"m",Qwe).call(this,l);if(a.controller.signal?.aborted)throw new Il;ue(this,Ap,"m",eve).call(this)}finally{o&&i&&o.removeEventListener("abort",i)}}_connected(e){this.ended||(at(this,x8,e,"f"),at(this,b8,e?.headers.get("request-id"),"f"),ue(this,g8,"f").call(this,e),this._emit("connect"))}get ended(){return ue(this,KB,"f")}get errored(){return ue(this,w8,"f")}get aborted(){return ue(this,v8,"f")}abort(){this.controller.abort()}on(e,n){return(ue(this,wv,"f")[e]||(ue(this,wv,"f")[e]=[])).push({listener:n}),this}off(e,n){let r=ue(this,wv,"f")[e];if(!r)return this;let o=r.findIndex(i=>i.listener===n);return o>=0&&r.splice(o,1),this}once(e,n){return(ue(this,wv,"f")[e]||(ue(this,wv,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{at(this,j0,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){at(this,j0,!0,"f"),await ue(this,WB,"f")}get currentMessage(){return ue(this,qC,"f")}async finalMessage(){return await this.done(),ue(this,Ap,"m",Zwe).call(this)}async finalText(){return await this.done(),ue(this,Ap,"m",XGe).call(this)}_emit(e,...n){if(ue(this,KB,"f"))return;e==="end"&&(at(this,KB,!0,"f"),ue(this,y8,"f").call(this));let r=ue(this,wv,"f")[e];if(r&&(ue(this,wv,"f")[e]=r.filter(o=>!o.once),r.forEach(({listener:o})=>o(...n))),e==="abort"){let o=n[0];!ue(this,j0,"f")&&!r?.length&&Promise.reject(o),ue(this,VB,"f").call(this,o),ue(this,HB,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=n[0];!ue(this,j0,"f")&&!r?.length&&Promise.reject(o),ue(this,VB,"f").call(this,o),ue(this,HB,"f").call(this,o),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",ue(this,Ap,"m",Zwe).call(this))}async _fromReadableStream(e,n){let r=n?.signal,o;r&&(r.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),r.addEventListener("abort",o));try{ue(this,Ap,"m",Xwe).call(this),this._connected(null);let i=ly.fromReadableStream(e,this.controller);for await(let s of i)ue(this,Ap,"m",Qwe).call(this,s);if(i.controller.signal?.aborted)throw new Il;ue(this,Ap,"m",eve).call(this)}finally{r&&o&&r.removeEventListener("abort",o)}}[(qC=new WeakMap,HO=new WeakMap,jB=new WeakMap,g8=new WeakMap,VB=new WeakMap,WB=new WeakMap,y8=new WeakMap,HB=new WeakMap,wv=new WeakMap,KB=new WeakMap,w8=new WeakMap,v8=new WeakMap,j0=new WeakMap,x8=new WeakMap,b8=new WeakMap,qB=new WeakMap,Jwe=new WeakMap,Ap=new WeakSet,Zwe=function(){if(this.receivedMessages.length===0)throw new Ut("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},XGe=function(){if(this.receivedMessages.length===0)throw new Ut("stream ended without producing a Message with role=assistant");let n=this.receivedMessages.at(-1).content.filter(r=>r.type==="text").map(r=>r.text);if(n.length===0)throw new Ut("stream ended without producing a content block with type=text");return n.join(" ")},Xwe=function(){this.ended||at(this,qC,void 0,"f")},Qwe=function(n){if(this.ended)return;let r=ue(this,Ap,"m",QGe).call(this,n);switch(this._emit("streamEvent",n,r),n.type){case"content_block_delta":{let o=r.content.at(-1);switch(n.delta.type){case"text_delta":{o.type==="text"&&this._emit("text",n.delta.text,o.text||"");break}case"citations_delta":{o.type==="text"&&this._emit("citation",n.delta.citation,o.citations??[]);break}case"input_json_delta":{t8e(o)&&o.input&&this._emit("inputJson",n.delta.partial_json,o.input);break}case"thinking_delta":{o.type==="thinking"&&this._emit("thinking",n.delta.thinking,o.thinking);break}case"signature_delta":{o.type==="thinking"&&this._emit("signature",o.signature);break}default:n.delta}break}case"message_stop":{this._addMessageParam(r),this._addMessage(qwe(r,ue(this,HO,"f"),{logger:ue(this,qB,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",r.content.at(-1));break}case"message_start":{at(this,qC,r,"f");break}case"content_block_start":case"message_delta":break}},eve=function(){if(this.ended)throw new Ut("stream has ended, this shouldn't happen");let n=ue(this,qC,"f");if(!n)throw new Ut("request ended without sending any chunks");return at(this,qC,void 0,"f"),qwe(n,ue(this,HO,"f"),{logger:ue(this,qB,"f")})},QGe=function(n){let r=ue(this,qC,"f");if(n.type==="message_start"){if(r)throw new Ut(`Unexpected event order, got ${n.type} before receiving "message_stop"`);return n.message}if(!r)throw new Ut(`Unexpected event order, got ${n.type} before "message_start"`);switch(n.type){case"message_stop":return r;case"message_delta":return r.stop_reason=n.delta.stop_reason,r.stop_sequence=n.delta.stop_sequence,r.usage.output_tokens=n.usage.output_tokens,n.usage.input_tokens!=null&&(r.usage.input_tokens=n.usage.input_tokens),n.usage.cache_creation_input_tokens!=null&&(r.usage.cache_creation_input_tokens=n.usage.cache_creation_input_tokens),n.usage.cache_read_input_tokens!=null&&(r.usage.cache_read_input_tokens=n.usage.cache_read_input_tokens),n.usage.server_tool_use!=null&&(r.usage.server_tool_use=n.usage.server_tool_use),r;case"content_block_start":return r.content.push({...n.content_block}),r;case"content_block_delta":{let o=r.content.at(n.index);switch(n.delta.type){case"text_delta":{o?.type==="text"&&(r.content[n.index]={...o,text:(o.text||"")+n.delta.text});break}case"citations_delta":{o?.type==="text"&&(r.content[n.index]={...o,citations:[...o.citations??[],n.delta.citation]});break}case"input_json_delta":{if(o&&t8e(o)){let i=o[e8e]||"";i+=n.delta.partial_json;let s={...o};Object.defineProperty(s,e8e,{value:i,enumerable:!1,writable:!0}),i&&(s.input=s8(i)),r.content[n.index]=s}break}case"thinking_delta":{o?.type==="thinking"&&(r.content[n.index]={...o,thinking:o.thinking+n.delta.thinking});break}case"signature_delta":{o?.type==="thinking"&&(r.content[n.index]={...o,signature:n.delta.signature});break}default:n.delta}return r}case"content_block_stop":return r}},Symbol.asyncIterator)](){let e=[],n=[],r=!1;return this.on("streamEvent",o=>{let i=n.shift();i?i.resolve(o):e.push(o)}),this.on("end",()=>{r=!0;for(let o of n)o.resolve(void 0);n.length=0}),this.on("abort",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),this.on("error",o=>{r=!0;for(let i of n)i.reject(o);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,s)=>n.push({resolve:i,reject:s})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ly(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}});var KO,tve=C(()=>{pi();Hi();ri();Lwe();RO();Ts();KO=class extends Mn{create(e,n){return this._client.post("/v1/messages/batches",{body:e,...n})}retrieve(e,n){return this._client.get(et`/v1/messages/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/v1/messages/batches",Pp,{query:e,...n})}delete(e,n){return this._client.delete(et`/v1/messages/batches/${e}`,n)}cancel(e,n){return this._client.post(et`/v1/messages/batches/${e}/cancel`,n)}async results(e,n){let r=await this.retrieve(e);if(!r.results_url)throw new Ut(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);return this._client.get(r.results_url,{...n,headers:_e([{Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,i)=>UO.fromResponse(i.response,i.controller))}}});var GC,r8e,FBt,nve=C(()=>{pi();ri();OB();n8e();Ywe();tve();tve();_we();GC=class extends Mn{constructor(){super(...arguments),this.batches=new KO(this._client)}create(e,n){e.model in r8e&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${r8e[e.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),FBt.includes(e.model)&&e.thinking&&e.thinking.type==="enabled"&&console.warn(`Using Claude with ${e.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let r=this._client._options.timeout;if(!e.stream&&r==null){let i=i8[e.model]??void 0;r=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}let o=o8(e.tools,e.messages);return this._client.post("/v1/messages",{body:e,timeout:r??6e5,...n,headers:_e([o,n?.headers]),stream:e.stream??!1})}parse(e,n){return this.create(e,n).then(r=>Gwe(r,e,{logger:this._client.logger??console}))}stream(e,n){return C8.createMessage(this,e,n,{logger:this._client.logger??console})}countTokens(e,n){return this._client.post("/v1/messages/count_tokens",{body:e,...n})}},r8e={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026","claude-3-5-haiku-latest":"February 19th, 2026","claude-3-5-haiku-20241022":"February 19th, 2026","claude-opus-4-0":"June 15th, 2026","claude-opus-4-20250514":"June 15th, 2026","claude-sonnet-4-0":"June 15th, 2026","claude-sonnet-4-20250514":"June 15th, 2026"},FBt=["claude-mythos-preview","claude-opus-4-6"];GC.Batches=KO});var V0,rve=C(()=>{pi();Hi();ri();Ts();V0=class extends Mn{retrieve(e,n={},r){let{betas:o}=n??{};return this._client.get(et`/v1/models/${e}`,{...r,headers:_e([{...o?.toString()!=null?{"anthropic-beta":o?.toString()}:void 0},r?.headers])})}list(e={},n){let{betas:r,...o}=e??{};return this._client.getAPIList("/v1/models",Pp,{query:o,...n,headers:_e([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}}});var o8e=C(()=>{RGe();Hwe();Kwe();nve();rve()});var GB,ove=C(()=>{GB=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0}});var ive,sve,_8,i8e,s8e,a8e,Ei,cy,ave=C(()=>{dv();Kye();zC();Zye();pO();Xye();_O();SGe();ewe();Jye();tu();Hi();fwe();o8e();QG();Kwe();rve();Hwe();nve();Xye();ri();ove();PB();zC();s8e="\\n\\nHuman:",a8e="\\n\\nAssistant:",Ei=class{constructor({baseURL:e=GB("ANTHROPIC_BASE_URL"),apiKey:n=GB("ANTHROPIC_API_KEY")??null,authToken:r=GB("ANTHROPIC_AUTH_TOKEN")??null,...o}={}){ive.add(this),_8.set(this,void 0);let i={apiKey:n,authToken:r,...o,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&vGe())throw new Ut(`It looks like you're running in a browser-like environment.

This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,

new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);this.baseURL=i.baseURL,this.timeout=i.timeout??sve.DEFAULT_TIMEOUT,this.logger=i.logger??console;let s="warn";this.logLevel=s,this.logLevel=rwe(i.logLevel,"ClientOptions.logLevel",this)??rwe(GB("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??s,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??bGe(),at(this,_8,_Ge,"f"),this._options=i,this.apiKey=typeof n=="string"?n:null,this.authToken=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(e.get("x-api-key")||e.get("authorization"))&&!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!n.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return _e([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return _e([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return _e([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return TGe(e)}getUserAgent(){return`${this.constructor.name}/JS ${jC}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hye()}`}makeStatusError(e,n,r,o){return Va.generate(e,n,r,o)}buildURL(e,n,r){let o=!ue(this,ive,"m",i8e).call(this)&&r||this.baseURL,i=fGe(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery(),a=Object.fromEntries(i.searchParams);return(!Yye(s)||!Yye(a))&&(n={...a,...s,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new Ut("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:n,...o})))}request(e,n=null){return new O0(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){let o=await e,i=o.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(o);let{req:s,url:a,timeout:l}=await this.buildRequest(o,{retryCount:i-n});await this.prepareRequest(s,{url:a,options:o});let c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Wa(this).debug(`[${c}] sending request`,mv({retryOfRequestLogID:r,method:o.method,url:a,options:o,headers:s.headers})),o.signal?.aborted)throw new Il;let f=new AbortController,p=await this.fetchWithTimeout(a,s,l,f).catch(SB),m=Date.now();if(p instanceof globalThis.Error){let y=`retrying, ${n} attempts remaining`;if(o.signal?.aborted)throw new Il;let w=fv(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(n)return Wa(this).info(`[${c}] connection ${w?"timed out":"failed"} - ${y}`),Wa(this).debug(`[${c}] connection ${w?"timed out":"failed"} (${y})`,mv({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),this.retryRequest(o,n,r??c);throw Wa(this).info(`[${c}] connection ${w?"timed out":"failed"} - error; no more retries left`),Wa(this).debug(`[${c}] connection ${w?"timed out":"failed"} (error; no more retries left)`,mv({retryOfRequestLogID:r,url:a,durationMs:m-d,message:p.message})),w?new mO:new BC({cause:p})}let h=[...p.headers.entries()].filter(([y])=>y==="request-id").map(([y,w])=>", "+y+": "+JSON.stringify(w)).join(""),g=`[${c}${u}${h}] ${s.method} ${a} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${m-d}ms`;if(!p.ok){let y=await this.shouldRetry(p);if(n&&y){let T=`retrying, ${n} attempts remaining`;return await CGe(p.body),Wa(this).info(`${g} - ${T}`),Wa(this).debug(`[${c}] response error (${T})`,mv({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),this.retryRequest(o,n,r??c,p.headers)}let w=y?"error; no more retries left":"error; not retryable";Wa(this).info(`${g} - ${w}`);let v=await p.text().catch(T=>SB(T).message),x=qG(v),b=x?void 0:v;throw Wa(this).debug(`[${c}] response error (${w})`,mv({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,message:b,durationMs:Date.now()-d})),this.makeStatusError(p.status,x,b,p.headers)}return Wa(this).info(g),Wa(this).debug(`[${c}] response start`,mv({retryOfRequestLogID:r,url:p.url,status:p.status,headers:p.headers,durationMs:m-d})),{response:p,options:o,controller:f,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...r})}requestAPIList(e,n){let r=this.makeRequest(n,null,void 0);return new kB(this,r,e)}async fetchWithTimeout(e,n,r,o){let{signal:i,method:s,...a}=n||{},l=this._makeAbort(o);i&&i.addEventListener("abort",l,{once:!0});let c=setTimeout(l,r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:o.signal,...u?{duplex:"half"}:{},method:"GET",...a};s&&(d.method=s.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(c)}}async shouldRetry(e){let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,o){let i,s=o?.get("retry-after-ms");if(s){let l=parseFloat(s);Number.isNaN(l)||(i=l)}let a=o?.get("retry-after");if(a&&!i){let l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(i===void 0){let l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await hGe(i),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){let i=n-e,s=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return s*a*1e3}calculateNonstreamingTimeout(e,n){if(36e5*e/128e3>6e5||n!=null&&e>n)throw new Ut("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:n=0}={}){let r={...e},{method:o,path:i,query:s,defaultBaseURL:a}=r,l=this.buildURL(i,s,a);"timeout"in r&&mGe("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:c,body:u}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:o,bodyHeaders:c,retryCount:n});return{req:{method:o,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:o}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let s=_e([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...xGe(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(s),s.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=_e([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:GG(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:ue(this,_8,"f").call(this,{body:e,headers:r})}};sve=Ei,_8=new WeakMap,ive=new WeakSet,i8e=function(){return this.baseURL!=="https://api.anthropic.com"};Ei.Anthropic=sve;Ei.HUMAN_PROMPT=s8e;Ei.AI_PROMPT=a8e;Ei.DEFAULT_TIMEOUT=6e5;Ei.AnthropicError=Ut;Ei.APIError=Va;Ei.APIConnectionError=BC;Ei.APIConnectionTimeoutError=mO;Ei.APIUserAbortError=Il;Ei.NotFoundError=wO;Ei.ConflictError=vO;Ei.RateLimitError=bO;Ei.BadRequestError=hO;Ei.AuthenticationError=gO;Ei.InternalServerError=CO;Ei.PermissionDeniedError=yO;Ei.UnprocessableEntityError=xO;Ei.toFile=n8;cy=class extends Ei{constructor(){super(...arguments),this.completions=new z0(this),this.messages=new GC(this),this.models=new V0(this),this.beta=new Pl(this)}};cy.Completions=z0;cy.Messages=GC;cy.Models=V0;cy.Beta=Pl});var l8e=C(()=>{ave();fwe();QG();ave();Hi();tu()});var c8e=C(()=>{tu();YG()});var u8e=C(()=>{zC();c8e();ove();PB();Kye();Zye();ewe()});function zBt(t){return JSON.parse(JSON.stringify(t))}function d8e(t){let e=zBt(t);return W0(e)}function W0(t){let e={},n=nu(t,"$ref");if(n!==void 0)return e.$ref=n,e;let r=nu(t,"$defs");if(r!==void 0){let u={};e.$defs=u;for(let[d,f]of Object.entries(r))u[d]=W0(f)}let o=nu(t,"type"),i=nu(t,"anyOf"),s=nu(t,"oneOf"),a=nu(t,"allOf");if(Array.isArray(i))e.anyOf=i.map(u=>W0(u));else if(Array.isArray(s))e.anyOf=s.map(u=>W0(u));else if(Array.isArray(a))e.allOf=a.map(u=>W0(u));else{if(o===void 0)throw new Error("JSON schema must have a type defined if anyOf/oneOf/allOf are not used");e.type=o}let l=nu(t,"description");l!==void 0&&(e.description=l);let c=nu(t,"title");if(c!==void 0&&(e.title=c),o==="object"){let u=nu(t,"properties")||{};e.properties=Object.fromEntries(Object.entries(u).map(([f,p])=>[f,W0(p)])),nu(t,"additionalProperties"),e.additionalProperties=!1;let d=nu(t,"required");d!==void 0&&(e.required=d)}else if(o==="string"){let u=nu(t,"format");u!==void 0&&BBt.has(u)?e.format=u:u!==void 0&&(t.format=u)}else if(o==="array"){let u=nu(t,"items");u!==void 0&&(e.items=W0(u));let d=nu(t,"minItems");d!==void 0&&(d===0||d===1)?e.minItems=d:d!==void 0&&(t.minItems=d)}if(Object.keys(t).length>0){let u=e.description;e.description=(u?u+`

`:"")+"{"+Object.entries(t).map(([d,f])=>`${d}: ${JSON.stringify(f)}`).join(", ")+"}"}return e}var BBt,f8e=C(()=>{u8e();BBt=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"])});function VBt(t){return t?Object.entries(jBt).find(([e])=>t.startsWith(e))?.[1]??p8e:p8e}function WBt(t){return!!(t.tools&&t.tools.length>0)}function HBt(t){for(let e of t.messages??[])if(typeof e.content!="string"){for(let n of e.content??[])if(typeof n=="object"&&n!=null&&n.type==="document"&&typeof n.citations=="object"&&n.citations?.enabled)return!0}return!1}function KBt(t){return!!(t.thinking&&(t.thinking.type==="enabled"||t.thinking.type==="adaptive"))}function qBt(t){return!!t.context_management?.edits?.some(e=>e.type==="compact_20260112")}function GBt(t){return"input_schema"in t}function YBt(t){return typeof t=="object"&&t!==null&&"type"in t&&("name"in t||"mcp_server_name"in t)&&typeof t.type=="string"&&["text_editor_","computer_","bash_","web_search_","web_fetch_","str_replace_editor_","str_replace_based_edit_tool_","code_execution_","memory_","tool_search_","mcp_toolset"].some(e=>typeof t.type=="string"&&t.type.startsWith(e))}function ZBt(t,e,...n){return Array.from(new Set([...t??[],...e??[],...n.flatMap(r=>Array.from(r))]))}function JBt(t){if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)&&t.content.length>=1&&"input"in t.content[0])return typeof t.content[0].input=="string"?t.content[0].input:JSON.stringify(t.content[0].input);if(Array.isArray(t.content)&&t.content.length>=1&&"text"in t.content[0]&&typeof t.content[0].text=="string")return t.content[0].text}var jBt,p8e,m8e,lve,h8e=C(()=>{Rye();zqe();jye();nGe();sGe();aGe();cGe();dGe();l8e();f8e();Kr();ac();Jo();vI();qd();Bu();Bd();pI();y2();wde();jBt={"claude-opus-4-7":16384,"claude-opus-4-6":16384,"claude-sonnet-4-6":16384,"claude-opus-4-5":16384,"claude-sonnet-4-5":16384,"claude-haiku-4-5":16384,"claude-opus-4-1":16384,"claude-sonnet-4":16384,"claude-opus-4":16384,"claude-3-7-sonnet":8192,"claude-3-5-sonnet":8192,"claude-3-5-haiku":8192,"claude-3-opus":4096,"claude-3-sonnet":4096,"claude-3-haiku":4096},p8e=4096;m8e=class extends dp{constructor(e,n){let r=typeof e=="string"?{...n??{},model:e}:e??{};super(r??{});I(this,"lc_serializable",!0);I(this,"anthropicApiKey");I(this,"apiKey");I(this,"apiUrl");I(this,"temperature");I(this,"topK");I(this,"topP");I(this,"maxTokens");I(this,"modelName","claude-sonnet-4-5-20250929");I(this,"model","claude-sonnet-4-5-20250929");I(this,"invocationKwargs");I(this,"stopSequences");I(this,"streaming",!1);I(this,"clientOptions");I(this,"thinking",{type:"disabled"});I(this,"contextManagement");I(this,"outputConfig");I(this,"inferenceGeo");I(this,"batchClient");I(this,"streamingClient");I(this,"streamUsage",!0);I(this,"betas");I(this,"createClient");if(this._addVersion("@langchain/anthropic","1.3.29"),this.anthropicApiKey=r?.apiKey??r?.anthropicApiKey??In("ANTHROPIC_API_KEY"),!this.anthropicApiKey&&!r?.createClient)throw new Error("Anthropic API key not found");this.clientOptions=r?.clientOptions??{},this.apiKey=this.anthropicApiKey,this.apiUrl=r?.anthropicApiUrl,this.modelName=r?.model??r?.modelName??this.model,this.model=this.modelName,this.invocationKwargs=r?.invocationKwargs??{},this.topP=r?.topP??this.topP,this.temperature=r?.temperature??this.temperature,this.topK=r?.topK??this.topK,this.maxTokens=r?.maxTokens??VBt(this.model),this.stopSequences=r?.stopSequences??this.stopSequences,this.streaming=r?.streaming??!1,this.streamUsage=r?.streamUsage??this.streamUsage,this.thinking=r?.thinking??this.thinking,this.contextManagement=r?.contextManagement??this.contextManagement,this.outputConfig=r?.outputConfig??this.outputConfig,this.inferenceGeo=r?.inferenceGeo??this.inferenceGeo,this.betas=r?.betas??this.betas,this.createClient=r?.createClient??(o=>new cy(o))}static lc_name(){return"ChatAnthropic"}get lc_secrets(){return{anthropicApiKey:"ANTHROPIC_API_KEY",apiKey:"ANTHROPIC_API_KEY"}}get lc_aliases(){return{modelName:"model"}}getLsParams(e){let n=this.invocationParams(e);return{ls_provider:"anthropic",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??void 0,ls_max_tokens:n.max_tokens??void 0,ls_stop:e.stop}}formatStructuredToolToAnthropic(e){if(e)return e.map(n=>{if(cp(n)&&n.extras?.providerToolDefinition)return n.extras.providerToolDefinition;if(YBt(n)||GBt(n))return n;if(Rg(n))return{name:n.function.name,description:n.function.description,input_schema:n.function.parameters};if(cp(n))return{name:n.name,description:n.description,input_schema:jr(n.schema)?Hr(n.schema):n.schema,...n.extras?Bqe.parse(n.extras):{}};throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(n,null,2)}`)})}bindTools(e,n){return this.withConfig({tools:this.formatStructuredToolToAnthropic(e),...n})}invocationParams(e){let n=Uqe(e?.tool_choice),r=e?.tools?.reduce((l,c)=>{if(typeof c=="object"&&"type"in c&&c.type in Lye){let u=Lye[c.type];if(!l.includes(u))return[...l,u]}return l},[]),o=(()=>{let l={...this.outputConfig,...e?.outputConfig};return e?.outputFormat&&!l.format&&(l.format=e.outputFormat),Object.keys(l).length>0?l:void 0})(),i=this.contextManagement?.edits?.some(l=>l.type==="compact_20260112")?["compact-2026-01-12"]:[],s=Qqe(this.model,o),a={model:this.model,stop_sequences:e?.stop??this.stopSequences,stream:this.streaming,max_tokens:this.maxTokens,tools:this.formatStructuredToolToAnthropic(e?.tools),tool_choice:n,thinking:this.thinking,context_management:this.contextManagement,...this.invocationKwargs,container:e?.container,betas:ZBt(this.betas,e?.betas,r??[],i,s),output_config:o,inference_geo:e?.inferenceGeo??this.inferenceGeo,mcp_servers:e?.mcp_servers,cache_control:e?.cache_control};return eGe({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature}),Object.assign(a,tGe({model:this.model,thinking:this.thinking,topK:this.topK,topP:this.topP,temperature:this.temperature})),a}_identifyingParams(){return{model_name:this.model,...this.invocationParams()}}identifyingParams(){return{model_name:this.model,...this.invocationParams()}}async*_streamResponseChunks(e,n,r){let o=this.invocationParams(n),i=CB(e),s={...o,...i,stream:!0},a=!WBt(s)&&!HBt(s)&&!KBt(s)&&!qBt(s),l=await this.createStreamWithRetry(s,{headers:n.headers,signal:n.signal});for await(let c of l){if(n.signal?.aborted){l.controller.abort();return}let u=this.streamUsage??n.streamUsage,d=rGe(c,{streamUsage:u,coerceContentToString:a});if(!d)continue;let{chunk:f}=d,p=JBt(f),m=new Jr({message:new Yt({content:f.content,additional_kwargs:f.additional_kwargs,tool_call_chunks:f.tool_call_chunks,usage_metadata:u?f.usage_metadata:void 0,response_metadata:f.response_metadata,id:f.id}),text:p??""});yield m,await r?.handleLLMNewToken(p??"",void 0,void 0,void 0,void 0,{chunk:m})}}async*_streamChatModelEvents(e,n,r){let o=this.invocationParams(n),i=CB(e),s={...o,...i,stream:!0},a=await this.createStreamWithRetry(s,{headers:n.headers,signal:n.signal}),l=this.streamUsage??n.streamUsage;yield*uGe(async function*(u,d){for await(let f of u){if(d?.aborted){u.controller?.abort();return}yield f}}(a,n.signal),{streamUsage:l??!0})}async _generateNonStreaming(e,n,r){let o=CB(e),{content:i,...s}=await this.completionWithRetry({...n,stream:!1,...o},r),a=oGe(i,s),{role:l,type:c,...u}=s;return{generations:a,llmOutput:u}}async _generate(e,n,r){if(n.signal?.throwIfAborted(),this.stopSequences&&n.stop)throw new Error('"stopSequence" parameter found in input and default params');let o=this.invocationParams(n);if(o.stream){let i,s=this._streamResponseChunks(e,n,r);for await(let a of s)i===void 0?i=a:i=i.concat(a);if(i===void 0)throw new Error("No chunks returned from Anthropic API.");return{generations:[{text:i.text,message:i.message}]}}else return this._generateNonStreaming(e,o,{signal:n.signal,headers:n.headers})}async createStreamWithRetry(e,n){if(!this.streamingClient){let s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.streamingClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}let{betas:r,...o}=e,i=async()=>{try{return e?.betas?.length?await this.streamingClient.beta.messages.create({...o,betas:r,...this.invocationKwargs,stream:!0},n):await this.streamingClient.messages.create({...o,...this.invocationKwargs,stream:!0},n)}catch(s){throw Wye(s)}};return this.caller.call(i)}async completionWithRetry(e,n){if(!this.batchClient){let s=this.apiUrl?{baseURL:this.apiUrl}:void 0;this.batchClient=this.createClient({dangerouslyAllowBrowser:!0,...this.clientOptions,...s,apiKey:this.apiKey,maxRetries:0})}let{betas:r,...o}=e,i=async()=>{try{return e?.betas?.length?await this.batchClient.beta.messages.create({...o,...this.invocationKwargs,betas:r},n):await this.batchClient.messages.create({...o,...this.invocationKwargs},n)}catch(s){throw Wye(s)}};return this.caller.callWithOptions({signal:n.signal??void 0},i)}_llmType(){return"anthropic"}get profile(){return lGe[this.model]??{}}withStructuredOutput(e,n){let r,o,{schema:i,name:s,includeRaw:a}={...n,schema:e},l=n?.method??"functionCalling";if(l==="jsonMode"&&(console.warn('"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".'),l="jsonSchema"),l==="jsonSchema"){o=iVe(i);let c=d8e(Hr(i));r=this.withConfig({outputVersion:"v0",outputConfig:{format:{type:"json_schema",schema:c}},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:c}})}else if(l==="functionCalling"){let c=s??"extract",u;if(jr(i)||Ob(i)){let d=Hr(i);u=[{name:c,description:d.description??"A function available to call.",input_schema:d}]}else typeof i.name=="string"&&typeof i.description=="string"&&typeof i.input_schema=="object"&&i.input_schema!=null?(u=[i],c=i.name):u=[{name:c,description:i.description??"",input_schema:i}];if(o=sVe(i,c,Fqe),this.thinking?.type==="enabled"||this.thinking?.type==="adaptive"){let d="Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called.";console.warn(d),r=this.withConfig({outputVersion:"v0",tools:u,ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:Hr(i)}});let f=p=>{if(!p.tool_calls||p.tool_calls.length===0)throw new Error(d);return p};r=r.pipe(f)}else r=this.withConfig({outputVersion:"v0",tools:u,tool_choice:{type:"tool",name:c},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:Hr(i)}})}else throw new TypeError(`Unrecognized structured output method '${l}'. Expected 'functionCalling' or 'jsonSchema'`);return h5(r,o,a,a?"StructuredOutputRunnable":"ChatAnthropicStructuredOutput")}},lve=class extends m8e{}});var g8e=C(()=>{jye()});var XBt,QBt,ezt,tzt,nzt,rzt,ozt,izt,szt,azt,lzt,czt,ih,y8e,w8e,v8e,x8e,b8e,C8e,_8e,S8e,T8e,I8e,P8e,E8e,A8e,k8e,M8e,uzt,dzt,fzt,pzt,mzt,hzt,YB=C(()=>{tv();XBt=se.object({command:se.literal("view"),path:se.string()}),QBt=se.object({command:se.literal("create"),path:se.string(),file_text:se.string()}),ezt=se.object({command:se.literal("str_replace"),path:se.string(),old_str:se.string(),new_str:se.string()}),tzt=se.object({command:se.literal("insert"),path:se.string(),insert_line:se.number(),insert_text:se.string()}),nzt=se.object({command:se.literal("delete"),path:se.string()}),rzt=se.object({command:se.literal("rename"),old_path:se.string(),new_path:se.string()}),ozt=se.discriminatedUnion("command",[XBt,QBt,ezt,tzt,nzt,rzt]),izt=se.object({command:se.literal("view"),path:se.string(),view_range:se.tuple([se.number(),se.number()]).optional()}),szt=se.object({command:se.literal("str_replace"),path:se.string(),old_str:se.string(),new_str:se.string()}),azt=se.object({command:se.literal("create"),path:se.string(),file_text:se.string()}),lzt=se.object({command:se.literal("insert"),path:se.string(),insert_line:se.number(),new_str:se.string()}),czt=se.discriminatedUnion("command",[izt,szt,azt,lzt]),ih=se.tuple([se.number(),se.number()]),y8e=se.object({action:se.literal("screenshot")}),w8e=se.object({action:se.literal("left_click"),coordinate:ih}),v8e=se.object({action:se.literal("right_click"),coordinate:ih}),x8e=se.object({action:se.literal("middle_click"),coordinate:ih}),b8e=se.object({action:se.literal("double_click"),coordinate:ih}),C8e=se.object({action:se.literal("triple_click"),coordinate:ih}),_8e=se.object({action:se.literal("left_click_drag"),start_coordinate:ih,end_coordinate:ih}),S8e=se.object({action:se.literal("left_mouse_down"),coordinate:ih}),T8e=se.object({action:se.literal("left_mouse_up"),coordinate:ih}),I8e=se.object({action:se.literal("scroll"),coordinate:ih,scroll_direction:se.enum(["up","down","left","right"]),scroll_amount:se.number()}),P8e=se.object({action:se.literal("type"),text:se.string()}),E8e=se.object({action:se.literal("key"),key:se.string()}),A8e=se.object({action:se.literal("mouse_move"),coordinate:ih}),k8e=se.object({action:se.literal("hold_key"),key:se.string()}),M8e=se.object({action:se.literal("wait"),duration:se.number().optional()}),uzt=se.object({action:se.literal("zoom"),region:se.tuple([se.number(),se.number(),se.number(),se.number()])}),dzt=se.discriminatedUnion("action",[y8e,w8e,v8e,x8e,b8e,C8e,_8e,S8e,T8e,I8e,P8e,E8e,A8e,k8e,M8e]),fzt=se.discriminatedUnion("action",[y8e,w8e,v8e,x8e,b8e,C8e,_8e,S8e,T8e,I8e,P8e,E8e,A8e,k8e,M8e,uzt]),pzt=se.object({command:se.string().describe("The bash command to run")}),mzt=se.object({restart:se.literal(!0).describe("Set to true to restart the bash session")}),hzt=se.union([pzt,mzt])});var N8e=C(()=>{YB();gp()});var O8e=C(()=>{});var R8e=C(()=>{});var L8e=C(()=>{});var D8e=C(()=>{YB();gp()});var $8e=C(()=>{YB();gp()});var F8e=C(()=>{});var U8e=C(()=>{YB();gp()});var B8e=C(()=>{});var z8e=C(()=>{N8e();O8e();R8e();L8e();D8e();$8e();F8e();U8e();B8e()});var j8e=C(()=>{h8e();g8e();z8e()});var cve,V8e=C(()=>{Jo();Yg();cve=class extends qg{constructor(e){let n=e?.apiKey||In("DEEPSEEK_API_KEY");if(!n)throw new Error('Deepseek API key not found. Please set the DEEPSEEK_API_KEY environment variable or pass the key into "apiKey" field.');super({...e,apiKey:n,configuration:{baseURL:"https://api.deepseek.com",...e?.configuration}});I(this,"lc_serializable",!0);I(this,"lc_namespace",["langchain","chat_models","deepseek"])}static lc_name(){return"ChatDeepSeek"}_llmType(){return"deepseek"}get lc_secrets(){return{apiKey:"DEEPSEEK_API_KEY"}}_convertCompletionsDeltaToBaseMessageChunk(e,n,r){let o=super._convertCompletionsDeltaToBaseMessageChunk(e,n,r);return o.additional_kwargs.reasoning_content=e.reasoning_content,o}_convertCompletionsMessageToBaseMessage(e,n){let r=super._convertCompletionsMessageToBaseMessage(e,n);return r.additional_kwargs.reasoning_content=e.reasoning_content,r}withStructuredOutput(e,n){let r={...n};return r?.method===void 0&&(r.method="functionCalling"),super.withStructuredOutput(e,r)}}});var W8e=C(()=>{V8e()});var H0,H8e=C(()=>{H0="0.19.0"});function q8e(t,e={auto:!1}){if(K8e)throw new Error(`you must \`import 'groq-sdk/shims/${t.kind}'\` before importing anything else from groq-sdk`);if(K0)throw new Error(`can't \`import 'groq-sdk/shims/${t.kind}'\` after \`import 'groq-sdk/shims/${K0}'\``);K8e=e.auto,K0=t.kind,uve=t.fetch,gzt=t.Request,yzt=t.Response,wzt=t.Headers,dve=t.FormData,vzt=t.Blob,S8=t.File,fve=t.ReadableStream,pve=t.getMultipartRequestOptions,mve=t.getDefaultAgent,T8=t.fileFromPath,hve=t.isFsReadStream}var K8e,K0,uve,gzt,yzt,wzt,dve,vzt,S8,fve,pve,mve,T8,hve,gve=C(()=>{K8e=!1});var I8,G8e=C(()=>{I8=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}});function Y8e({manuallyImported:t}={}){let e=t?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'groq-sdk'`:\n- `import 'groq-sdk/shims/node'` (if you're running on Node)\n- `import 'groq-sdk/shims/web'` (otherwise)\n",n,r,o,i;try{n=fetch,r=Request,o=Response,i=Headers}catch(s){throw new Error(`this environment is missing the following Web Fetch API type: ${s.message}. ${e}`)}return{kind:"web",fetch:n,Request:r,Response:o,Headers:i,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(s,a)=>({...a,body:new I8(s)}),getDefaultAgent:s=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/groq/groq-typescript#file-uploads")},isFsReadStream:s=>!1}}var Z8e=C(()=>{G8e()});var J8e=C(()=>{Z8e()});var yve,ZB=C(()=>{gve();J8e();gve();yve=()=>{K0||q8e(Y8e(),{auto:!0})};yve()});var El,Ha,q0,YC,qO,JB,XB,QB,ez,tz,nz,rz,oz,iz=C(()=>{GO();El=class extends Error{},Ha=class t extends El{constructor(e,n,r,o){super(`${t.makeMessage(e,n,r)}`),this.status=e,this.headers=o,this.error=n}static makeMessage(e,n,r){let o=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,n,r,o){if(!e||!o)return new YC({message:r,cause:P8(n)});let i=n;return e===400?new JB(e,i,r,o):e===401?new XB(e,i,r,o):e===403?new QB(e,i,r,o):e===404?new ez(e,i,r,o):e===409?new tz(e,i,r,o):e===422?new nz(e,i,r,o):e===429?new rz(e,i,r,o):e>=500?new oz(e,i,r,o):new t(e,i,r,o)}},q0=class extends Ha{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},YC=class extends Ha{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},qO=class extends YC{constructor({message:e}={}){super({message:e??"Request timed out."})}},JB=class extends Ha{},XB=class extends Ha{},QB=class extends Ha{},ez=class extends Ha{},tz=class extends Ha{},nz=class extends Ha{},rz=class extends Ha{},oz=class extends Ha{}});function _zt(t,e){let n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}function X8e(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){let n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var E8,wve,YO,Q8e=C(()=>{ZB();iz();iz();E8=class t{constructor(e,n){this.iterator=e,this.controller=n}static fromSSEResponse(e,n){let r=!1,o=new wve;async function*i(){if(!e.body)throw n.abort(),new El("Attempted to iterate over a response with no body");let a=new YO,l=X8e(e.body);for await(let c of l)for(let u of a.decode(c)){let d=o.decode(u);d&&(yield d)}for(let c of a.flush()){let u=o.decode(c);u&&(yield u)}}async function*s(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(let l of i())if(!a){if(l.data.startsWith("[DONE]")){a=!0;continue}if(l.event===null||l.event==="error"){let c;try{c=JSON.parse(l.data)}catch(u){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),u}if(c&&c.error)throw new Ha(c.error.status_code,c.error,c.error.message,void 0);yield c}}a=!0}catch(l){if(l instanceof Error&&l.name==="AbortError")return;throw l}finally{a||n.abort()}}return new t(s,n)}static fromReadableStream(e,n){let r=!1;async function*o(){let s=new YO,a=X8e(e);for await(let l of a)for(let c of s.decode(l))yield c;for(let l of s.flush())yield l}async function*i(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let s=!1;try{for await(let a of o())s||a&&(yield JSON.parse(a));s=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{s||n.abort()}}return new t(i,n)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],n=[],r=this.iterator(),o=i=>({next:()=>{if(i.length===0){let s=r.next();e.push(s),n.push(s)}return i.shift()}});return[new t(()=>o(e),this.controller),new t(()=>o(n),this.controller)]}toReadableStream(){let e=this,n,r=new TextEncoder;return new fve({async start(){n=e[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:s}=await n.next();if(s)return o.close();let a=r.encode(JSON.stringify(i)+`
`);o.enqueue(a)}catch(i){o.error(i)}},async cancel(){await n.return?.()}})}},wve=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,o]=_zt(e,":");return o.startsWith(" ")&&(o=o.substring(1)),n==="event"?this.event=o:n==="data"&&this.data.push(o),null}},YO=class t{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let n=this.decodeText(e);if(this.trailingCR&&(n="\r"+n,this.trailingCR=!1),n.endsWith("\r")&&(this.trailingCR=!0,n=n.slice(0,-1)),!n)return[];let r=t.NEWLINE_CHARS.has(n[n.length-1]||""),o=n.split(t.NEWLINE_REGEXP);return o.length===1&&!r?(this.buffer.push(o[0]),[]):(this.buffer.length>0&&(o=[this.buffer.join("")+o[0],...o.slice(1)],this.buffer=[]),r||(this.buffer=[o.pop()||""]),o)}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new El(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new El(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new El("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}};YO.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","\x85","\u2028","\u2029"]);YO.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g});async function bve(t,e,n){if(t=await t,t9e(t))return t;if(e9e(t)){let o=await t.blob();e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file");let i=sz(o)?[await o.arrayBuffer()]:[o];return new S8(i,e,n)}let r=await Tzt(t);if(e||(e=Pzt(t)??"unknown_file"),!n?.type){let o=r[0]?.type;typeof o=="string"&&(n={...n,type:o})}return new S8(r,e,n)}async function Tzt(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(sz(t))e.push(await t.arrayBuffer());else if(Ezt(t))for await(let n of t)e.push(n);else throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${Izt(t)}`);return e}function Izt(t){return`[${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}function Pzt(t){return vve(t.name)||vve(t.filename)||vve(t.path)?.split(/[\\/]/).pop()}var e9e,t9e,sz,Szt,vve,Ezt,Cve,G0,n9e,xve,A8=C(()=>{ZB();ZB();e9e=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function",t9e=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&sz(t),sz=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",Szt=t=>t9e(t)||e9e(t)||hve(t);vve=t=>{if(typeof t=="string")return t;if(typeof Buffer<"u"&&t instanceof Buffer)return String(t)},Ezt=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",Cve=t=>t&&typeof t=="object"&&t.body&&t[Symbol.toStringTag]==="MultipartBody",G0=async t=>{let e=await n9e(t.body);return pve(e,t)},n9e=async t=>{let e=new dve;return await Promise.all(Object.entries(t||{}).map(([n,r])=>xve(e,n,r))),e},xve=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(Szt(n)){let r=await bve(n);t.append(e,r)}else if(Array.isArray(n))await Promise.all(n.map(r=>xve(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,o])=>xve(t,`${e}[${r}]`,o)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}});async function l9e(t){let{response:e}=t;if(t.options.stream)return ZO("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):E8.fromSSEResponse(e,t.controller);if(e.status===204)return null;if(t.options.__binaryResponse)return e;let r=e.headers.get("content-type")?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){let s=await e.json();return ZO("response",e.status,e.url,e.headers,s),s}let i=await e.text();return ZO("response",e.status,e.url,e.headers,i),i}function Rzt(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:n}of t){let r=n.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}function Bzt(t){if(!t)return!0;for(let e in t)return!1;return!0}function zzt(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function a9e(t,e){for(let n in e){if(!zzt(e,n))continue;let r=n.toLowerCase();if(!r)continue;let o=e[n];o===null?delete t[r]:o!==void 0&&(t[r]=o)}}function ZO(t,...e){typeof process<"u"&&process?.env?.DEBUG==="true"&&console.log(`Groq:DEBUG:${t}`,...e)}var kzt,Mzt,k8,N8,O8,r9e,Sve,Nzt,Ozt,o9e,i9e,s9e,Lzt,Dzt,$zt,Fzt,Uzt,_ve,P8,Tve,jzt,c9e,Vzt,M8,GO=C(()=>{H8e();Q8e();iz();ZB();A8();A8();kzt=function(t,e,n,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!o:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(t,n):o?o.value=n:e.set(t,n),n},Mzt=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)};yve();N8=class t extends Promise{constructor(e,n=l9e){super(r=>{r(null)}),this.responsePromise=e,this.parseResponse=n}_thenUnwrap(e){return new t(this.responsePromise,async n=>e(await this.parseResponse(n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},O8=class{constructor({baseURL:e,maxRetries:n=2,timeout:r=6e4,httpAgent:o,fetch:i}){this.baseURL=e,this.maxRetries=_ve("maxRetries",n),this.timeout=_ve("timeout",r),this.httpAgent=o,this.fetch=i??uve}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Lzt(),...this.authHeaders(e)}}validateHeaders(e,n){}defaultIdempotencyKey(){return`stainless-node-retry-${jzt()}`}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(async o=>{let i=o&&sz(o?.body)?new DataView(await o.body.arrayBuffer()):o?.body instanceof DataView?o.body:o?.body instanceof ArrayBuffer?new DataView(o.body):o&&ArrayBuffer.isView(o?.body)?new DataView(o.body.buffer):o?.body;return{method:e,path:n,...o,body:i}}))}getAPIList(e,n,r){return this.requestAPIList(n,{method:"get",path:e,...r})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:n=0}={}){e={...e};let{method:r,path:o,query:i,headers:s={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:Cve(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,l=this.calculateContentLength(a),c=this.buildURL(o,i);"timeout"in e&&_ve("timeout",e.timeout),e.timeout=e.timeout??this.timeout;let u=e.httpAgent??this.httpAgent??mve(c),d=e.timeout+1e3;typeof u?.options?.timeout=="number"&&d>(u.options.timeout??0)&&(u.options.timeout=d),this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let f=this.buildHeaders({options:e,headers:s,contentLength:l,retryCount:n});return{req:{method:r,...a&&{body:a},headers:f,...u&&{agent:u},signal:e.signal??null},url:c,timeout:e.timeout}}buildHeaders({options:e,headers:n,contentLength:r,retryCount:o}){let i={};r&&(i["content-length"]=r);let s=this.defaultHeaders(e);return a9e(i,s),a9e(i,n),Cve(e.body)&&K0!=="node"&&delete i["content-type"],M8(s,"x-stainless-retry-count")===void 0&&M8(n,"x-stainless-retry-count")===void 0&&(i["x-stainless-retry-count"]=String(o)),M8(s,"x-stainless-timeout")===void 0&&M8(n,"x-stainless-timeout")===void 0&&e.timeout&&(i["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(i,n),i}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(n=>[...n])):{...e}:{}}makeStatusError(e,n,r,o){return Ha.generate(e,n,r,o)}request(e,n=null){return new N8(this.makeRequest(e,n))}async makeRequest(e,n){let r=await e,o=r.maxRetries??this.maxRetries;n==null&&(n=o),await this.prepareOptions(r);let{req:i,url:s,timeout:a}=this.buildRequest(r,{retryCount:o-n});if(await this.prepareRequest(i,{url:s,options:r}),ZO("request",s,r,i.headers),r.signal?.aborted)throw new q0;let l=new AbortController,c=await this.fetchWithTimeout(s,i,a,l).catch(P8);if(c instanceof Error){if(r.signal?.aborted)throw new q0;if(n)return this.retryRequest(r,n);throw c.name==="AbortError"?new qO:new YC({cause:c})}let u=Nzt(c.headers);if(!c.ok){if(n&&this.shouldRetry(c)){let g=`retrying, ${n} attempts remaining`;return ZO(`response (error; ${g})`,c.status,s,u),this.retryRequest(r,n,u)}let d=await c.text().catch(g=>P8(g).message),f=Dzt(d),p=f?void 0:d;throw ZO(`response (error; ${n?"(error; no more retries left)":"(error; not retryable)"})`,c.status,s,u,p),this.makeStatusError(c.status,f,p,u)}return{response:c,options:r,controller:l}}requestAPIList(e,n){let r=this.makeRequest(n,null);return new Sve(this,r,e)}buildURL(e,n){let r=Fzt(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return Bzt(o)||(n={...o,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(r.search=this.stringifyQuery(n)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([n,r])=>typeof r<"u").map(([n,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(n)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(n)}=`;throw new El(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,n,r,o){let{signal:i,...s}=n||{};i&&i.addEventListener("abort",()=>o.abort());let a=setTimeout(()=>o.abort(),r),l={signal:o.signal,...s};return l.method&&(l.method=l.method.toUpperCase()),this.fetch.call(void 0,e,l).finally(()=>{clearTimeout(a)})}shouldRetry(e){let n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r){let o,i=r?.["retry-after-ms"];if(i){let a=parseFloat(i);Number.isNaN(a)||(o=a)}let s=r?.["retry-after"];if(s&&!o){let a=parseFloat(s);Number.isNaN(a)?o=Date.parse(s)-Date.now():o=a*1e3}if(!(o&&0<=o&&o<60*1e3)){let a=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(n,a)}return await Uzt(o),this.makeRequest(e,n-1)}calculateDefaultRetryTimeoutMillis(e,n){let i=n-e,s=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return s*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${H0}`}},r9e=class{constructor(e,n,r,o){k8.set(this,void 0),kzt(this,k8,e,"f"),this.options=o,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new El("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let n={...this.options};if("params"in e&&typeof n.query=="object")n.query={...n.query,...e.params};else if("url"in e){let r=[...Object.entries(n.query||{}),...e.url.searchParams.entries()];for(let[o,i]of r)e.url.searchParams.set(o,i);n.query=void 0,n.path=e.url.toString()}return await Mzt(this,k8,"f").requestAPIList(this.constructor,n)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(k8=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let n of e.getPaginatedItems())yield n}},Sve=class extends N8{constructor(e,n,r){super(n,async o=>new r(e,o.response,await l9e(o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let n of e)yield n}},Nzt=t=>new Proxy(Object.fromEntries(t.entries()),{get(e,n){let r=n.toString();return e[r.toLowerCase()]||e[r]}}),Ozt=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":H0,"X-Stainless-OS":i9e(Deno.build.os),"X-Stainless-Arch":o9e(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":H0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":H0,"X-Stainless-OS":i9e(process.platform),"X-Stainless-Arch":o9e(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let t=Rzt();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":H0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":H0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};o9e=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",i9e=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),Lzt=()=>s9e??(s9e=Ozt()),Dzt=t=>{try{return JSON.parse(t)}catch{return}},$zt=/^[a-z][a-z0-9+.-]*:/i,Fzt=t=>$zt.test(t),Uzt=t=>new Promise(e=>setTimeout(e,t)),_ve=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new El(`${t} must be an integer`);if(e<0)throw new El(`${t} must be a positive integer`);return e},P8=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null)try{return new Error(JSON.stringify(t))}catch{}return new Error(t)},Tve=t=>{if(typeof process<"u")return process.env?.[t]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(t)?.trim()};jzt=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)}),c9e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Vzt=t=>typeof t?.get=="function",M8=(t,e)=>{let n=e.toLowerCase();if(Vzt(t)){let r=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(o,i,s)=>i+s.toUpperCase());for(let o of[e,n,e.toUpperCase(),r]){let i=t.get(o);if(i)return i}}for(let[r,o]of Object.entries(t))if(r.toLowerCase()===n)return Array.isArray(o)?(o.length<=1||console.warn(`Received ${o.length} entries for the ${e} header, using the first entry.`),o[0]):o}});var u9e=C(()=>{});var mi,kp=C(()=>{mi=class{constructor(e){this._client=e}}});var JO,Ive=C(()=>{kp();JO=class extends mi{create(e,n){return this._client.post("/openai/v1/audio/speech",{body:e,...n,headers:{Accept:"application/octet-stream",...n?.headers},__binaryResponse:!0})}}});var XO,Pve=C(()=>{kp();GO();XO=class extends mi{create(e,n){return this._client.post("/openai/v1/audio/transcriptions",G0({body:e,...n}))}}});var QO,Eve=C(()=>{kp();GO();QO=class extends mi{create(e,n){return this._client.post("/openai/v1/audio/translations",G0({body:e,...n}))}}});var uy,Ave=C(()=>{kp();Ive();Ive();Pve();Pve();Eve();Eve();uy=class extends mi{constructor(){super(...arguments),this.speech=new JO(this._client),this.transcriptions=new XO(this._client),this.translations=new QO(this._client)}};uy.Speech=JO;uy.Transcriptions=XO;uy.Translations=QO});var Y0,kve=C(()=>{kp();Y0=class extends mi{create(e,n){return this._client.post("/openai/v1/batches",{body:e,...n})}retrieve(e,n){return this._client.get(`/openai/v1/batches/${e}`,n)}list(e){return this._client.get("/openai/v1/batches",e)}cancel(e,n){return this._client.post(`/openai/v1/batches/${e}/cancel`,n)}}});var eR,Mve=C(()=>{kp();eR=class extends mi{create(e,n){return this._client.post("/openai/v1/chat/completions",{body:e,...n,stream:e.stream??!1})}}});var ZC,Nve=C(()=>{kp();Mve();Mve();ZC=class extends mi{constructor(){super(...arguments),this.completions=new eR(this._client)}};ZC.Completions=eR});var Z0,Ove=C(()=>{kp();Z0=class extends mi{}});var J0,Rve=C(()=>{kp();J0=class extends mi{create(e,n){return this._client.post("/openai/v1/embeddings",{body:e,...n})}}});var X0,Lve=C(()=>{kp();GO();X0=class extends mi{create(e,n){return this._client.post("/openai/v1/files",G0({body:e,...n}))}list(e){return this._client.get("/openai/v1/files",e)}delete(e,n){return this._client.delete(`/openai/v1/files/${e}`,n)}content(e,n){return this._client.get(`/openai/v1/files/${e}/content`,n)}info(e,n){return this._client.get(`/openai/v1/files/${e}`,n)}}});var Q0,Dve=C(()=>{kp();Q0=class extends mi{retrieve(e,n){return this._client.get(`/openai/v1/models/${e}`,n)}list(e){return this._client.get("/openai/v1/models",e)}delete(e,n){return this._client.delete(`/openai/v1/models/${e}`,n)}}});var d9e=C(()=>{u9e();Ave();kve();Nve();Ove();Rve();Lve();Dve()});var f9e,wo,p9e,m9e=C(()=>{GO();iz();A8();d9e();kve();Ove();Rve();Lve();Dve();Ave();Nve();wo=class extends O8{constructor({baseURL:e=Tve("GROQ_BASE_URL"),apiKey:n=Tve("GROQ_API_KEY"),...r}={}){if(n===void 0)throw new El("The GROQ_API_KEY environment variable is missing or empty; either provide it, or instantiate the Groq client with an apiKey option, like new Groq({ apiKey: 'My API Key' }).");let o={apiKey:n,...r,baseURL:e||"https://api.groq.com"};if(!o.dangerouslyAllowBrowser&&c9e())throw new El(`It looks like you're running in a browser-like environment.

This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,

new Groq({ apiKey, dangerouslyAllowBrowser: true })`);super({baseURL:o.baseURL,timeout:o.timeout??6e4,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new Z0(this),this.chat=new ZC(this),this.embeddings=new J0(this),this.audio=new uy(this),this.models=new Q0(this),this.batches=new Y0(this),this.files=new X0(this),this._options=o,this.apiKey=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}};f9e=wo;wo.Groq=f9e;wo.DEFAULT_TIMEOUT=6e4;wo.GroqError=El;wo.APIError=Ha;wo.APIConnectionError=YC;wo.APIConnectionTimeoutError=qO;wo.APIUserAbortError=q0;wo.NotFoundError=ez;wo.ConflictError=tz;wo.RateLimitError=rz;wo.BadRequestError=JB;wo.AuthenticationError=XB;wo.InternalServerError=oz;wo.PermissionDeniedError=QB;wo.UnprocessableEntityError=nz;wo.toFile=bve;wo.fileFromPath=T8;wo.Completions=Z0;wo.Chat=ZC;wo.Embeddings=J0;wo.Audio=uy;wo.Models=Q0;wo.Batches=Y0;wo.Files=X0;p9e=wo});function Xzt(t){if(t.role!=="system"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function")throw new Error(`Unsupported message role: ${t.role}. Expected "system", "assistant", "user", or "function"`);return t.role}function g9e(t){switch(t.type){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!rc.isInstance(t))throw new Error("Invalid generic chat message");return Xzt(t);default:throw new Error(`Unknown message type: ${t.type}`)}}function h9e(t){return t.map(e=>{let n={role:g9e(e),content:e.content,name:e.name,function_call:e.additional_kwargs.function_call,tool_calls:e.additional_kwargs.tool_calls,tool_call_id:e.tool_call_id};return rp(e)&&e.tool_calls?.length?n.tool_calls=e.tool_calls.map(cU):(e.additional_kwargs.tool_calls!=null&&(n.tool_calls=e.additional_kwargs.tool_calls),e.tool_call_id!=null&&(n.tool_call_id=e.tool_call_id)),n})}function Qzt(t,e,n){let r=t.tool_calls;switch(t.role){case"assistant":{let o=[],i=[];for(let s of r??[])try{o.push(Xb(s,{returnId:!0}))}catch(a){i.push(Bw(s,a.message))}return new kn({content:t.content||"",additional_kwargs:{tool_calls:r},tool_calls:o,invalid_tool_calls:i,usage_metadata:e,response_metadata:n})}default:return new rc(t.content||"",t.role??"unknown")}}function ejt(t,e,n,r){let o=t.role??e,i=t.content??"",s;t.function_call?s={function_call:t.function_call}:t.tool_calls?s={tool_calls:t.tool_calls}:s={},t.audio&&(s.audio={...t.audio,index:n.choices[0].index});let a,l=r,c,u=n.x_groq;u?.usage&&(a={input_tokens:u.usage.prompt_tokens,output_tokens:u.usage.completion_tokens,total_tokens:u.usage.total_tokens},c={completion_time:u.usage.completion_time,prompt_time:u.usage.prompt_time,queue_time:u.usage.queue_time,total_time:u.usage.total_time}),u?.id&&(l=u.id);let d={usage:a,timing:c};if(o==="user")return new Ub({content:i,response_metadata:d});if(o==="assistant"){let f=[];if(Array.isArray(t.tool_calls))for(let p of t.tool_calls)f.push({name:p.function?.name,args:p.function?.arguments,id:p.id,index:p.index,type:"tool_call_chunk"});return new Yt({content:i,tool_call_chunks:f,additional_kwargs:s,id:l,response_metadata:d})}else return o==="system"?new Sg({content:i,response_metadata:d}):o==="developer"?new Sg({content:i,response_metadata:d,additional_kwargs:{__openai_role__:"developer"}}):o==="function"?new Fb({content:i,additional_kwargs:s,name:t.name,response_metadata:d}):o==="tool"?new Bk({content:i,additional_kwargs:s,tool_call_id:t.tool_call_id,response_metadata:d}):new $b({content:i,role:o,response_metadata:d})}function tjt(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}var Yzt,Zzt,Jzt,$ve,y9e=C(()=>{Bu();vI();Kr();ac();Jo();Bd();m9e();jm();Uw();fM();pI();Yzt=["frequency_penalty","function_call","functions","logit_bias","logprobs","max_completion_tokens","max_tokens","n","parallel_tool_calls","presence_penalty","reasoning_format","response_format","seed","service_tier","stop","temperature","tool_choice","top_logprobs","top_p"],Zzt=["headers","promptIndex","stream_options","tools"],Jzt=[...Yzt,...Zzt];$ve=class extends dp{constructor(e){super(e);I(this,"lc_namespace",["langchain","chat_models","groq"]);I(this,"client");I(this,"model");I(this,"temperature",.7);I(this,"stop");I(this,"stopSequences");I(this,"maxTokens");I(this,"streaming",!1);I(this,"apiKey");I(this,"streamUsage",!0);I(this,"topP");I(this,"frequencyPenalty");I(this,"presencePenalty");I(this,"logprobs");I(this,"n");I(this,"logitBias");I(this,"user");I(this,"reasoningFormat");I(this,"serviceTier");I(this,"topLogprobs");I(this,"lc_serializable",!0);let n=e.apiKey||In("GROQ_API_KEY");if(!n)throw new Error('Groq API key not found. Please set the GROQ_API_KEY environment variable or provide the key into "apiKey"');let r={"User-Agent":"langchainjs",...e.defaultHeaders??{}};this.client=new p9e({apiKey:n,dangerouslyAllowBrowser:!0,baseURL:e.baseUrl,timeout:e.timeout,httpAgent:e.httpAgent,fetch:e.fetch,maxRetries:0,defaultHeaders:r,defaultQuery:e.defaultQuery}),this.apiKey=n,this.temperature=e.temperature??this.temperature,this.model=e.model,this.streaming=e.streaming??this.streaming,this.stop=e.stopSequences??(typeof e.stop=="string"?[e.stop]:e.stop)??[],this.stopSequences=this.stop,this.maxTokens=e.maxTokens,this.topP=e.topP,this.frequencyPenalty=e.frequencyPenalty,this.presencePenalty=e.presencePenalty,this.logprobs=e.logprobs,this.n=e.n,this.logitBias=e.logitBias,this.user=e.user}get lc_serialized_keys(){return["client","model","temperature","stop","stopSequences","maxTokens","streaming","apiKey","streamUsage","topP","frequencyPenalty","presencePenalty","logprobs","n","logitBias","user","reasoningFormat","serviceTier","topLogprobs"]}static lc_name(){return"ChatGroq"}_llmType(){return"groq"}get lc_secrets(){return{apiKey:"GROQ_API_KEY"}}get callKeys(){return[...super.callKeys,...Jzt]}getLsParams(e){let n=this.invocationParams(e);return{ls_provider:"groq",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??this.temperature,ls_max_tokens:n.max_tokens??this.maxTokens,ls_stop:e.stop}}async completionWithRetry(e,n){return this.caller.call(async()=>this.client.chat.completions.create(e,n))}invocationParams(e,n){let r=super.invocationParams(e),o={};e?.stream_options!==void 0?o={stream_options:e.stream_options}:(this.streamUsage&&this.streaming||n?.streaming)&&(o={stream_options:{include_usage:!0}});let i={model:this.model,frequency_penalty:this.frequencyPenalty,function_call:e?.function_call,functions:e?.functions,logit_bias:this.logitBias,logprobs:this.logprobs,n:this.n,parallel_tool_calls:e?.parallel_tool_calls,presence_penalty:this.presencePenalty,reasoning_format:this.reasoningFormat,response_format:e?.response_format,seed:e?.seed,service_tier:this.serviceTier,stop:e?.stop??this.stopSequences,temperature:e?.temperature??this.temperature,tool_choice:tjt(e?.tool_choice),tools:e?.tools?.length?e.tools.map(s=>Gb(s)):void 0,top_logprobs:this.topLogprobs,top_p:this.topP,user:this.user,stream:this.streaming,...r,...o};return i.max_completion_tokens=e?.max_completion_tokens??e?.max_tokens??this.maxTokens,i.max_completion_tokens===-1&&delete i.max_completion_tokens,i}bindTools(e,n){return this.withConfig({tools:e.map(r=>Gb(r)),...n})}async*_streamResponseChunks(e,n,r){let o=this.invocationParams(n,{streaming:!0}),i=h9e(e),s=await this.completionWithRetry({...o,messages:i,stream:!0},{signal:n?.signal,headers:n?.headers}),a,l,c;for await(let u of s){c=u;let d=u?.choices[0];if(!d)continue;d.delta?.role&&(a=d.delta.role);let f=ejt(d.delta,a,u,l),p={prompt:n.promptIndex??0,completion:d.index??0};if(typeof f.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let m={...p};d.finish_reason!=null&&(m.finish_reason=d.finish_reason,m.system_fingerprint=u.system_fingerprint,m.model_name=u.model);let h=new Jr({message:f,text:f.content,generationInfo:m});yield h,await r?.handleLLMNewToken(h.text??"",p,void 0,void 0,void 0,{chunk:h})}if(c&&("choices"in c&&delete c.choices,yield new Jr({message:new Yt({content:"",response_metadata:c}),text:""})),n.signal?.aborted)throw new Error("AbortError")}async _generate(e,n,r){if(this.streaming){let o={},i=this._streamResponseChunks(e,n,r),s={};for await(let l of i){let c=l.generationInfo?.completion??0;s[c]===void 0?s[c]=l:s[c]=s[c].concat(l)}return{generations:Object.entries(s).sort(([l],[c])=>parseInt(l,10)-parseInt(c,10)).map(([l,c])=>c),llmOutput:{estimatedTokenUsage:o}}}else return this._generateNonStreaming(e,n,r)}async _generateNonStreaming(e,n,r){let o={},i=this.invocationParams(n),s=h9e(e),a=await this.completionWithRetry({...i,stream:!1,messages:s},{signal:n?.signal,headers:n?.headers});if("usage"in a&&a.usage){let{completion_tokens:c,prompt_tokens:u,total_tokens:d}=a.usage;c&&(o.completionTokens=(o.completionTokens??0)+c),u&&(o.promptTokens=(o.promptTokens??0)+u),d&&(o.totalTokens=(o.totalTokens??0)+d)}let l=[];if("choices"in a&&a.choices)for(let c of a.choices){let u=c.message?.content??"",d;o.totalTokens!==void 0&&(d={input_tokens:o.promptTokens??0,output_tokens:o.completionTokens??0,total_tokens:o.totalTokens});let{choices:f,...p}=a,m={text:u,message:Qzt(c.message??{role:"assistant"},d,p)};m.generationInfo={...c.finish_reason?{finish_reason:c.finish_reason}:{},...c.logprobs?{logprobs:c.logprobs}:{}},l.push(m)}return{generations:l,llmOutput:{tokenUsage:o}}}withStructuredOutput(e,n){let r=e,o=n?.name,i=n?.method,s=n?.includeRaw,a=o??"extract",l,c;if(i==="jsonMode"){let p;jr(r)?(l=Vm.fromZodSchema(r),p=Hr(r)):l=new Gd,c=this.withConfig({response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"jsonMode"},schema:p}})}else if(jr(r)){let p=Hr(r);c=this.bindTools([{type:"function",function:{name:a,description:p.description,parameters:p}}]).withConfig({tool_choice:{type:"function",function:{name:a}},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:p}}),l=new up({returnSingle:!0,keyName:a,zodSchema:r})}else{let p;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(p=r,a=r.name):(a=r.title??a,p={name:a,description:r.description??"",parameters:r}),c=this.bindTools([{type:"function",function:p}]).withConfig({tool_choice:{type:"function",function:{name:a}},ls_structured_output_format:{kwargs:{method:"functionCalling"},schema:r}}),l=new up({returnSingle:!0,keyName:a})}if(!s)return c.pipe(l).withConfig({runName:"ChatGroqStructuredOutput"});let u=xl.assign({parsed:(p,m)=>l.invoke(p.raw,m)}),d=xl.assign({parsed:()=>null}),f=u.withFallbacks({fallbacks:[d]});return Kc.from([{raw:c},f]).withConfig({runName:"ChatGroqStructuredOutput"})}}});var w9e=C(()=>{y9e()});var Fve,v9e=C(()=>{Jo();Yg();Fve=class extends qg{constructor(e){let n=e?.apiKey||In("XAI_API_KEY");if(!n)throw new Error('xAI API key not found. Please set the XAI_API_KEY environment variable or provide the key into "apiKey" field.');super({...e,model:e?.model||"grok-beta",apiKey:n,configuration:{baseURL:"https://api.x.ai/v1"}});I(this,"lc_serializable",!0);I(this,"lc_namespace",["langchain","chat_models","xai"])}static lc_name(){return"ChatXAI"}_llmType(){return"xai"}get lc_secrets(){return{apiKey:"XAI_API_KEY"}}toJSON(){let e=super.toJSON();return"kwargs"in e&&typeof e.kwargs=="object"&&e.kwargs!=null&&(delete e.kwargs.openai_api_key,delete e.kwargs.configuration),e}getLsParams(e){let n=super.getLsParams(e);return n.ls_provider="xai",n}async completionWithRetry(e,n){delete e.frequency_penalty,delete e.presence_penalty,delete e.logit_bias,delete e.functions;let r=e.messages.map(i=>i.content?i:{...i,content:""}),o={...e,messages:r};return o.stream===!0?super.completionWithRetry(o,n):super.completionWithRetry(o,n)}_convertCompletionsDeltaToBaseMessageChunk(e,n,r){let o=super._convertCompletionsDeltaToBaseMessageChunk(e,n,r);return n.choices[0]?.finish_reason?o.usage_metadata=o.response_metadata.usage:(delete o.response_metadata.usage,delete o.usage_metadata),o}_convertCompletionsMessageToBaseMessage(e,n){let r=super._convertCompletionsMessageToBaseMessage(e,n);return r.additional_kwargs.reasoning_content=e.reasoning_content,r}withStructuredOutput(e,n){let r={...n};return r?.method===void 0&&(r.method="functionCalling"),super.withStructuredOutput(e,r)}}});var x9e=C(()=>{v9e()});var tR,b9e=C(()=>{Kr();ac();Yg();Gm();ye();tR=class extends Zc{constructor(e){let{enableReasoning:n=!1,reasoningEffort:r,enablePromptCaching:o=!0,...i}=e;super(i),this.enableReasoning=n,this.reasoningEffort=r,this.enablePromptCaching=o;let s=e.configuration?.baseURL||"https://openrouter.ai/api/v1";this.isOpenRouter=s.includes("openrouter.ai"),this.openaiClient=new en({apiKey:e.apiKey,baseURL:s,defaultHeaders:e.configuration?.defaultHeaders,fetch:e.configuration?.fetch,dangerouslyAllowBrowser:!0})}invocationParams(e){let n=super.invocationParams(e),r=this.isOpenRouter&&this.enablePromptCaching?{...n,cache_control:{type:"ephemeral"}}:n;if(this.enableReasoning)if(this.reasoningEffort){let o=this.reasoningEffort==="minimal"?"low":this.reasoningEffort;return k(`OpenRouter reasoning enabled with effort: ${o}`),{...r,reasoning:{effort:o}}}else return k("OpenRouter reasoning enabled with max_tokens: 1024"),{...r,reasoning:{max_tokens:1024}};return r}async*_streamResponseChunks(e,n,r){let o=this.invocationParams(n),i=this.toOpenRouterMessages(e),s=await this.openaiClient.chat.completions.create({...o,messages:i,stream:!0,stream_options:{...o.stream_options??{},include_usage:!0}}),a;for await(let l of s){l.usage&&(a=l.usage);let c=l.choices?.[0],u=c?.delta;if(!c||!u)continue;let d=this.normalizeReasoningChunk(u?.reasoning),f=this.extractReasoningDetails(c),p=this.extractDeltaContent(u.content),m=this.buildMessageChunk({rawChunk:l,delta:u,content:p,finishReason:c.finish_reason,reasoningDetails:f,reasoningText:d}),h=new Jr({message:m,text:typeof m.content=="string"?m.content:"",generationInfo:{finish_reason:c.finish_reason,system_fingerprint:l.system_fingerprint,model:l.model}});yield h,h.text&&await r?.handleLLMNewToken(h.text)}if(a&&(yield this.buildUsageGenerationChunk(a)),n.signal?.aborted)throw new Error("AbortError")}toOpenRouterMessages(e){return e.map(n=>{let r=n,o=typeof n._getType=="function"?n._getType():r.role??"user",i=o==="human"?"user":o==="ai"?"assistant":o;return r.tool_call_id?{role:"tool",content:n.content,tool_call_id:r.tool_call_id}:n.additional_kwargs?.function_call?{role:i,content:n.content,function_call:n.additional_kwargs.function_call}:n.additional_kwargs?.tool_calls?{role:i,content:n.content,tool_calls:n.additional_kwargs.tool_calls}:{role:i,content:n.content}})}buildMessageChunk(e){let{rawChunk:n,delta:r,content:o,finishReason:i,reasoningText:s,reasoningDetails:a}=e,l=this.extractToolCallChunks(r.tool_calls),c={};r.function_call&&(c.function_call=r.function_call),Array.isArray(r.tool_calls)&&(c.tool_calls=r.tool_calls);let u={};s&&(u.reasoning=s),a&&a.length>0&&(u.reasoning_details=a),Object.keys(u).length>0&&(c.delta={...c.delta,...u}),a&&a.length>0&&(c.reasoning_details=a);let d=this.buildResponseMetadata(n,i);return new Yt({content:o,additional_kwargs:c,tool_call_chunks:l,response_metadata:d,id:n.id})}normalizeReasoningChunk(e){if(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(n=>this.normalizeReasoningChunk(n)).filter(n=>!!n).join("");if(typeof e=="object"){let n=e,o=[n.output_text,n.text,n.reasoning,n.thinking,n.content].find(i=>typeof i=="string");if(typeof o=="string")return o}}}extractReasoningDetails(e){let n=e,r=n?.delta?.reasoning_details??n?.message?.reasoning_details??e?.reasoning_details;if(Array.isArray(r))return r.filter(o=>o!=null)}extractDeltaContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(n=>typeof n=="string"?n:n&&typeof n=="object"&&typeof n.text=="string"?n.text:"").join(""):""}extractToolCallChunks(e){if(Array.isArray(e))return e.map(n=>{let r=n;return{name:r?.function?.name,args:r?.function?.arguments,id:r?.id,index:r?.index,type:"tool_call_chunk"}})}buildResponseMetadata(e,n){let r={model_provider:"openrouter"};n&&(r.finish_reason=n),e.model&&(r.model=e.model);let o=e.system_fingerprint;return o&&(r.system_fingerprint=o),e.usage&&(r.usage={...e.usage},r.tokenUsage={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens}),r}buildUsageGenerationChunk(e){let n={},r={},o=e.prompt_tokens_details??{};typeof o.audio_tokens=="number"&&(n.audio=o.audio_tokens),typeof o.cached_tokens=="number"&&(n.cache_read=o.cached_tokens);let i=e.completion_tokens_details??{};typeof i.audio_tokens=="number"&&(r.audio=i.audio_tokens),typeof i.reasoning_tokens=="number"&&(r.reasoning=i.reasoning_tokens);let s={input_tokens:e.prompt_tokens??0,output_tokens:e.completion_tokens??0,total_tokens:e.total_tokens??0};Object.keys(n).length>0&&(s.input_token_details=n),Object.keys(r).length>0&&(s.output_token_details=r);let a=new Yt({content:"",response_metadata:{usage:{...e}},usage_metadata:s});return new Jr({message:a,text:""})}}});function njt(t){let e=t||window.fetch;return async(n,r)=>{if(r?.body&&typeof r.body=="string")try{let o=JSON.parse(r.body),i=!1;Array.isArray(o.tools)&&(o.tools=o.tools.map(s=>{let a={};for(let[l,c]of Object.entries(s))c!=null&&(a[l]=c);return a}),i=!0),i&&(r={...r,body:JSON.stringify(o)})}catch{}return e(n,r)}}var az,C9e=C(()=>{Yg();az=class extends Zc{constructor(e){let r=e.configuration?.fetch;super({...e,useResponsesApi:!0,configuration:{...e.configuration,fetch:njt(r)},modelKwargs:{...e.modelKwargs,text:{format:{type:"text"}}}})}}});function _9e(t,e,n=!1){let r=n?"Amazon Bedrock streaming request failed with status":"Amazon Bedrock request failed with status";if(t===400&&e.includes("on-demand throughput")&&e.includes("inference profile")){let i=e.match(/model ID ([^\s]+) with/)?.[1]??"<model-id>",s=i.includes(".")?i.split(".")[0]:"<provider>";return`This Bedrock model requires a cross-region inference profile ID, not a bare regional model ID. Update the model name in Settings \u2192 Models to use one of the prefixed forms: global.${s}.<id> (recommended), us.${s}.<id>, eu.${s}.<id>, or apac.${s}.<id>. The current value "${i}" is not accepted by AWS on-demand throughput.`}return`${r} ${t}: ${e}`}var L8,D8,S9e=C(()=>{L8=N(uD());vI();ye();Kr();ac();Bd();Bu();D8=class extends dp{constructor(e){let{modelId:n,apiKey:r,endpoint:o,streamEndpoint:i,defaultMaxTokens:s,defaultTemperature:a,defaultTopP:l,anthropicVersion:c,enableThinking:u,fetchImplementation:d,...f}=e;if(!n)throw new Error("Amazon Bedrock model identifier is required.");if(!r)throw new Error("Amazon Bedrock API key is required.");if(!o)throw new Error("Amazon Bedrock endpoint is required.");super(f);let p=typeof fetch<"u"?fetch.bind(window):void 0;if(this.fetchImpl=d??p,!this.fetchImpl)throw new Error("No fetch implementation available for Amazon Bedrock requests.");f.streaming&&!i&&ee("Amazon Bedrock streaming requested without a streaming endpoint; falling back to non-streaming mode."),this.modelName=n,this.apiKey=r,this.endpoint=o,this.streamEndpoint=i,this.defaultMaxTokens=s,this.defaultTemperature=a,this.defaultTopP=l,this.anthropicVersion=c,this.enableThinking=u??!1}_llmType(){return"amazon-bedrock"}bindTools(e){let n=Object.create(this);return n.boundTools=e,n}convertToolsToClaude(e){return e.map(n=>{let r={type:"object",properties:{}};return n.schema&&(r=jr(n.schema)?Hr(n.schema):n.schema),{name:n.name,description:n.description||"",input_schema:r}})}extractToolCalls(e){let n=e;if(!Array.isArray(n?.content))return;let r=n.content.filter(o=>o.type==="tool_use");if(r.length!==0)return r.map(o=>({id:o.id,name:o.name,args:o.input||{},type:"tool_call"}))}async _generate(e,n,r){let o=this.buildRequestBody(e,n),i=await this.fetchImpl(this.endpoint,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(o)});if(!i.ok){let m=await i.text();throw new Error(_9e(i.status,m))}let s=await i.json(),a=this.extractText(s),l=this.extractToolCalls(s);r&&a&&await r.handleLLMNewToken(a);let c=this.extractUsage(s),u=c?this.normaliseUsageMetadata(c):void 0,d={stopReason:s.stop_reason??s.stopReason,usage:c,rawResponse:s};return{generations:[{message:new kn({content:a,response_metadata:d,usage_metadata:u,tool_calls:l}),text:a,generationInfo:d}],llmOutput:d}}async*_streamResponseChunks(e,n={},r){if(!this.streamEndpoint){let p=await this._generate(e,n,r),m=p.generations[0]?.text??"";if(!m)return;let h=new Yt({content:m,response_metadata:p.llmOutput??{}});yield new Jr({message:h,text:m,generationInfo:p.llmOutput??{}});return}let o=this.buildRequestBody(e,n),i=`bedrock-${Date.now()}-${Math.random().toString(36).slice(2,9)}`;k(`[${i}] Starting Bedrock stream request to ${this.streamEndpoint}`);let s=await this.fetchImpl(this.streamEndpoint,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(o),signal:n?.signal});if(!s.ok){let p=await s.text();throw new Error(_9e(s.status,p,!0))}if(!s.body)throw new Error("Amazon Bedrock streaming response did not include a readable body.");let a=s.body.getReader(),l=new Uint8Array(0),c,u,d=!1,f=[];try{for(;;){let{value:p,done:m}=await a.read();if(m)break;if(!p)continue;let h=new Uint8Array(l.length+p.length);h.set(l),h.set(p,l.length),l=h;let{messages:g,remainingBytes:y}=this.parseEventStreamBuffer(l);l=new Uint8Array(y);for(let w of g){let v=this.safeJsonParse(w);if(!v||typeof v!="object"){ee(`[${i}] Failed to parse event JSON: ${w.slice(0,100)}...`);continue}let x=v,b=x;typeof x.bytes=="string"&&!x.type&&(b={type:"chunk",chunk:{bytes:x.bytes}});let _=await this.processStreamEvent(b,r,u,c);if(u=_.usage??u,c=_.stopReason??c,_.hasText||f.push(this.describeEvent(x)),_.deltaChunks.length>0)for(let T of _.deltaChunks)!(Array.isArray(T.message.content)&&T.message.content.length>0&&T.message.content[0]?.type==="thinking")&&T.text&&(d=!0),yield T;_.debugSummaries.length>0&&f.push(..._.debugSummaries)}}}catch(p){throw z(`[${i}] Error during stream processing: ${p instanceof Error?p.message:String(p)}`),p}finally{a.releaseLock()}if((u||c)&&(yield this.buildTerminalMetadataChunk(c,u)),!d){ee(`[${i}] Stream complete but no answer text yielded (only thinking or no content). Usage: ${JSON.stringify(u)}, stopReason: ${c}`),f.length>0&&k(`[${i}] Amazon Bedrock streaming produced no answer text. Sample events: ${f.slice(0,5).join(" | ")}`),ee(`[${i}] Amazon Bedrock streaming returned no answer content. Falling back to non-streaming response.`);let p=await this._generate(e,n,r),m=p.generations[0]?.text??"";if(m){let h=p.llmOutput??{};yield new Jr({message:new Yt({content:m,response_metadata:h}),text:m,generationInfo:h})}}}safeJsonParse(e){try{return JSON.parse(e)}catch{return null}}buildContentItemsFromDelta(e){if(!e||typeof e!="object")return null;let n=e.content_block_delta,r=e.contentBlockDelta,o=n?.delta??r?.delta??e.delta;if(!o||typeof o!="object")return null;let i=o,s=i.type;if(s==="thinking"||s==="thinking_delta"){let a=i.thinking;return typeof a=="string"&&a.length>0?[{type:"thinking",thinking:a}]:[{type:"thinking",thinking:""}]}if(s==="text_delta"||s==="text"){let a=i.text;if(typeof a=="string"&&a.length>0)return[{type:"text",text:a}]}return null}extractToolCallChunk(e){if(!e||typeof e!="object")return null;let n=e.content_block;if(e.type==="content_block_start"&&n?.type==="tool_use")return{id:n.id,index:typeof e.index=="number"?e.index:0,name:n.name,args:""};let r=e.delta;return e.type==="content_block_delta"&&r?.type==="input_json_delta"?{index:typeof e.index=="number"?e.index:0,args:typeof r.partial_json=="string"?r.partial_json:""}:null}async processStreamEvent(e,n,r,o){let i=[],s=r,a=o,l=!1,c=[],u=e.chunk;if(e?.type==="chunk"&&typeof u?.bytes=="string"){let d=this.decodeChunkBytes(u.bytes);for(let f of d){let p=this.safeJsonParse(f);if(!p||typeof p!="object"){c.push(`Failed to parse inner payload: ${this.describePayload(f)}`);continue}let m=p,h=this.buildChunkMetadata(m),g=this.buildContentItemsFromDelta(m),y=this.extractToolCallChunk(m);if(y){let x=new Yt({content:"",response_metadata:h,tool_call_chunks:[y]}),b=new Jr({message:x,text:"",generationInfo:h});i.push(b),l=!0}else if(g&&g.length>0){let x=g[0]?.type==="thinking",b=x?g[0].thinking||"":g[0]?.text||"",_={};x&&b&&(_.delta={reasoning:b});let T=new Yt({content:g,response_metadata:h,...Object.keys(_).length>0?{additional_kwargs:_}:{}}),S=new Jr({message:T,text:b,generationInfo:h});i.push(S),l=!0,n&&b&&await n.handleLLMNewToken(b)}else{let x=this.extractStreamText(m);if(x){let b=new Yt({content:x,response_metadata:h}),_=new Jr({message:b,text:x,generationInfo:h});i.push(_),l=!0,n&&await n.handleLLMNewToken(x)}else{let b=m.delta;if(m.type==="content_block_delta"&&b?.type!=="input_json_delta"){let _=`No content in content_block_delta event: ${this.describeEvent(m)}`;c.push(_),ee(`processStreamEvent: ${_}`)}}}let w=this.extractUsage(m);w&&(s=w);let v=this.extractStopReason(m);v&&(a=v)}}else{let d=this.buildChunkMetadata(e),f=this.buildContentItemsFromDelta(e),p=this.extractToolCallChunk(e);if(p){let g=new Yt({content:"",response_metadata:d,tool_call_chunks:[p]}),y=new Jr({message:g,text:"",generationInfo:d});i.push(y),l=!0}else if(f&&f.length>0){let g=f[0]?.type==="thinking",y=g?f[0].thinking||"":f[0]?.text||"",w={};g&&y&&(w.delta={reasoning:y});let v=new Yt({content:f,response_metadata:d,...Object.keys(w).length>0?{additional_kwargs:w}:{}}),x=new Jr({message:v,text:y,generationInfo:d});i.push(x),l=!0,n&&y&&await n.handleLLMNewToken(y)}else{let g=this.extractStreamText(e);if(g){let y=new Yt({content:g,response_metadata:d}),w=new Jr({message:y,text:g,generationInfo:d});i.push(w),l=!0,n&&await n.handleLLMNewToken(g)}}let m=this.extractUsage(e);m&&(s=m);let h=this.extractStopReason(e);h&&(a=h)}return{deltaChunks:i,usage:s,stopReason:a,hasText:l,debugSummaries:c}}describeEvent(e){if(!e||typeof e!="object")return"<empty event>";let n=e,r=typeof n.type=="string"?n.type:"unknown",o=Object.keys(n).slice(0,6).join(","),i=this.stringifyForLog(n);return`${r} {${o}} -> ${i}`}describePayload(e){return e?e.length<=200?e:`${e.slice(0,200)}\u2026 (len=${e.length})`:"<empty payload>"}stringifyForLog(e){try{let n=this.sanitiseForLog(e),r=JSON.stringify(n);return r?r.length>400?`${r.slice(0,400)}\u2026 (len=${r.length})`:r:"<un-stringifiable>"}catch{return"<failed to stringify>"}}sanitiseForLog(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.slice(0,5).map(i=>this.sanitiseForLog(i));let n=e,r={},o=Object.entries(n);for(let i=0;i<o.length&&i<10;i+=1){let[s,a]=o[i];typeof a=="string"&&a.length>200?s==="bytes"||s==="chunk"||s==="chunk_bytes"?r[s]=`<base64 len=${a.length}>`:r[s]=`${a.slice(0,200)}\u2026 (len=${a.length})`:r[s]=this.sanitiseForLog(a)}return r}decodeChunkBytes(e){let n=this.decodeBase64ToUint8Array(e);if(!n||n.length===0)return ee("decodeChunkBytes: Failed to decode base64 or empty bytes"),[];let r=this.findFirstNonWhitespaceByte(n);if(r===123||r===91){let s=this.decodeUtf8(n);return this.splitJsonLines(s)}let o=this.decodeEventStreamMessages(n);if(o.length>0)return o;ee("decodeChunkBytes: EventStream decoding failed, falling back to plain UTF-8");let i=this.decodeUtf8(n);return this.splitJsonLines(i)}decodeBase64ToUint8Array(e){try{return new Uint8Array(L8.Buffer.from(e,"base64"))}catch{return null}}findFirstNonWhitespaceByte(e){for(let n=0;n<e.length;n+=1){let r=e[n];if(r!==void 0&&!this.isWhitespaceByte(r))return r}return null}isWhitespaceByte(e){return e===9||e===10||e===13||e===32}decodeUtf8(e){return e.length===0?"":typeof TextDecoder<"u"?new TextDecoder().decode(e):typeof L8.Buffer<"u"?L8.Buffer.from(e).toString("utf-8"):""}splitJsonLines(e){return e?e.split(`
`).map(n=>n.trim()).filter(n=>n.length>0):[]}parseEventStreamBuffer(e){let n=[];if(e.length<12)return{messages:n,remainingBytes:e};let r=new DataView(e.buffer,e.byteOffset,e.byteLength),o=0;for(;o+12<=e.length;){let s=r.getUint32(o,!1),a=r.getUint32(o+4,!1);if(o+s>e.length)break;if(s<=0||a<0||a+12>s){ee(`parseEventStreamBuffer: Invalid message structure at offset ${o}: totalLength=${s}, headersLength=${a}`);break}let l=o+12+a,c=o+s-4;if(l>c||c>e.length){ee(`parseEventStreamBuffer: Invalid payload bounds at offset ${o}`);break}if(l<e.length){let u=e.subarray(l,c),d=this.decodeUtf8(u).trim();d.length>0&&n.push(d)}if(o+=s,s===0)break}let i=o<e.length?e.subarray(o):new Uint8Array(0);return{messages:n,remainingBytes:i}}decodeEventStreamMessages(e){let{messages:n}=this.parseEventStreamBuffer(e);return n}buildChunkMetadata(e){let n={provider:"amazon-bedrock"};typeof e?.type=="string"&&(n.event_type=e.type),e?.index!==void 0&&(n.event_index=e.index);let r=this.extractStopReason(e);r&&(n.stop_reason=r);let o=this.extractUsage(e);return o&&(n.usage=o),n}extractStreamText(e){if(!e||typeof e!="object")return null;let n=e.delta,r=e.content_block_delta,o=e.contentBlockDelta,i=r?.delta,s=o?.delta,a=[n?.thinking,i?.thinking,s?.thinking,n?.reasoning_content,e.reasoning_content];for(let h of a)if(typeof h=="string"&&h.length>0)return h;let l=[e.text,e.outputText,e.completion,e.resultText,e.delta];for(let h of l)if(typeof h=="string"&&h.length>0)return h;let c=e.message,u=e.messageStop,d=e.message_stop,f=u?.message,p=d?.message,m=[n?.text,n?.output_text,n?.content,s?.text,s?.output_text,s?.content,i?.text,i?.output_text,i?.content,c?.content,f?.content,p?.content,e.content];for(let h of m){let g=this.extractTextFromCandidate(h);if(g)return g}return null}extractTextFromCandidate(e){if(!e)return null;if(typeof e=="string")return e.length>0?e:null;if(Array.isArray(e)){let n=e.map(r=>{if(typeof r=="string")return r;if(r&&typeof r=="object"){let o=r;if(typeof o.text=="string")return o.text;if(typeof o.value=="string")return o.value;if(Array.isArray(o.content))return o.content.map(i=>{let s=i;return typeof s?.text=="string"?s.text:""}).join("")}return""}).join("");return n.length>0?n:null}if(typeof e=="object"){let n=e;if(typeof n.text=="string")return n.text.length>0?n.text:null;if(n.text&&typeof n.text=="object"){let r=this.extractTextFromCandidate(n.text);if(r)return r}if(typeof n.value=="string")return n.value.length>0?n.value:null;if(Array.isArray(n.content))return this.extractTextFromCandidate(n.content);if(n.delta){let r=this.extractTextFromCandidate(n.delta);if(r)return r}if(n.message&&typeof n.message=="object"){let r=this.extractTextFromCandidate(n.message);if(r)return r}}return null}extractUsage(e){if(!(!e||typeof e!="object")){if(e.usage&&typeof e.usage=="object")return e.usage;if(e.metrics&&typeof e.metrics=="object")return e.metrics;if(e["amazon-bedrock-invocationMetrics"]&&typeof e["amazon-bedrock-invocationMetrics"]=="object")return e["amazon-bedrock-invocationMetrics"];if(e.messageStop&&typeof e.messageStop=="object")return this.extractUsage(e.messageStop);if(e.message_stop&&typeof e.message_stop=="object")return this.extractUsage(e.message_stop)}}extractStopReason(e){if(!e||typeof e!="object")return;let n=e.messageStop,r=e.message_stop,o=e.stop_reason||e.stopReason||e.completionReason||e.completion_reason||e.reason||n?.stopReason||r?.stop_reason||(e.type==="message_stop"?e.reason:void 0);return typeof o=="string"?o:void 0}buildTerminalMetadataChunk(e,n){let r=n?this.normaliseUsageMetadata(n):void 0,o={provider:"amazon-bedrock"};e&&(o.stop_reason=e),n&&(o.usage=n);let i=new Yt({content:"",response_metadata:o,usage_metadata:r});return new Jr({message:i,text:"",generationInfo:o})}normaliseUsageMetadata(e){let n=this.coerceNumber(e.inputTokens)??this.coerceNumber(e.input_tokens)??this.coerceNumber(e.inputTokenCount)??this.coerceNumber(e.promptTokens)??this.coerceNumber(e.prompt_tokens)??0,r=this.coerceNumber(e.outputTokens)??this.coerceNumber(e.output_tokens)??this.coerceNumber(e.outputTokenCount)??this.coerceNumber(e.completionTokens)??this.coerceNumber(e.completion_tokens)??0,o=this.coerceNumber(e.totalTokens)??this.coerceNumber(e.total_tokens)??n+r;return{input_tokens:n,output_tokens:r,total_tokens:o}}coerceNumber(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let n=Number(e);return Number.isFinite(n)?n:void 0}}convertImageContent(e){try{let n=e.match(/^data:([^;]+);base64,(.+)$/);if(!n)return null;let[,r,o]=n;return!r||!o||!r.startsWith("image/")?null:{type:"image",source:{type:"base64",media_type:r,data:o}}}catch(n){return z("Error converting image content:",n),null}}buildRequestBody(e,n){let r=[],o=[];e.forEach(c=>{let u=c.type;if(u==="system"){let p=this.normaliseMessageContent(c),m=typeof p=="string"?p:"";m&&o.push(m);return}if(u==="tool"){let p=c,m=typeof p.content=="string"?p.content:JSON.stringify(p.content);r.push({role:"user",content:[{type:"tool_result",tool_use_id:p.tool_call_id,content:m}]});return}if(u==="ai"){let m=c.tool_calls;if(m&&m.length>0){let h=[],g=this.normaliseMessageContent(c);typeof g=="string"&&g&&h.push({type:"text",text:g});for(let y of m)h.push({type:"tool_use",id:y.id||`tool_${Date.now()}`,name:y.name,input:y.args});h.length>0&&r.push({role:"assistant",content:h});return}}let d=this.normaliseMessageContent(c);if(!d)return;let f=[];if(typeof d=="string")f.push({type:"text",text:d});else if(Array.isArray(d))for(let p of d)if(p.type==="text"&&typeof p.text=="string")f.push({type:"text",text:p.text});else if(p.type==="image_url"&&p.image_url?.url){let m=p.image_url,h=this.convertImageContent(m.url);h&&f.push(h)}else p.type==="image"&&p.source&&f.push(p);f.length>0&&r.push({role:u==="ai"?"assistant":"user",content:f})});let i=n?.maxTokens??this.defaultMaxTokens,s=n?.temperature??this.defaultTemperature,a=n?.topP??this.defaultTopP,l={messages:r};if(this.boundTools&&this.boundTools.length>0&&(l.tools=this.convertToolsToClaude(this.boundTools)),o.length>0&&(l.system=o.join(`

`)),i!==void 0&&(l.max_tokens=i),this.anthropicVersion&&(l.anthropic_version=this.anthropicVersion),this.enableThinking){let c=this.modelName.match(/claude-opus-4-(\d{1,2})(?:[-.]|$)/),u=c?parseInt(c[1],10)>=7:!1;l.thinking=u?{type:"adaptive",display:"summarized"}:{type:"enabled",budget_tokens:2048},l.temperature=1,k("[BedrockChatModel] Enabled thinking mode for Claude model with temperature=1")}else s!==void 0&&(l.temperature=s);return a!==void 0&&(l.top_p=a),l}normaliseMessageContent(e){let{content:n}=e;return typeof n=="string"?n:Array.isArray(n)?n.some(o=>typeof o=="object"&&o!==null&&(o.type==="image_url"||o.type==="image"))?n.map(o=>{if(typeof o=="string")return{type:"text",text:o};if(typeof o=="object"&&o!==null){if(o.type==="text"||o.type==="image_url"||o.type==="image")return o;if("text"in o&&typeof o.text=="string")return{type:"text",text:o.text};if("content"in o&&typeof o.content=="string")return{type:"text",text:o.content}}return null}).filter(o=>o!==null):n.map(o=>{if(typeof o=="string")return o;if(typeof o=="object"&&o!==null){if("text"in o&&typeof o.text=="string")return o.text;if("content"in o&&typeof o.content=="string")return o.content}return""}).join(""):typeof n=="object"&&n!==null&&"text"in n?n.text??"":""}extractText(e){return typeof e?.outputText=="string"?e.outputText:Array.isArray(e?.content)?e.content.map(n=>{if(!n)return"";if(typeof n=="string")return n;if(typeof n=="object"){let r=n;if(typeof r.text=="string")return r.text;if(r.text&&typeof r.text=="object"&&"text"in r.text)return r.text.text??""}return""}).join(""):typeof e?.completion=="string"?e.completion:typeof e?.resultText=="string"?e.resultText:""}}});function Uve(t){return t instanceof Mp||t instanceof Error&&t.name==="AuthCancelledError"}var Mp,Bve=C(()=>{Mp=class t extends Error{constructor(n="Authentication cancelled by user."){super(n);this.name="AuthCancelledError";Object.setPrototypeOf(this,t.prototype)}}});var lz,T9e,rjt,ojt,ijt,cz,sjt,ajt,I9e,ljt,sh,uz=C(()=>{Se();Su();lz=require("obsidian");Bve();T9e="Iv1.b507a08c87ecfe98",rjt="https://github.com/login/device/code",ojt="https://github.com/login/oauth/access_token",ijt="https://api.github.com/copilot_internal/v2/token",cz="https://api.githubcopilot.com",sjt=`${cz}/models`,ajt=60*1e3,I9e=60*60*1e3,ljt=3,sh=class t{constructor(){this.abortController=null;this.refreshPromise=null;this.refreshAttempts=0;this.modelPolicyTermsCache=new Map;this.authGeneration=0}static getInstance(){return t.instance||(t.instance=new t),t.instance}getAuthState(){let e=q(),n=!!e.githubCopilotAccessToken,r=!!e.githubCopilotToken,o=e.githubCopilotTokenExpiresAt,s=!(typeof o=="number"&&o>0)||o<Date.now();return r&&!s||r&&n?{status:"authenticated"}:n?{status:"pending"}:{status:"idle"}}isAuthenticated(){return this.getAuthState().status==="authenticated"}async startDeviceCodeFlow(){let e=new URLSearchParams({client_id:T9e,scope:"read:user"}).toString(),n=await(0,lz.requestUrl)({url:rjt,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:e,throw:!1}),r=this.getRequestUrlJson(n);if(n.status!==200){let i=typeof r.error_description=="string"?r.error_description:typeof r.error=="string"?r.error:"";throw new Error(i?`Failed to get device code: ${i}`:`Failed to get device code: ${n.status}`)}if(typeof r.device_code!="string"||typeof r.user_code!="string"||typeof r.expires_in!="number")throw new Error("Invalid device code response from GitHub");let o=typeof r.verification_uri=="string"?r.verification_uri:typeof r.verification_uri_complete=="string"?r.verification_uri_complete:null;if(!o)throw new Error("Invalid device code response from GitHub: missing verification URI");return{deviceCode:r.device_code,userCode:r.user_code,verificationUri:o,expiresIn:r.expires_in,interval:typeof r.interval=="number"&&r.interval>0?r.interval:5}}async pollForAccessToken(e,n,r,o){let i=this.authGeneration;this.abortPolling();let s=new AbortController;this.abortController=s;let a=Date.now()+r*1e3,l=0;try{for(;Date.now()<a;){if(s.signal.aborted||this.authGeneration!==i)throw new Mp;if(l++,o?.(l),await this.delay(n*1e3,s.signal),s.signal.aborted||this.authGeneration!==i)throw new Mp;let c=new URLSearchParams({client_id:T9e,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"}).toString(),u=await(0,lz.requestUrl)({url:ojt,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:c,throw:!1});if(s.signal.aborted||this.authGeneration!==i)throw new Mp;let d=this.getRequestUrlJson(u);if(u.status!==200){let f=typeof d.error_description=="string"?d.error_description:typeof d.error=="string"?d.error:`HTTP ${u.status}`;throw new Error(`Token request failed: ${f}`)}if(typeof d.access_token=="string"&&d.access_token){if(s.signal.aborted||this.authGeneration!==i)throw new Mp;return Ls({githubCopilotAccessToken:d.access_token}),d.access_token}if(d.error!=="authorization_pending"){if(d.error==="slow_down"){n+=5;continue}if(d.error==="device_code_expired"||d.error==="expired_token")throw new Error("Device code expired. Please restart authentication.");if(d.error==="access_denied")throw new Error("Authorization denied by user.");if(typeof d.error=="string"&&d.error)throw new Error(typeof d.error_description=="string"&&d.error_description?d.error_description:d.error)}}throw new Error("Device code expired. Please restart authentication.")}finally{this.abortController===s&&(this.abortController=null)}}async fetchCopilotToken(e){let n=this.authGeneration,r=e||q().githubCopilotAccessToken;if(!r)throw new Error("No GitHub access token available");r=await pn(r);let o=await(0,lz.requestUrl)({url:ijt,method:"GET",headers:{Authorization:`Bearer ${r}`,Accept:"application/json"},throw:!1});if(this.authGeneration!==n)throw new Mp("Authentication was reset during token refresh.");let i=this.getRequestUrlJson(o);if(o.status!==200){let l=typeof i.message=="string"?i.message:typeof i.error=="string"?i.error:"";throw new Error(l?`Failed to get Copilot token: ${o.status} (${l})`:`Failed to get Copilot token: ${o.status}`)}let s=i.token;if(!s||typeof s!="string")throw new Error("Invalid response from Copilot API: missing or invalid token");let a=this.parseCopilotTokenExpiresAt(i);if(this.authGeneration!==n)throw new Mp("Authentication was reset during token refresh.");return Ls({githubCopilotToken:s,githubCopilotTokenExpiresAt:a}),s}async getValidCopilotToken(){let e=q(),n=e.githubCopilotTokenExpiresAt,o=!(typeof n=="number"&&n>0)||n<Date.now()+ajt;if(e.githubCopilotToken&&!o)return this.refreshAttempts=0,await pn(e.githubCopilotToken);if(!e.githubCopilotAccessToken)throw new Error("Not authenticated with GitHub Copilot. Please set up authentication first.");if(this.refreshAttempts>=ljt)throw this.refreshAttempts=0,new Error("Failed to refresh Copilot token after multiple attempts. Please try reconnecting.");return this.refreshPromise?this.refreshPromise:(this.refreshAttempts++,this.refreshPromise=this.fetchCopilotToken().finally(()=>{this.refreshPromise=null}),this.refreshPromise)}buildCopilotHeaders(e){return{"Content-Type":"application/json",Authorization:`Bearer ${e}`,"User-Agent":"GitHubCopilotChat/0.38.2026022001","Editor-Version":"vscode/1.110.0","Editor-Plugin-Version":"copilot-chat/0.38.2026022001","Copilot-Integration-Id":"vscode-chat","Openai-Intent":"conversation-panel","X-GitHub-Api-Version":"2025-05-01"}}abortPolling(){this.abortController&&(this.abortController.abort(),this.abortController=null)}resetAuth(){this.authGeneration++,this.abortPolling(),this.refreshPromise=null,this.refreshAttempts=0,this.modelPolicyTermsCache.clear(),Ls({githubCopilotAccessToken:"",githubCopilotToken:"",githubCopilotTokenExpiresAt:0})}async listModels(){let e=async i=>await(0,lz.requestUrl)({url:sjt,method:"GET",headers:{...this.buildCopilotHeaders(i),Accept:"application/json","Openai-Intent":"model-access"},throw:!1}),n=await this.getValidCopilotToken(),r=await e(n);if(r.status===401&&(this.clearCopilotToken(),n=await this.getValidCopilotToken(),r=await e(n)),r.status!==200)throw new Error(`Failed to list models: ${r.status}`);let o=this.getRequestUrlJson(r);return this.modelPolicyTermsCache.clear(),o.data?.forEach(i=>{i.policy?.terms&&this.modelPolicyTermsCache.set(i.id,i.policy.terms)}),o}getPolicyTerms(e){return this.modelPolicyTermsCache.get(e)}clearCopilotToken(){Ls({githubCopilotToken:"",githubCopilotTokenExpiresAt:0})}buildCopilotRequestHeaders(e){return this.buildCopilotHeaders(e)}invalidateCopilotToken(){this.clearCopilotToken()}getRequestUrlJson(e){if(typeof e.json=="string")try{return JSON.parse(e.json)}catch{return e.json}return e.json}parseCopilotTokenExpiresAt(e){if(!e||typeof e!="object")return Date.now()+I9e;let n=e,r=this.parseExpiresAtValue(n.expires_at);if(r!==null)return r;let o=n.expires_in,i=typeof o=="number"?o:typeof o=="string"?Number(o):Number.NaN;return Number.isFinite(i)&&i>0?Date.now()+i*1e3:Date.now()+I9e}parseExpiresAtValue(e){if(typeof e=="number")return!Number.isFinite(e)||e<=0?null:e>1e12?e:e*1e3;if(typeof e=="string"){let n=e.trim();if(!n)return null;let r=Number(n);if(Number.isFinite(r)&&r>0)return r>1e12?r:r*1e3;let o=Date.parse(n);if(!Number.isNaN(o)&&o>0)return o}return null}delay(e,n){return n?n.aborted?Promise.reject(new Mp):new Promise((r,o)=>{let i=()=>{window.clearTimeout(s),o(new Mp)},s=window.setTimeout(()=>{n.removeEventListener("abort",i),r()},e);n.addEventListener("abort",i,{once:!0})}):new Promise(r=>window.setTimeout(r,e))}}});function zve(t,e){return async(n,r={})=>{let o=typeof n=="string"?n:typeof Request<"u"&&n instanceof Request?n.url:n instanceof URL?n.href:n.url,i=async l=>{let c=t.buildCopilotRequestHeaders(l),u=new Headers(r.headers);for(let[d,f]of Object.entries(c))u.set(d,f);return e(o,{...r,headers:u})},s=await t.getValidCopilotToken(),a=await i(s);if(a.status===401){try{await a.body?.cancel()}catch{}t.invalidateCopilotToken(),s=await t.getValidCopilotToken(),a=await i(s)}return a}}var dz,jve=C(()=>{Yg();uz();dz=class extends Zc{constructor(e){let{fetchImplementation:n,configuration:r,apiKey:o,...i}=e,s=sh.getInstance(),a=n??r?.fetch??fetch,l=zve(s,a);super({...i,apiKey:o||"copilot-dynamic-token",useResponsesApi:!0,streamUsage:!1,configuration:{...r??{},baseURL:r?.baseURL??cz,fetch:l}})}_llmType(){return"github-copilot"}}});function ujt(t){return typeof t=="string"?t:t==null?"":Array.isArray(t)?t.map(e=>typeof e=="string"?e:e&&typeof e=="object"&&typeof e.text=="string"?e.text:"").join(""):typeof t=="object"&&typeof t.text=="string"?t.text:""}var cjt,$8,P9e=C(()=>{Yg();uz();jve();qe();cjt=4;$8=class t extends qg{constructor(n){let{fetchImplementation:r,configuration:o,apiKey:i,...s}=n,a=sh.getInstance(),l=r??o?.fetch??fetch,c=t.buildAuthedFetch(a,l);super({...s,apiKey:i||"copilot-dynamic-token",streamUsage:!1,configuration:{...o??{},baseURL:o?.baseURL??cz,fetch:c}});this.lc_serializable=!1;this.lc_namespace=["langchain","chat_models","github_copilot"]}static buildAuthedFetch(n,r){return zve(n,r)}_llmType(){return"github-copilot"}_convertCompletionsDeltaToBaseMessageChunk(n,r,o){return!n.role&&!o&&(o="assistant"),n.content=ujt(n.content),super._convertCompletionsDeltaToBaseMessageChunk(n,r,o)}async getNumTokens(n){let r=Kx(n);return r?Math.ceil(r.length/cjt):0}}});var Vve={};zn(Vve,{default:()=>Np,normalizeAzureUrl:()=>A9e});function A9e(t){if(!t)return{baseUrl:void 0,apiVersion:void 0};let e;try{e=new URL(t)}catch{return{baseUrl:t,apiVersion:void 0}}let n=e.searchParams.get("api-version")||void 0;e.search="";let r=e.toString().replace(/\/+$/,"");return r=r.replace(/\/(chat\/completions|embeddings)$/,""),{baseUrl:r,apiVersion:n}}var E9e,djt,fjt,as,Np,eP=C(()=>{Ir();It();Su();ye();ns();Se();qe();j8e();qd();W8e();_de();w9e();Bde();Yg();x9e();Nf();E9e=require("obsidian");b9e();C9e();S9e();P9e();jve();djt=[{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_NONE"}];mI.prototype.getNumTokens=async t=>{let e=typeof t=="string"?t:t.map(n=>n.text??"").join("");return Math.ceil(e.length/4)};fjt={openai:Zc,"azure openai":Zc,anthropic:lve,cohereai:Zc,google:bde,xai:Fve,openrouterai:tR,ollama:$de,"lm-studio":tR,groq:$ve,"3rd party (openai-format)":Zc,siliconflow:Zc,"copilot-plus":tR,mistralai:Zc,deepseek:cve,"amazon-bedrock":D8,"github-copilot":$8};as=class as{constructor(){this.providerApiKeyMap={openai:()=>q().openAIApiKey,google:()=>q().googleApiKey,"azure openai":()=>q().azureOpenAIApiKey,anthropic:()=>q().anthropicApiKey,cohereai:()=>q().cohereApiKey,openrouterai:()=>q().openRouterAiApiKey,groq:()=>q().groqApiKey,xai:()=>q().xaiApiKey,ollama:()=>"default-key","lm-studio":()=>"default-key","3rd party (openai-format)":()=>"default-key","copilot-plus":()=>q().plusLicenseKey,mistralai:()=>q().mistralApiKey,deepseek:()=>q().deepseekApiKey,"amazon-bedrock":()=>q().amazonBedrockApiKey,siliconflow:()=>q().siliconflowApiKey,"github-copilot":()=>q().githubCopilotToken||q().githubCopilotAccessToken};this.buildModelMap(),Ho(()=>{this.buildModelMap(),this.validateCurrentModel()})}static getInstance(){return as.instance||(as.instance=new as),as.instance}getTemperatureForModel(e,n,r){if(!e.isThinkingEnabled)return e.isOSeries||e.isGPT5?as.REASONING_MODEL_TEMPERATURE:n.temperature??r.temperature}async getModelConfig(e){let n=q(),r=e.name,o=AA(r),{isThinkingEnabled:i,usesAdaptiveThinking:s}=o,a=this.getTemperatureForModel(o,e,n),l=e.maxTokens??n.maxTokens,c={modelName:r,streaming:e.stream??!0,maxRetries:3,maxConcurrency:3,enableCors:e.enableCors,...!i&&a!==void 0?{temperature:a}:{}},d={openai:{modelName:r,apiKey:await pn(e.apiKey||n.openAIApiKey),configuration:{baseURL:e.baseUrl,fetch:e.enableCors?fo:void 0,organization:await pn(e.openAIOrgId||n.openAIOrgId)},...this.getOpenAISpecialConfig(r,e.maxTokens??n.maxTokens,e.temperature??n.temperature,e)},anthropic:{anthropicApiKey:await pn(e.apiKey||n.anthropicApiKey),model:r,anthropicApiUrl:e.baseUrl,clientOptions:{defaultHeaders:{"anthropic-dangerous-direct-browser-access":"true"},fetch:e.enableCors?fo:void 0},...i&&{thinking:s?{type:"adaptive",display:"summarized"}:{type:"enabled",budget_tokens:as.ANTHROPIC_THINKING_BUDGET_TOKENS}}},"azure openai":await(async()=>{let h=A9e(e.baseUrl);return{modelName:e.baseUrl?r:e.azureOpenAIApiDeploymentName||n.azureOpenAIApiDeploymentName,apiKey:await pn(e.apiKey||n.azureOpenAIApiKey),configuration:{baseURL:h.baseUrl||`https://${e.azureOpenAIApiInstanceName||n.azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${e.azureOpenAIApiDeploymentName||n.azureOpenAIApiDeploymentName}`,defaultQuery:{"api-version":h.apiVersion||e.azureOpenAIApiVersion||n.azureOpenAIApiVersion||"2024-05-01-preview"},defaultHeaders:{"Content-Type":"application/json","api-key":await pn(e.apiKey||n.azureOpenAIApiKey)},fetch:e.enableCors?fo:void 0},...this.getOpenAISpecialConfig(r,e.maxTokens??n.maxTokens,e.temperature??n.temperature,e)}})(),cohereai:{modelName:r,apiKey:await pn(e.apiKey||n.cohereApiKey),configuration:{baseURL:e.baseUrl||Cu.cohereai.host,fetch:e.enableCors?fo:void 0}},google:{apiKey:await pn(e.apiKey||n.googleApiKey),model:r,safetySettings:djt,baseUrl:e.baseUrl},xai:{apiKey:await pn(e.apiKey||n.xaiApiKey),model:r},openrouterai:{modelName:r,apiKey:await pn(e.apiKey||n.openRouterAiApiKey),configuration:{baseURL:e.baseUrl||"https://openrouter.ai/api/v1",fetch:e.enableCors?fo:void 0,defaultHeaders:{"HTTP-Referer":"https://obsidiancopilot.com","X-Title":"Obsidian Copilot"}},enableReasoning:e.capabilities?.includes("reasoning")??!1,reasoningEffort:e.capabilities?.includes("reasoning")&&e.reasoningEffort?e.reasoningEffort:void 0,enablePromptCaching:e.enablePromptCaching??!0},groq:{apiKey:await pn(e.apiKey||n.groqApiKey),model:r},ollama:{model:r,baseUrl:e.baseUrl||"http://localhost:11434",headers:{Authorization:`Bearer ${await pn(e.apiKey||"default-key")}`},fetch:e.enableCors?fo:void 0,think:e.capabilities?.includes("reasoning")??!1,repeatPenalty:1.1,numCtx:e.numCtx??ZE},"lm-studio":{modelName:r,apiKey:e.apiKey||"default-key",streamUsage:e.streamUsage??!1,configuration:{baseURL:e.baseUrl||"http://localhost:1234/v1",fetch:e.enableCors?fo:void 0},enableReasoning:e.capabilities?.includes("reasoning")??!1,reasoningEffort:e.capabilities?.includes("reasoning")&&e.reasoningEffort?e.reasoningEffort:void 0},"3rd party (openai-format)":{modelName:r,apiKey:await pn(e.apiKey||n.openAIApiKey),streamUsage:e.streamUsage??!1,configuration:{baseURL:e.baseUrl,fetch:e.enableCors?fo:void 0,defaultHeaders:{"dangerously-allow-browser":"true"}},...this.getOpenAISpecialConfig(r,e.maxTokens??n.maxTokens,e.temperature??n.temperature,e)},siliconflow:{modelName:r,apiKey:await pn(e.apiKey||n.siliconflowApiKey),configuration:{baseURL:e.baseUrl||Cu.siliconflow.host,fetch:e.enableCors?fo:void 0},...this.getOpenAISpecialConfig(r,e.maxTokens??n.maxTokens,e.temperature??n.temperature,e)},"copilot-plus":{modelName:r,apiKey:await pn(n.plusLicenseKey),configuration:{baseURL:jy,fetch:fo}},mistralai:{modelName:r,apiKey:await pn(e.apiKey||n.mistralApiKey),configuration:{baseURL:e.baseUrl||Cu.mistralai.host,fetch:e.enableCors?fo:void 0}},deepseek:{modelName:r,apiKey:await pn(e.apiKey||n.deepseekApiKey),configuration:{baseURL:e.baseUrl||Cu.deepseek.host,fetch:e.enableCors?fo:void 0}},"amazon-bedrock":{},"github-copilot":{modelName:r,fetchImplementation:e.enableCors?Qy:void 0}}[e.provider]||{};e.provider==="amazon-bedrock"&&(d=await this.buildBedrockConfig(e,r,n,l,a));let f=this.getProviderSpecificParams(e.provider,e);return{...c,...d,...f,...{maxTokens:l}}}getOpenAISpecialConfig(e,n,r,o){let i=q(),s=AA(e),a=this.getTemperatureForModel(s,o||{},i),l={maxTokens:n,temperature:a};if((s.isOSeries||s.isGPT5)&&o?.reasoningEffort&&(l.reasoning={effort:o.reasoningEffort},s.isGPT5&&o?.verbosity&&o?.provider!=="azure openai")){let c=o.verbosity;l.text={verbosity:c}}return l}async buildBedrockConfig(e,n,r,o,i){let s=e.apiKey||r.amazonBedrockApiKey;if(!s)throw new Error("Amazon Bedrock API key is not configured. Provide a key in Settings > API Keys or the model definition.");let a=await pn(s),l=e.bedrockRegion?.trim(),c=r.amazonBedrockRegion?.trim(),u=l||c||"us-east-1",d=e.baseUrl?.trim(),p=(d?d.replace(/\/+$/,""):void 0)||`https://bedrock-runtime.${u}.amazonaws.com`,m=encodeURIComponent(n),h=`${p}/model/${m}/invoke`,g=`${p}/model/${m}/invoke-with-response-stream`,y=e.enableCors?fo:void 0,v=/(^|\.)anthropic\./.test(n)?"bedrock-2023-05-31":void 0,x=e.capabilities?.includes("reasoning")??!1;return{modelName:n,modelId:n,apiKey:a,endpoint:h,streamEndpoint:g,defaultMaxTokens:o,defaultTemperature:i,defaultTopP:e.topP,anthropicVersion:v,enableThinking:x,fetchImplementation:y,streaming:e.stream??!0}}getProviderSpecificParams(e,n){let r={};return n.topP!==void 0&&["openai","azure openai","anthropic","google","openrouterai","ollama","lm-studio","3rd party (openai-format)","mistralai","deepseek","siliconflow"].includes(e)&&(r.topP=n.topP),n.frequencyPenalty!==void 0&&["openai","azure openai","openrouterai","ollama","lm-studio","3rd party (openai-format)","mistralai","deepseek","siliconflow"].includes(e)&&(r.frequencyPenalty=n.frequencyPenalty),r}buildModelMap(){let e=q().activeModels;as.modelMap={};let n=as.modelMap;(e??Gh).forEach(o=>{if(o.enabled){if(!Object.values(Ec).contains(o.provider)){console.warn(`Unknown provider: ${o.provider} for model: ${o.name}`);return}let i=this.getProviderConstructor(o),s=this.hasProviderCredentials(o),a=ln(o);n[a]={hasApiKey:s,AIConstructor:i,vendor:o.provider}}})}hasProviderCredentials(e){if(e.provider==="amazon-bedrock"){let r=q();return!!(e.apiKey||r.amazonBedrockApiKey)}let n=this.providerApiKeyMap[e.provider];return n?!!(e.apiKey||n()):!!e.apiKey}getProviderConstructor(e){let n=fjt[e.provider];if(!n)throw console.warn(`Unknown provider: ${e.provider} for model: ${e.name}`),new Error(`Unknown provider: ${e.provider} for model: ${e.name}`);return n}getChatModel(){if(!as.chatModel)throw new Error("No valid chat model available. Please check your API key settings.");return as.chatModel}isModelConfigValid(e,n){let r=ln(e),o=as.modelMap[r];return!(!o||!o.hasApiKey||e.plusExclusive&&!P5e())}resolveModelForTemperatureOverride(){let e=q();try{let n=Iu();if(n){let r=$f(n,e.activeModels);if(this.isModelConfigValid(r,e))return r}}catch{}for(let n of e.activeModels)if(n.enabled&&!n.believerExclusive&&this.isModelConfigValid(n,e))return n;throw new Error("No valid chat model available for temperature override. Please check your API key settings and ensure at least one model is properly configured.")}async getChatModelWithTemperature(e){let r={...this.resolveModelForTemperatureOverride(),temperature:e};return await this.createModelInstance(r)}async setChatModel(e){try{let n=await this.createModelInstance(e);as.chatModel=n,AA(e.name).isGPT5&&(e.provider==="openai"||e.provider==="3rd party (openai-format)")&&k(`Chat model set with Responses API for GPT-5: ${e.name}`)}catch(n){throw z(n),n}}async createModelInstance(e){let n=ln(e),r=as.modelMap[n];if(!r)throw new Error(`No model found for: ${n}`);if(!r.hasApiKey){let c=`API key is not provided for the model: ${n}.`;throw e.provider==="copilot-plus"?new DS("Copilot Plus license key is not configured. Please enter your license key in the Copilot Plus section at the top of Basic Settings."):new fD(c)}let o=await this.getModelConfig(e),i=AA(e.name),s={...o},a=Bte(e);if(i.isGPT5&&(r.vendor==="openai"||r.vendor==="3rd party (openai-format)")&&(s.useResponsesApi=!0,k(`Enabling Responses API for GPT-5 model: ${e.name} (${r.vendor})`)),a&&(s.useResponsesApi=!0,k(`Enabling Responses API for GitHub Copilot model: ${e.name}`)),e.provider==="lm-studio"&&e.useResponsesApi!==!1){let c=new az(s);return k(`[ChatModelManager] Using Responses API for LM Studio model: ${e.name}`),c}return a?new dz(s):new r.AIConstructor(s)}validateChatModel(e){return e!=null}estimateTokens(e){return e?Math.ceil(e.length/4):0}async countTokens(e){return as.chatModel?.getNumTokens(e)??this.estimateTokens(e)}validateCurrentModel(){if(!as.chatModel)return;let e=Iu();if(!e)return;as.modelMap[e]?.hasApiKey||(as.chatModel=null,k("Failed to reinitialize model due to missing API key"))}async ping(e){let n=async r=>{let o={...e,enableCors:r},i=await this.getModelConfig(o),{streaming:s,maxTokens:a,maxCompletionTokens:l,...c}=i,u=AA(e.name),f={maxTokens:u.isThinkingEnabled?4096:30},p={...c,...f},m=Bte(e);u.isGPT5&&(e.provider==="openai"||e.provider==="3rd party (openai-format)")&&(p.useResponsesApi=!0),m&&(p.useResponsesApi=!0),await(e.provider==="lm-studio"&&e.useResponsesApi!==!1?new az(p):m?new dz(p):new(this.getProviderConstructor(o))(p)).invoke([{role:"user",content:"hello"}],{timeout:8e3})};try{return await n(!1),!0}catch(r){k("First ping attempt failed, retrying with CORS enabled.");try{return await n(!0),new E9e.Notice("Connection successful, but requires CORS to be enabled. Please enable CORS for this model once you add it above."),!0}catch(o){let i=`
without CORS Error: `+Xt(r)+`
with CORS Error: `+Xt(o);throw new Error(i)}}}findModelByName(e){return q().activeModels.find(r=>r.name===e)}};as.ANTHROPIC_THINKING_BUDGET_TOKENS=2048,as.REASONING_MODEL_TEMPERATURE=1;Np=as});var k9e={};zn(k9e,{TieredLexicalRetriever:()=>ah});async function pjt(){try{if(!Wve){let e=await Promise.resolve().then(()=>(eP(),Vve));Wve=()=>e.default.getInstance()}return Wve().getChatModel()}catch{return null}}var Hve,Wve,ah,fz=C(()=>{ye();Se();qe();iv();lO();Hve=require("obsidian");iB();N0();Wve=null;ah=class extends ay{constructor(n,r){super();this.app=n;this.options=r;this.lc_namespace=["tiered_lexical_retriever"];this.lastQueryExpansion=null;this.searchCore=new VG(n,pjt),this.chunkManager=PC(n)}getLastQueryExpansion(){return this.lastQueryExpansion}async getRelevantDocuments(n,r){try{let i=Df(n,this.app.vault).map(f=>f.basename),s=[...new Set([...this.options.salientTerms,...i])];q().debug&&k("TieredLexicalRetriever: Starting search",{query:n,salientTerms:s,maxK:this.options.maxK});let a=q(),l=await this.searchCore.retrieve(n,{maxResults:this.options.maxK,salientTerms:s,enableLexicalBoosts:a.enableLexicalBoosts,preExpandedQuery:this.options.preExpandedQuery}),c=l.results;this.lastQueryExpansion=l.queryExpansion;let u=await this.convertToDocuments(c),d=this.sortResults(u);return q().debug&&k("TieredLexicalRetriever: Search complete",{totalResults:d.length,searchResults:c.length}),d}catch(o){return ee("TieredLexicalRetriever: Error during search",o),[]}}async convertToDocuments(n){let r=[];for(let o of n)try{if(o.id.includes("#")){let[s]=o.id.split("#"),a=this.app.vault.getAbstractFileByPath(s);if(!a||!(a instanceof Hve.TFile))continue;let l="",c=this.chunkManager;if(typeof c.getChunkText=="function"?l=await c.getChunkText(o.id):typeof c.getChunkTextSync=="function"&&(l=c.getChunkTextSync(o.id)||""),!l)continue;let u=this.app.metadataCache.getFileCache(a);r.push(new fi({pageContent:l,metadata:{path:s,chunkId:o.id,title:a.basename,mtime:a.stat.mtime,ctime:a.stat.ctime,tags:u?.tags?.map(d=>d.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"chunk-v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!0}}))}else{let s=this.app.vault.getAbstractFileByPath(o.id);if(!s||!(s instanceof Hve.TFile))continue;let a=await this.app.vault.cachedRead(s);if(!a)continue;let l=this.app.metadataCache.getFileCache(s);r.push(new fi({pageContent:a,metadata:{path:o.id,title:s.basename,mtime:s.stat.mtime,ctime:s.stat.ctime,tags:l?.tags?.map(c=>c.tag)||[],score:o.score,rerank_score:o.score,engine:o.engine||"v3",includeInContext:o.score>(this.options.minSimilarityScore||.1),explanation:o.explanation,isChunk:!1}}))}}catch(i){ee(`TieredLexicalRetriever: Failed to convert result ${o.id}`,i)}return k(`TieredLexicalRetriever: Converted ${r.length} results to Documents`),r}sortResults(n){return n.sort((r,o)=>{let i=r.metadata.score||0,a=(o.metadata.score||0)-i;if(Math.abs(a)>.01)return a;if(r.metadata.isChunk&&o.metadata.isChunk&&r.metadata.path===o.metadata.path){let l=parseInt(r.metadata.chunkId?.split("#")[1]||"0"),c=parseInt(o.metadata.chunkId?.split("#")[1]||"0");return l-c}return a})}}});var M9e={};zn(M9e,{MergedSemanticRetriever:()=>tP});var JC,tP,Kve=C(()=>{Nye();N0();fz();iv();lO();JC=class JC extends ay{constructor(n,r,o){super();this.app=n;this.options=r;this.lc_namespace=["merged_semantic_retriever"];this.originalMaxK=Math.max(1,r.maxK),this.returnAll=!!r.returnAll;let i=this.returnAll?ni:Math.min(this.originalMaxK*2,ni),s={...r,maxK:i,returnAll:this.returnAll};this.lexicalRetriever=new ah(n,s);let a=this.returnAll?ni:Math.min(this.originalMaxK*2,ni);this.semanticRetriever=o||new vB({minSimilarityScore:r.minSimilarityScore??.1,maxK:a,salientTerms:r.salientTerms,timeRange:r.timeRange,textWeight:r.textWeight,returnAll:this.returnAll,useRerankerThreshold:r.useRerankerThreshold})}async getRelevantDocuments(n){let[r,o]=await Promise.all([this.lexicalRetriever.getRelevantDocuments(n),this.semanticRetriever.getRelevantDocuments(n)]),i=new Map;for(let l of r)this.insertResult(i,l,"lexical");for(let l of o)this.insertResult(i,l,"semantic");let s=Array.from(i.values()).sort((l,c)=>(c.metadata?.score??0)-(l.metadata?.score??0)),a=this.returnAll?ni:this.originalMaxK;return s.slice(0,a)}insertResult(n,r,o){let i=this.getDocumentKey(r),s=this.decorateDocument(r,o),a=n.get(i);if(!a){n.set(i,s);return}let l=a.metadata?.source,c=this.getDocumentScore(a),u=this.getDocumentScore(s);if(o==="lexical"){(l!=="lexical"||u>c)&&n.set(i,s);return}l!=="lexical"&&u>c&&n.set(i,s)}getDocumentKey(n){let r=n.metadata??{};return r.chunkId||r.path||r.id||r.title||`${n.pageContent.slice(0,64)}::${n.pageContent.length}`}decorateDocument(n,r){let o={...n.metadata??{},source:r},i=this.extractBaseScore(o),s=r==="lexical"?JC.LEXICAL_WEIGHT:JC.SEMANTIC_WEIGHT,a=i*s;return r==="lexical"&&this.hasTagMatch(o)&&(a*=JC.TAG_MATCH_BOOST),o.score=a,o.rerank_score=a,new fi({pageContent:n.pageContent,metadata:o})}extractBaseScore(n){let r=[n?.rerank_score,n?.score];for(let o of r)if(typeof o=="number"&&!Number.isNaN(o))return o;return 0}getDocumentScore(n){let r=n.metadata?.score;return typeof r=="number"&&!Number.isNaN(r)?r:0}hasTagMatch(n){let r=n?.explanation;if(!r)return!1;let o=r.lexicalMatches;return Array.isArray(o)?o.some(i=>i?.field==="tags"):!1}};JC.LEXICAL_WEIGHT=1,JC.SEMANTIC_WEIGHT=1,JC.TAG_MATCH_BOOST=1.1;tP=JC});var O9e={};zn(O9e,{FilterRetriever:()=>XC});var N9e,XC,U8=C(()=>{ye();Se();fc();qe();iv();N9e=require("obsidian");N0();XC=class{constructor(e,n){this.app=e;this.options=n}async getRelevantDocuments(e){if(this.options.timeRange)return this.getTimeRangeDocuments(e);let n=Df(e,this.app.vault),r=await this.getTitleMatches(n),o=await this.getTagMatches(this.resolveTagTerms(e));return this.combineGuaranteedMatches(r,o)}hasTimeRange(){return this.options.timeRange!==void 0}async getTimeRangeDocuments(e){if(!this.options.timeRange)return[];let{startTime:n,endTime:r}=this.options.timeRange,o=this.generateDailyNoteDateRange(n,r);q().debug&&k("FilterRetriever: Generated daily note titles",{startTime:new Date(n).toISOString(),endTime:new Date(r).toISOString(),titlesCount:o.length,firstTitle:o[0],lastTitle:o[o.length-1]});let{inclusions:i,exclusions:s}=Bo(),a=o.join(", "),l=Df(a,this.app.vault).filter(y=>Qr(y,i,s)),u=(await this.getTitleMatches(l)).map(y=>(y.metadata.includeInContext=!0,y)),d=this.app.vault.getMarkdownFiles().filter(y=>Qr(y,i,s)),f=[],p=this.options.returnAll?ni:Math.min(this.options.maxK,ni);for(let y of d)if(y.stat.mtime>=n&&y.stat.mtime<=r){if(l.some(w=>w.path===y.path))continue;if(f.length>=p)break;try{let w=await this.app.vault.cachedRead(y),v=this.app.metadataCache.getFileCache(y),x=(Date.now()-y.stat.mtime)/(1e3*60*60*24),b=Math.max(.3,Math.min(1,1-x/30));f.push(new fi({pageContent:w,metadata:{path:y.path,title:y.basename,mtime:y.stat.mtime,ctime:y.stat.ctime,tags:v?.tags?.map(_=>_.tag)||[],includeInContext:!0,score:b,rerank_score:b,source:"time-filtered"}}))}catch(w){ee(`FilterRetriever: Failed to read file ${y.path}`,w)}}let m=new Map;for(let y of u)m.set(y.metadata.path,y);for(let y of f)m.has(y.metadata.path)||m.set(y.metadata.path,{...y,metadata:{...y.metadata,includeInContext:!0}});let h=this.options.returnAll?ni:this.options.maxK,g=Array.from(m.values()).sort((y,w)=>{let v=y.metadata.score||0;return(w.metadata.score||0)-v}).slice(0,h);return q().debug&&k("FilterRetriever: Time range search complete",{timeRange:this.options.timeRange,dailyNotesFound:l.length,timeFilteredDocs:f.length,totalResults:g.length}),g}resolveTagTerms(e){let n=new Set;for(let r of this.options.salientTerms??[])typeof r=="string"&&r.startsWith("#")&&n.add(r.toLowerCase());if(n.size===0)for(let r of this.extractTagsFromQuery(e))n.add(r);return Array.from(n)}extractTagsFromQuery(e){if(!e)return[];let n=null;try{n=e.match(/#[\p{L}\p{N}_/-]+/gu)}catch{n=e.match(/#[a-z0-9_/-]+/g)}if(!n)return[];let r=new Set;for(let o of n){let i=o.trim();i.length<=1||r.add(i.toLowerCase())}return Array.from(r)}generateDailyNoteDateRange(e,n){let r=[],o=new Date(e),i=new Date(n),s=365;Math.ceil((n-e)/(1e3*60*60*24))>s&&(ee(`FilterRetriever: Date range exceeds ${s} days, limiting to recent ${s} days`),o.setTime(i.getTime()-s*24*60*60*1e3));let l=new Date(o);for(;l<=i;)r.push(`[[${l.toLocaleDateString("en-CA")}]]`),l.setDate(l.getDate()+1);return r}async getTitleMatches(e){let n=[];for(let r of e)if(!nB(r))try{let o=await this.app.vault.cachedRead(r),i=this.app.metadataCache.getFileCache(r);n.push(new fi({pageContent:o,metadata:{path:r.path,title:r.basename,mtime:r.stat.mtime,ctime:r.stat.ctime,tags:i?.tags?.map(s=>s.tag)||[],includeInContext:!0,score:1,rerank_score:1,source:"title-match"}}))}catch(o){ee(`FilterRetriever: Failed to read title-matched file ${r.path}`,o)}return n}async getTagMatches(e){if(e.length===0)return[];let{inclusions:n,exclusions:r}=Bo(),o=this.app.vault.getMarkdownFiles(),i=[],s=this.options.returnAll?ni:this.options.maxK;for(let a of o){if(i.length>=s)break;if(!Qr(a,n,r)||nB(a))continue;let l=this.app.metadataCache.getFileCache(a);if(!l)continue;let c=(0,N9e.getAllTags)(l)??[];if(!(c.length===0||!c.some(d=>{let f=d.toLowerCase();return e.some(p=>f===p||f.startsWith(p+"/"))})))try{let d=await this.app.vault.cachedRead(a);i.push(new fi({pageContent:d,metadata:{path:a.path,title:a.basename,mtime:a.stat.mtime,ctime:a.stat.ctime,tags:c,includeInContext:!0,score:1,rerank_score:1,source:"tag-match"}}))}catch(d){ee(`FilterRetriever: Failed to read tag-matched file ${a.path}`,d)}}return i}combineGuaranteedMatches(...e){let n=new Set,r=[];for(let o of e)for(let i of o){let s=i.metadata.path;n.has(s)||(n.add(s),r.push(i))}return r}}});var R9e={};zn(R9e,{mergeFilterAndSearchResults:()=>nR});function nR(t,e){let n=new Set;for(let o of t)o.metadata?.path&&n.add(o.metadata.path);let r=e.filter(o=>{let i=o.metadata?.path;return!i||!n.has(i)});return{filterResults:t,searchResults:r}}var B8=C(()=>{});var MYe=Tt((dxe,fxe)=>{(function(t,e){typeof dxe=="object"&&typeof fxe<"u"?fxe.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_quarterOfYear=e()})(dxe,function(){"use strict";var t="month",e="quarter";return function(n,r){var o=r.prototype;o.quarter=function(a){return this.$utils().u(a)?Math.ceil((this.month()+1)/3):this.month(this.month()%3+3*(a-1))};var i=o.add;o.add=function(a,l){return a=Number(a),this.$utils().p(l)===e?this.add(3*a,t):i.bind(this)(a,l)};var s=o.startOf;o.startOf=function(a,l){var c=this.$utils(),u=!!c.u(l)||l;if(c.p(a)===e){var d=this.quarter()-1;return u?this.month(3*d).startOf(t).startOf("day"):this.month(3*d+2).endOf(t).endOf("day")}return s.bind(this)(a,l)}}})});var i_=Tt((pxe,mxe)=>{(function(t,e){typeof pxe=="object"&&typeof mxe<"u"?mxe.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(pxe,function(){"use strict";var t=1e3,e=6e4,n=36e5,r="millisecond",o="second",i="minute",s="hour",a="day",l="week",c="month",u="quarter",d="year",f="date",p="Invalid Date",m=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|Y{1,4}|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,g={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(D){var $=["th","st","nd","rd"],B=D%100;return"["+D+($[(B-20)%10]||$[B]||$[0])+"]"}},y=function(D,$,B){var W=String(D);return!W||W.length>=$?D:""+Array($+1-W.length).join(B)+D},w={s:y,z:function(D){var $=-D.utcOffset(),B=Math.abs($),W=Math.floor(B/60),F=B%60;return($<=0?"+":"-")+y(W,2,"0")+":"+y(F,2,"0")},m:function D($,B){if($.date()<B.date())return-D(B,$);var W=12*(B.year()-$.year())+(B.month()-$.month()),F=$.clone().add(W,c),Z=B-F<0,V=$.clone().add(W+(Z?-1:1),c);return+(-(W+(B-F)/(Z?F-V:V-F))||0)},a:function(D){return D<0?Math.ceil(D)||0:Math.floor(D)},p:function(D){return{M:c,y:d,w:l,d:a,D:f,h:s,m:i,s:o,ms:r,Q:u}[D]||String(D||"").toLowerCase().replace(/s$/,"")},u:function(D){return D===void 0}},v="en",x={};x[v]=g;var b="$isDayjsObject",_=function(D){return D instanceof A||!(!D||!D[b])},T=function D($,B,W){var F;if(!$)return v;if(typeof $=="string"){var Z=$.toLowerCase();x[Z]&&(F=Z),B&&(x[Z]=B,F=Z);var V=$.split("-");if(!F&&V.length>1)return D(V[0])}else{var H=$.name;x[H]=$,F=H}return!W&&F&&(v=F),F||!W&&v},S=function(D,$){if(_(D))return D.clone();var B=typeof $=="object"?$:{};return B.date=D,B.args=arguments,new A(B)},P=w;P.l=T,P.i=_,P.w=function(D,$){return S(D,{locale:$.$L,utc:$.$u,x:$.$x,$offset:$.$offset})};var A=function(){function D(B){this.$L=T(B.locale,null,!0),this.parse(B),this.$x=this.$x||B.x||{},this[b]=!0}var $=D.prototype;return $.parse=function(B){this.$d=function(W){var F=W.date,Z=W.utc;if(F===null)return new Date(NaN);if(P.u(F))return new Date;if(F instanceof Date)return new Date(F);if(typeof F=="string"&&!/Z$/i.test(F)){var V=F.match(m);if(V){var H=V[2]-1||0,te=(V[7]||"0").substring(0,3);return Z?new Date(Date.UTC(V[1],H,V[3]||1,V[4]||0,V[5]||0,V[6]||0,te)):new Date(V[1],H,V[3]||1,V[4]||0,V[5]||0,V[6]||0,te)}}return new Date(F)}(B),this.init()},$.init=function(){var B=this.$d;this.$y=B.getFullYear(),this.$M=B.getMonth(),this.$D=B.getDate(),this.$W=B.getDay(),this.$H=B.getHours(),this.$m=B.getMinutes(),this.$s=B.getSeconds(),this.$ms=B.getMilliseconds()},$.$utils=function(){return P},$.isValid=function(){return this.$d.toString()!==p},$.isSame=function(B,W){var F=S(B);return this.startOf(W)<=F&&F<=this.endOf(W)},$.isAfter=function(B,W){return S(B)<this.startOf(W)},$.isBefore=function(B,W){return this.endOf(W)<S(B)},$.$g=function(B,W,F){return P.u(B)?this[W]:this.set(F,B)},$.unix=function(){return Math.floor(this.valueOf()/1e3)},$.valueOf=function(){return this.$d.getTime()},$.startOf=function(B,W){var F=this,Z=!!P.u(W)||W,V=P.p(B),H=function(E,R){var L=P.w(F.$u?Date.UTC(F.$y,R,E):new Date(F.$y,R,E),F);return Z?L:L.endOf(a)},te=function(E,R){return P.w(F.toDate()[E].apply(F.toDate("s"),(Z?[0,0,0,0]:[23,59,59,999]).slice(R)),F)},fe=this.$W,me=this.$M,j=this.$D,G="set"+(this.$u?"UTC":"");switch(V){case d:return Z?H(1,0):H(31,11);case c:return Z?H(1,me):H(0,me+1);case l:var J=this.$locale().weekStart||0,M=(fe<J?fe+7:fe)-J;return H(Z?j-M:j+(6-M),me);case a:case f:return te(G+"Hours",0);case s:return te(G+"Minutes",1);case i:return te(G+"Seconds",2);case o:return te(G+"Milliseconds",3);default:return this.clone()}},$.endOf=function(B){return this.startOf(B,!1)},$.$set=function(B,W){var F,Z=P.p(B),V="set"+(this.$u?"UTC":""),H=(F={},F[a]=V+"Date",F[f]=V+"Date",F[c]=V+"Month",F[d]=V+"FullYear",F[s]=V+"Hours",F[i]=V+"Minutes",F[o]=V+"Seconds",F[r]=V+"Milliseconds",F)[Z],te=Z===a?this.$D+(W-this.$W):W;if(Z===c||Z===d){var fe=this.clone().set(f,1);fe.$d[H](te),fe.init(),this.$d=fe.set(f,Math.min(this.$D,fe.daysInMonth())).$d}else H&&this.$d[H](te);return this.init(),this},$.set=function(B,W){return this.clone().$set(B,W)},$.get=function(B){return this[P.p(B)]()},$.add=function(B,W){var F,Z=this;B=Number(B);var V=P.p(W),H=function(me){var j=S(Z);return P.w(j.date(j.date()+Math.round(me*B)),Z)};if(V===c)return this.set(c,this.$M+B);if(V===d)return this.set(d,this.$y+B);if(V===a)return H(1);if(V===l)return H(7);var te=(F={},F[i]=e,F[s]=n,F[o]=t,F)[V]||1,fe=this.$d.getTime()+B*te;return P.w(fe,this)},$.subtract=function(B,W){return this.add(-1*B,W)},$.format=function(B){var W=this,F=this.$locale();if(!this.isValid())return F.invalidDate||p;var Z=B||"YYYY-MM-DDTHH:mm:ssZ",V=P.z(this),H=this.$H,te=this.$m,fe=this.$M,me=F.weekdays,j=F.months,G=F.meridiem,J=function(R,L,K,Y){return R&&(R[L]||R(W,Z))||K[L].slice(0,Y)},M=function(R){return P.s(H%12||12,R,"0")},E=G||function(R,L,K){var Y=R<12?"AM":"PM";return K?Y.toLowerCase():Y};return Z.replace(h,function(R,L){return L||function(K){switch(K){case"YY":return String(W.$y).slice(-2);case"YYYY":return P.s(W.$y,4,"0");case"M":return fe+1;case"MM":return P.s(fe+1,2,"0");case"MMM":return J(F.monthsShort,fe,j,3);case"MMMM":return J(j,fe);case"D":return W.$D;case"DD":return P.s(W.$D,2,"0");case"d":return String(W.$W);case"dd":return J(F.weekdaysMin,W.$W,me,2);case"ddd":return J(F.weekdaysShort,W.$W,me,3);case"dddd":return me[W.$W];case"H":return String(H);case"HH":return P.s(H,2,"0");case"h":return M(1);case"hh":return M(2);case"a":return E(H,te,!0);case"A":return E(H,te,!1);case"m":return String(te);case"mm":return P.s(te,2,"0");case"s":return String(W.$s);case"ss":return P.s(W.$s,2,"0");case"SSS":return P.s(W.$ms,3,"0");case"Z":return V}return null}(R)||V.replace(":","")})},$.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},$.diff=function(B,W,F){var Z,V=this,H=P.p(W),te=S(B),fe=(te.utcOffset()-this.utcOffset())*e,me=this-te,j=function(){return P.m(V,te)};switch(H){case d:Z=j()/12;break;case c:Z=j();break;case u:Z=j()/3;break;case l:Z=(me-fe)/6048e5;break;case a:Z=(me-fe)/864e5;break;case s:Z=me/n;break;case i:Z=me/e;break;case o:Z=me/t;break;default:Z=me}return F?Z:P.a(Z)},$.daysInMonth=function(){return this.endOf(c).$D},$.$locale=function(){return x[this.$L]},$.locale=function(B,W){if(!B)return this.$L;var F=this.clone(),Z=T(B,W,!0);return Z&&(F.$L=Z),F},$.clone=function(){return P.w(this.$d,this)},$.toDate=function(){return new Date(this.valueOf())},$.toJSON=function(){return this.isValid()?this.toISOString():null},$.toISOString=function(){return this.$d.toISOString()},$.toString=function(){return this.$d.toUTCString()},D}(),O=A.prototype;return S.prototype=O,[["$ms",r],["$s",o],["$m",i],["$H",s],["$W",a],["$M",c],["$y",d],["$D",f]].forEach(function(D){O[D[1]]=function($){return this.$g($,D[0],D[1])}}),S.extend=function(D,$){return D.$i||(D($,A,S),D.$i=!0),S},S.locale=T,S.isDayjs=_,S.unix=function(D){return S(1e3*D)},S.en=x[v],S.Ls=x,S.p={},S})});var fy,wR=C(()=>{Ra();fy=class extends gr{constructor(e){super(e);I(this,"lc_serializable",!0);I(this,"lc_namespace",["langchain_core","prompts",this._getPromptType()]);I(this,"inputVariables");I(this,"outputParser");I(this,"partialVariables");I(this,"metadata");I(this,"tags");let{inputVariables:n}=e;if(n.includes("stop"))throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename.");Object.assign(this,e)}get lc_attributes(){return{partialVariables:void 0}}async mergePartialAndUserVariables(e){let n=this.partialVariables??{},r={};for(let[o,i]of Object.entries(n))typeof i=="string"?r[o]=i:r[o]=await i();return{...r,...e}}async invoke(e,n){let r={...this.metadata,...n?.metadata},o=[...this.tags??[],...n?.tags??[]];return this._callWithConfig(i=>this.formatPromptValue(i),e,{...n,tags:o,metadata:r,runType:"prompt"})}}});var cP,rj=C(()=>{tU();wR();cP=class extends fy{async formatPromptValue(t){return new o5(await this.format(t))}}});function zxe(t){return typeof t=="function"}function bWt(t){return xR(t)?"array":typeof t}function Bxe(t){return t.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function n7e(t,e){return t!=null&&typeof t=="object"&&e in t}function CWt(t,e){return t!=null&&typeof t!="object"&&t.hasOwnProperty&&t.hasOwnProperty(e)}function SWt(t,e){return _Wt.call(t,e)}function IWt(t){return!SWt(TWt,t)}function EWt(t){return String(t).replace(/[&<>"'`=\/]/g,function(n){return PWt[n]})}function OWt(t,e){if(!t)return[];var n=!1,r=[],o=[],i=[],s=!1,a=!1,l="",c=0;function u(){if(s&&!a)for(;i.length;)delete o[i.pop()];else i=[];s=!1,a=!1}var d,f,p;function m(S){if(typeof S=="string"&&(S=S.split(kWt,2)),!xR(S)||S.length!==2)throw new Error("Invalid tags: "+S);d=new RegExp(Bxe(S[0])+"\\s*"),f=new RegExp("\\s*"+Bxe(S[1])),p=new RegExp("\\s*"+Bxe("}"+S[1]))}m(e||Dp.tags);for(var h=new ij(t),g,y,w,v,x,b;!h.eos();){if(g=h.pos,w=h.scanUntil(d),w)for(var _=0,T=w.length;_<T;++_)v=w.charAt(_),IWt(v)?(i.push(o.length),l+=v):(a=!0,n=!0,l+=" "),o.push(["text",v,g,g+1]),g+=1,v===`
`&&(u(),l="",c=0,n=!1);if(!h.scan(d))break;if(s=!0,y=h.scan(NWt)||"name",h.scan(AWt),y==="="?(w=h.scanUntil(r7e),h.scan(r7e),h.scanUntil(f)):y==="{"?(w=h.scanUntil(p),h.scan(MWt),h.scanUntil(f),y="&"):w=h.scanUntil(f),!h.scan(f))throw new Error("Unclosed tag at "+h.pos);if(y==">"?x=[y,w,g,h.pos,l,c,n]:x=[y,w,g,h.pos],c++,o.push(x),y==="#"||y==="^")r.push(x);else if(y==="/"){if(b=r.pop(),!b)throw new Error('Unopened section "'+w+'" at '+g);if(b[1]!==w)throw new Error('Unclosed section "'+b[1]+'" at '+g)}else y==="name"||y==="{"||y==="&"?a=!0:y==="="&&m(w)}if(u(),b=r.pop(),b)throw new Error('Unclosed section "'+b[1]+'" at '+h.pos);return LWt(RWt(o))}function RWt(t){for(var e=[],n,r,o=0,i=t.length;o<i;++o)n=t[o],n&&(n[0]==="text"&&r&&r[0]==="text"?(r[1]+=n[1],r[3]=n[3]):(e.push(n),r=n));return e}function LWt(t){for(var e=[],n=e,r=[],o,i,s=0,a=t.length;s<a;++s)switch(o=t[s],o[0]){case"#":case"^":n.push(o),r.push(o),n=o[4]=[];break;case"/":i=r.pop(),i[5]=o[2],n=r.length>0?r[r.length-1][4]:e;break;default:n.push(o)}return e}function ij(t){this.string=t,this.tail=t,this.pos=0}function vR(t,e){this.view=t,this.cache={".":this.view},this.parent=e}function ru(){this.templateCache={_cache:{},set:function(e,n){this._cache[e]=n},get:function(e){return this._cache[e]},clear:function(){this._cache={}}}}var xWt,xR,_Wt,TWt,PWt,AWt,kWt,r7e,MWt,NWt,Dp,oj,w9,o7e=C(()=>{xWt=Object.prototype.toString,xR=Array.isArray||function(e){return xWt.call(e)==="[object Array]"};_Wt=RegExp.prototype.test;TWt=/\S/;PWt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};AWt=/\s*/,kWt=/\s+/,r7e=/\s*=/,MWt=/\s*\}/,NWt=/#|\^|\/|>|\{|&|=|!/;ij.prototype.eos=function(){return this.tail===""};ij.prototype.scan=function(e){var n=this.tail.match(e);if(!n||n.index!==0)return"";var r=n[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};ij.prototype.scanUntil=function(e){var n=this.tail.search(e),r;switch(n){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,n),this.tail=this.tail.substring(n)}return this.pos+=r.length,r};vR.prototype.push=function(e){return new vR(e,this)};vR.prototype.lookup=function(e){var n=this.cache,r;if(n.hasOwnProperty(e))r=n[e];else{for(var o=this,i,s,a,l=!1;o;){if(e.indexOf(".")>0)for(i=o.view,s=e.split("."),a=0;i!=null&&a<s.length;)a===s.length-1&&(l=n7e(i,s[a])||CWt(i,s[a])),i=i[s[a++]];else i=o.view[e],l=n7e(o.view,e);if(l){r=i;break}o=o.parent}n[e]=r}return zxe(r)&&(r=r.call(this.view)),r};ru.prototype.clearCache=function(){typeof this.templateCache<"u"&&this.templateCache.clear()};ru.prototype.parse=function(e,n){var r=this.templateCache,o=e+":"+(n||Dp.tags).join(":"),i=typeof r<"u",s=i?r.get(o):void 0;return s==null&&(s=OWt(e,n),i&&r.set(o,s)),s};ru.prototype.render=function(e,n,r,o){var i=this.getConfigTags(o),s=this.parse(e,i),a=n instanceof vR?n:new vR(n,void 0);return this.renderTokens(s,a,r,e,o)};ru.prototype.renderTokens=function(e,n,r,o,i){for(var s="",a,l,c,u=0,d=e.length;u<d;++u)c=void 0,a=e[u],l=a[0],l==="#"?c=this.renderSection(a,n,r,o,i):l==="^"?c=this.renderInverted(a,n,r,o,i):l===">"?c=this.renderPartial(a,n,r,i):l==="&"?c=this.unescapedValue(a,n):l==="name"?c=this.escapedValue(a,n,i):l==="text"&&(c=this.rawValue(a)),c!==void 0&&(s+=c);return s};ru.prototype.renderSection=function(e,n,r,o,i){var s=this,a="",l=n.lookup(e[1]);function c(f){return s.render(f,n,r,i)}if(l){if(xR(l))for(var u=0,d=l.length;u<d;++u)a+=this.renderTokens(e[4],n.push(l[u]),r,o,i);else if(typeof l=="object"||typeof l=="string"||typeof l=="number")a+=this.renderTokens(e[4],n.push(l),r,o,i);else if(zxe(l)){if(typeof o!="string")throw new Error("Cannot use higher-order sections without the original template");l=l.call(n.view,o.slice(e[3],e[5]),c),l!=null&&(a+=l)}else a+=this.renderTokens(e[4],n,r,o,i);return a}};ru.prototype.renderInverted=function(e,n,r,o,i){var s=n.lookup(e[1]);if(!s||xR(s)&&s.length===0)return this.renderTokens(e[4],n,r,o,i)};ru.prototype.indentPartial=function(e,n,r){for(var o=n.replace(/[^ \t]/g,""),i=e.split(`
`),s=0;s<i.length;s++)i[s].length&&(s>0||!r)&&(i[s]=o+i[s]);return i.join(`
`)};ru.prototype.renderPartial=function(e,n,r,o){if(r){var i=this.getConfigTags(o),s=zxe(r)?r(e[1]):r[e[1]];if(s!=null){var a=e[6],l=e[5],c=e[4],u=s;l==0&&c&&(u=this.indentPartial(s,c,a));var d=this.parse(u,i);return this.renderTokens(d,n,r,u,o)}}};ru.prototype.unescapedValue=function(e,n){var r=n.lookup(e[1]);if(r!=null)return r};ru.prototype.escapedValue=function(e,n,r){var o=this.getConfigEscape(r)||Dp.escape,i=n.lookup(e[1]);if(i!=null)return typeof i=="number"&&o===Dp.escape?String(i):o(i)};ru.prototype.rawValue=function(e){return e[1]};ru.prototype.getConfigTags=function(e){return xR(e)?e:e&&typeof e=="object"?e.tags:void 0};ru.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!xR(e))return e.escape};Dp={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(t){oj.templateCache=t},get templateCache(){return oj.templateCache}},oj=new ru;Dp.clearCache=function(){return oj.clearCache()};Dp.parse=function(e,n){return oj.parse(e,n)};Dp.render=function(e,n,r,o){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+bWt(e)+'" was given as the first argument for mustache#render(template, view, partials)');return oj.render(e,n,r,o)};Dp.escape=EWt;Dp.Scanner=ij;Dp.Context=vR;Dp.Writer=ru;w9=Dp});function i7e(){w9.escape=t=>t}var bR,s7e,sj,a7e,l7e,v9,c7e,df,CR,_R,uP=C(()=>{JT();o7e();bR=t=>{let e=t.split(""),n=[],r=(i,s)=>{for(let a=s;a<e.length;a+=1)if(i.includes(e[a]))return a;return-1},o=0;for(;o<e.length;)if(e[o]==="{"&&o+1<e.length&&e[o+1]==="{")n.push({type:"literal",text:"{"}),o+=2;else if(e[o]==="}"&&o+1<e.length&&e[o+1]==="}")n.push({type:"literal",text:"}"}),o+=2;else if(e[o]==="{"){let i=r("}",o);if(i<0)throw new Error("Unclosed '{' in template.");n.push({type:"variable",name:e.slice(o+1,i).join("")}),o=i+1}else{if(e[o]==="}")throw new Error("Single '}' in template.");{let i=r("{}",o),s=(i<0?e.slice(o):e.slice(o,i)).join("");n.push({type:"literal",text:s}),o=i<0?e.length:i}}return n},s7e=(t,e=[])=>{let n=[];for(let r of t)if(r[0]==="name"){let o=r[1].includes(".")?r[1].split(".")[0]:r[1];n.push({type:"variable",name:o})}else if(["#","&","^",">"].includes(r[0])){if(n.push({type:"variable",name:r[1]}),r[0]==="#"&&r.length>4&&Array.isArray(r[4])){let o=[...e,r[1]],i=s7e(r[4],o);n.push(...i)}}else n.push({type:"literal",text:r[1]});return n},sj=t=>(i7e(),s7e(w9.parse(t))),a7e=(t,e)=>bR(t).reduce((n,r)=>{if(r.type==="variable"){if(r.name in e)return n+(typeof e[r.name]=="string"?e[r.name]:JSON.stringify(e[r.name]));throw new Error(`(f-string) Missing value for input ${r.name}`)}return n+r.text},""),l7e=(t,e)=>(i7e(),w9.render(t,e)),v9={"f-string":a7e,mustache:l7e},c7e={"f-string":bR,mustache:sj},df=(t,e,n)=>{try{return v9[e](t,n)}catch(r){throw Lb(r,"INVALID_PROMPT_INPUT")}},CR=(t,e)=>c7e[e](t),_R=(t,e,n)=>{if(!(e in v9))throw new Error(`Invalid template format. Got \`${e}\`;
                         should be one of ${Object.keys(v9)}`);try{let r=Object.fromEntries(n.map(o=>[o,"foo"]));Array.isArray(t)?t.forEach(o=>{if(o.type==="text"&&"text"in o&&typeof o.text=="string")df(o.text,e,r);else if(o.type==="image_url"){if(typeof o.image_url=="string")df(o.image_url,e,r);else if(typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"){let i=o.image_url.url;df(i,e,r)}}else throw new Error(`Invalid message template received. ${JSON.stringify(o,null,2)}`)}):df(t,e,r)}catch(r){throw new Error(`Invalid prompt schema: ${r.message}`)}}});var ki,x9=C(()=>{rj();uP();ki=class aj extends cP{constructor(n){super(n);I(this,"template");I(this,"templateFormat","f-string");I(this,"validateTemplate",!0);I(this,"additionalContentFields");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){if(this.templateFormat==="mustache")throw new Error("Mustache templates cannot be validated.");let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),_R(this.template,this.templateFormat,r)}}static lc_name(){return"PromptTemplate"}_getPromptType(){return"prompt"}async format(n){let r=await this.mergePartialAndUserVariables(n);return df(this.template,this.templateFormat,r)}static fromExamples(n,r,o,i=`

`,s=""){return new aj({inputVariables:o,template:[s,...n,r].join(i)})}static fromTemplate(n,r){let{templateFormat:o="f-string",...i}=r??{},s=new Set;return CR(n,o).forEach(a=>{a.type==="variable"&&s.add(a.name)}),new aj({inputVariables:[...s],templateFormat:o,template:n,...i})}async partial(n){let r=this.inputVariables.filter(i=>!(i in n)),o={...this.partialVariables??{},...n};return new aj({...this,inputVariables:r,partialVariables:o})}serialize(){if(this.outputParser!==void 0)throw new Error("Cannot serialize a prompt template with an output parser");return{_type:this._getPromptType(),input_variables:this.inputVariables,template:this.template,template_format:this.templateFormat}}static async deserialize(n){if(!n.template)throw new Error("Prompt template must have a template");return new aj({inputVariables:n.input_variables,template:n.template,templateFormat:n.template_format})}}});var lj,jxe=C(()=>{tU();wR();uP();lj=class u7e extends fy{constructor(n){super(n);I(this,"lc_namespace",["langchain_core","prompts","image"]);I(this,"template");I(this,"templateFormat","f-string");I(this,"validateTemplate",!0);I(this,"additionalContentFields");if(this.template=n.template,this.templateFormat=n.templateFormat??this.templateFormat,this.validateTemplate=n.validateTemplate??this.validateTemplate,this.additionalContentFields=n.additionalContentFields,this.validateTemplate){let r=this.inputVariables;this.partialVariables&&(r=r.concat(Object.keys(this.partialVariables))),_R([{type:"image_url",image_url:this.template}],this.templateFormat,r)}}static lc_name(){return"ImagePromptTemplate"}_getPromptType(){return"prompt"}async partial(n){let r=this.inputVariables.filter(i=>!(i in n)),o={...this.partialVariables??{},...n};return new u7e({...this,inputVariables:r,partialVariables:o})}async format(n){let r={};for(let[a,l]of Object.entries(this.template))typeof l=="string"?r[a]=df(l,this.templateFormat,n):r[a]=l;let o=n.url||r.url,i=n.detail||r.detail;if(!o)throw new Error("Must provide either an image URL.");if(typeof o!="string")throw new Error("url must be a string.");let s={url:o};return i&&(s.detail=i),s}async formatPromptValue(n){return new h4e(await this.format(n))}}});function Vxe(t,e){let n=[];for(let r of Object.values(t))if(typeof r=="string")CR(r,e).forEach(o=>{o.type==="variable"&&n.push(o.name)});else if(Array.isArray(r))for(let o of r)typeof o=="string"?CR(o,e).forEach(i=>{i.type==="variable"&&n.push(i.name)}):typeof o=="object"&&n.push(...Vxe(o,e));else typeof r=="object"&&r!==null&&n.push(...Vxe(r,e));return Array.from(new Set(n))}function Wxe(t,e,n){let r={};for(let[o,i]of Object.entries(t))if(typeof i=="string")r[o]=df(i,n,e);else if(Array.isArray(i)){let s=[];for(let a of i)typeof a=="string"?s.push(df(a,n,e)):typeof a=="object"&&s.push(Wxe(a,e,n));r[o]=s}else typeof i=="object"&&i!==null?r[o]=Wxe(i,e,n):r[o]=i;return r}var b9,Hxe=C(()=>{Ra();uP();b9=class extends gr{constructor(e){let n=e.templateFormat??"f-string",r=Vxe(e.template,n);super({inputVariables:r,...e});I(this,"lc_namespace",["langchain_core","prompts","dict"]);I(this,"lc_serializable",!0);I(this,"template");I(this,"templateFormat");I(this,"inputVariables");this.template=e.template,this.templateFormat=n,this.inputVariables=r}static lc_name(){return"DictPromptTemplate"}async format(e){return Wxe(this.template,e,this.templateFormat)}async invoke(e){return await this._callWithConfig(this.format.bind(this),e,{runType:"prompt"})}}});function DWt(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:Object.keys(t).length===1&&"text"in t&&typeof t.text=="string"}function $Wt(t){return t===null||typeof t!="object"||Array.isArray(t)?!1:"image_url"in t&&(typeof t.image_url=="string"||typeof t.image_url=="object"&&t.image_url!==null&&"url"in t.image_url&&typeof t.image_url.url=="string")}function FWt(t){return typeof t.formatMessages=="function"}function UWt(t,e){if(FWt(t)||np(t))return t;if(Array.isArray(t)&&t[0]==="placeholder"){let o=t[1];if(e?.templateFormat==="mustache"&&typeof o=="string"&&o.slice(0,2)==="{{"&&o.slice(-2)==="}}")return new Pv({variableName:o.slice(2,-2),optional:!0});if(typeof o=="string"&&o[0]==="{"&&o[o.length-1]==="}")return new Pv({variableName:o.slice(1,-1),optional:!0});throw new Error(`Invalid placeholder template for format ${e?.templateFormat??'"f-string"'}: "${t[1]}". Expected a variable name surrounded by ${e?.templateFormat==="mustache"?"double":"single"} curly braces.`)}let n=Lm(t),r;if(typeof n.content=="string"?r=n.content:r=n.content.map(o=>"text"in o?{...o,text:o.text}:"image_url"in o?{...o,image_url:o.image_url}:o),n._getType()==="human")return ff.fromTemplate(r,e);if(n._getType()==="ai")return Gxe.fromTemplate(r,e);if(n._getType()==="system")return fh.fromTemplate(r,e);if(rc.isInstance(n))return f7e.fromTemplate(n.content,n.role,e);throw new Error(`Could not coerce message prompt template from input. Received message type: "${n._getType()}".`)}function BWt(t){return t.constructor.lc_name()==="MessagesPlaceholder"}var _9,Pv,d7e,Kxe,f7e,qxe,ff,Gxe,fh,ou,cj=C(()=>{JT();nc();Wu();T2();Bb();I2();Dm();Ra();Kr();tU();wR();rj();uP();x9();jxe();Hxe();_9=class extends gr{constructor(){super(...arguments);I(this,"lc_namespace",["langchain_core","prompts","chat"]);I(this,"lc_serializable",!0)}async invoke(e,n){return this._callWithConfig(r=>this.formatMessages(r),e,{...n,runType:"prompt"})}},Pv=class extends _9{constructor(e){typeof e=="string"&&(e={variableName:e});super(e);I(this,"variableName");I(this,"optional");this.variableName=e.variableName,this.optional=e.optional??!1}static lc_name(){return"MessagesPlaceholder"}get inputVariables(){return[this.variableName]}async formatMessages(e){let n=e[this.variableName];if(this.optional&&!n)return[];if(!n){let o=new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`);throw o.name="InputFormatError",o}let r;try{Array.isArray(n)?r=n.map(Lm):r=[Lm(n)]}catch(o){let i=typeof n=="string"?n:JSON.stringify(n,null,2),s=new Error([`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`,`Received value: ${i}`,`Additional message: ${o.message}`].join(`

`));throw s.name="InputFormatError",s.lc_error_code=o.lc_error_code,s}return r}},d7e=class extends _9{constructor(e){"prompt"in e||(e={prompt:e});super(e);I(this,"prompt");this.prompt=e.prompt}get inputVariables(){return this.prompt.inputVariables}async formatMessages(e){return[await this.format(e)]}},Kxe=class extends fy{constructor(t){super(t)}async format(t){return(await this.formatPromptValue(t)).toString()}async formatPromptValue(t){return new i5(await this.formatMessages(t))}},f7e=class extends d7e{constructor(e,n){"prompt"in e||(e={prompt:e,role:n});super(e);I(this,"role");this.role=e.role}static lc_name(){return"ChatMessagePromptTemplate"}async format(e){return new rc(await this.prompt.format(e),this.role)}static fromTemplate(e,n,r){return new this(ki.fromTemplate(e,{templateFormat:r?.templateFormat}),n)}};qxe=class extends _9{constructor(e,n){"prompt"in e||(e={prompt:e});super(e);I(this,"lc_namespace",["langchain_core","prompts","chat"]);I(this,"lc_serializable",!0);I(this,"inputVariables",[]);I(this,"additionalOptions",{});I(this,"prompt");I(this,"messageClass");I(this,"chatMessageClass");if(this.prompt=e.prompt,Array.isArray(this.prompt)){let r=[];this.prompt.forEach(o=>{"inputVariables"in o&&(r=r.concat(o.inputVariables))}),this.inputVariables=r}else this.inputVariables=this.prompt.inputVariables;this.additionalOptions=n??this.additionalOptions}static _messageClass(){throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate")}createMessage(e){let n=this.constructor;if(n._messageClass())return new(n._messageClass())({content:e});if(n.chatMessageClass){let r=n.chatMessageClass();return new r({content:e,role:this.getRoleFromMessageClass(r.lc_name())})}else throw new Error("No message class defined")}getRoleFromMessageClass(e){switch(e){case"HumanMessage":return"human";case"AIMessage":return"ai";case"SystemMessage":return"system";case"ChatMessage":return"chat";default:throw new Error("Invalid message class name")}}static fromTemplate(e,n){if(typeof e=="string")return new this(ki.fromTemplate(e,n));let r=[];for(let o of e)if(typeof o=="string")r.push(ki.fromTemplate(o,n));else if(o!==null)if(DWt(o)){let i="";typeof o.text=="string"&&(i=o.text??"");let s={...n,additionalContentFields:o};r.push(ki.fromTemplate(i,s))}else if($Wt(o)){let i=o.image_url??"",s,a=[];if(typeof i=="string"){let l;n?.templateFormat==="mustache"?l=sj(i):l=bR(i);let c=l.flatMap(u=>u.type==="variable"?[u.name]:[]);if((c?.length??0)>0){if(c.length>1)throw new Error(`Only one format variable allowed per image template.
Got: ${c}
From: ${i}`);a=[c[0]]}else a=[];i={url:i},s=new lj({template:i,inputVariables:a,templateFormat:n?.templateFormat,additionalContentFields:o})}else if(typeof i=="object"){if("url"in i){let l;n?.templateFormat==="mustache"?l=sj(i.url):l=bR(i.url),a=l.flatMap(c=>c.type==="variable"?[c.name]:[])}else a=[];s=new lj({template:i,inputVariables:a,templateFormat:n?.templateFormat,additionalContentFields:o})}else throw new Error("Invalid image template");r.push(s)}else typeof o=="object"&&r.push(new b9({template:o,templateFormat:n?.templateFormat}));return new this({prompt:r,additionalOptions:n})}async format(e){if(this.prompt instanceof cP){let n=await this.prompt.format(e);return this.createMessage(n)}else{let n=[];for(let r of this.prompt){let o={};if(!("inputVariables"in r))throw new Error(`Prompt ${r} does not have inputVariables defined.`);for(let i of r.inputVariables)o||(o={[i]:e[i]}),o={...o,[i]:e[i]};if(r instanceof cP){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),i!==""&&n.push({...s,type:"text",text:i})}else if(r instanceof lj){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),n.push({...s,type:"image_url",image_url:i})}else if(r instanceof b9){let i=await r.format(o),s;"additionalContentFields"in r&&(s=r.additionalContentFields),n.push({...s,...i})}}return this.createMessage(n)}}async formatMessages(e){return[await this.format(e)]}},ff=class extends qxe{static _messageClass(){return Zo}static lc_name(){return"HumanMessagePromptTemplate"}},Gxe=class extends qxe{static _messageClass(){return kn}static lc_name(){return"AIMessagePromptTemplate"}},fh=class extends qxe{static _messageClass(){return Vu}static lc_name(){return"SystemMessagePromptTemplate"}};ou=class C9 extends Kxe{constructor(n){super(n);I(this,"promptMessages");I(this,"validateTemplate",!0);I(this,"templateFormat","f-string");if(n.templateFormat==="mustache"&&n.validateTemplate===void 0&&(this.validateTemplate=!1),Object.assign(this,n),this.validateTemplate){let r=new Set;for(let l of this.promptMessages)if(!(l instanceof Vs))for(let c of l.inputVariables)r.add(c);let o=this.inputVariables,i=new Set(this.partialVariables?o.concat(Object.keys(this.partialVariables)):o),s=new Set([...i].filter(l=>!r.has(l)));if(s.size>0)throw new Error(`Input variables \`${[...s]}\` are not used in any of the prompt messages.`);let a=new Set([...r].filter(l=>!i.has(l)));if(a.size>0)throw new Error(`Input variables \`${[...a]}\` are used in prompt messages but not in the prompt template.`)}}static lc_name(){return"ChatPromptTemplate"}get lc_aliases(){return{promptMessages:"messages"}}_getPromptType(){return"chat"}async _parseImagePrompts(n,r){return typeof n.content=="string"||(n.content=await Promise.all(n.content.map(async o=>{if(o.type!=="image_url")return o;let i="";typeof o.image_url=="string"?i=o.image_url:typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url&&typeof o.image_url.url=="string"&&(i=o.image_url.url);let s=await ki.fromTemplate(i,{templateFormat:this.templateFormat}).format(r);return typeof o.image_url=="object"&&o.image_url!==null&&"url"in o.image_url?o.image_url.url=s:o.image_url=s,o}))),n}async formatMessages(n){let r=await this.mergePartialAndUserVariables(n),o=[];for(let i of this.promptMessages)if(i instanceof Vs)o.push(await this._parseImagePrompts(i,r));else{let s;this.templateFormat==="mustache"?s={...r}:s=i.inputVariables.reduce((l,c)=>{if(!(c in r)&&!(BWt(i)&&i.optional))throw Lb(new Error(`Missing value for input variable \`${c.toString()}\``),"INVALID_PROMPT_INPUT");return l[c]=r[c],l},{});let a=await i.formatMessages(s);o=o.concat(a)}return o}async partial(n){let r=this.inputVariables.filter(i=>!(i in n)),o={...this.partialVariables??{},...n};return new C9({...this,inputVariables:r,partialVariables:o})}static fromTemplate(n,r){let o=new ff({prompt:ki.fromTemplate(n,r)});return this.fromMessages([o])}static fromMessages(n,r){let o=n.reduce((a,l)=>a.concat(l instanceof C9?l.promptMessages:[UWt(l,r)]),[]),i=n.reduce((a,l)=>l instanceof C9?Object.assign(a,l.partialVariables):a,Object.create(null)),s=new Set;for(let a of o)if(!(a instanceof Vs))for(let l of a.inputVariables)l in i||s.add(l);return new this({...r,inputVariables:[...s],promptMessages:o,partialVariables:i,templateFormat:r?.templateFormat})}}});var p7e=C(()=>{rj();uP();x9();cj()});var m7e=C(()=>{wR();cj()});var h7e=C(()=>{Ra();cj()});var ph=C(()=>{$n();wR();rj();uP();x9();jxe();Hxe();cj();p7e();m7e();h7e()});function Jxe(t,e){let n=new Set;for(let r of e)t.has(r)&&n.add(r);return n}function C7e(t,e){let n=new Set(t);for(let r of e)n.add(r);return n}function dj(t,e){let n=new Set(t);for(let r of e)n.delete(r);return n}var _7e=C(()=>{});var Xxe={};zn(Xxe,{SequentialChain:()=>tHt,SimpleSequentialChain:()=>nHt});function fj(t){return Array.from(t).map(e=>`"${e}"`).join(", ")}var tHt,nHt,Qxe=C(()=>{MR();_7e();tHt=class S7e extends mc{constructor(n){super(n);I(this,"chains");I(this,"inputVariables");I(this,"outputVariables");I(this,"returnAll");if(this.chains=n.chains,this.inputVariables=n.inputVariables,this.outputVariables=n.outputVariables??[],this.outputVariables.length>0&&n.returnAll)throw new Error("Either specify variables to return using `outputVariables` or use `returnAll` param. Cannot apply both conditions at the same time.");this.returnAll=n.returnAll??!1,this._validateChains()}static lc_name(){return"SequentialChain"}get inputKeys(){return this.inputVariables}get outputKeys(){return this.outputVariables}_validateChains(){if(this.chains.length===0)throw new Error("Sequential chain must have at least one chain.");let n=this.memory?.memoryKeys??[],r=new Set(this.inputKeys),o=new Set(n),i=Jxe(r,o);if(i.size>0)throw new Error(`The following keys: ${fj(i)} are overlapping between memory and input keys of the chain variables. This can lead to unexpected behaviour. Please use input and memory keys that don't overlap.`);let s=C7e(r,o);for(let a of this.chains){let l=dj(new Set(a.inputKeys),s);if(a.memory&&(l=dj(l,new Set(a.memory.memoryKeys))),l.size>0)throw new Error(`Missing variables for chain "${a._chainType()}": ${fj(l)}. Only got the following variables: ${fj(s)}.`);let c=new Set(a.outputKeys),u=Jxe(s,c);if(u.size>0)throw new Error(`The following output variables for chain "${a._chainType()}" are overlapping: ${fj(u)}. This can lead to unexpected behaviour.`);for(let d of c)s.add(d)}if(this.outputVariables.length===0)if(this.returnAll){let a=dj(s,r);this.outputVariables=Array.from(a)}else this.outputVariables=this.chains[this.chains.length-1].outputKeys;else{let a=dj(new Set(this.outputVariables),new Set(s));if(a.size>0)throw new Error(`The following output variables were expected to be in the final chain output but were not found: ${fj(a)}.`)}}async _call(n,r){let o={},i=n,s=0;for(let l of this.chains){s+=1,o=await l.call(i,r?.getChild(`step_${s}`));for(let c of Object.keys(o))i[c]=o[c]}let a={};for(let l of this.outputVariables)a[l]=i[l];return a}_chainType(){return"sequential_chain"}static async deserialize(n){let r=[],o=n.input_variables,i=n.output_variables,s=n.chains;for(let a of s){let l=await mc.deserialize(a);r.push(l)}return new S7e({chains:r,inputVariables:o,outputVariables:i})}serialize(){let n=[];for(let r of this.chains)n.push(r.serialize());return{_type:this._chainType(),input_variables:this.inputVariables,output_variables:this.outputVariables,chains:n}}},nHt=class T7e extends mc{constructor(n){super(n);I(this,"chains");I(this,"inputKey","input");I(this,"outputKey","output");I(this,"trimOutputs");this.chains=n.chains,this.trimOutputs=n.trimOutputs??!1,this._validateChains()}static lc_name(){return"SimpleSequentialChain"}get inputKeys(){return[this.inputKey]}get outputKeys(){return[this.outputKey]}_validateChains(){for(let n of this.chains){if(n.inputKeys.filter(r=>!n.memory?.memoryKeys.includes(r)).length!==1)throw new Error(`Chains used in SimpleSequentialChain should all have one input, got ${n.inputKeys.length} for ${n._chainType()}.`);if(n.outputKeys.length!==1)throw new Error(`Chains used in SimpleSequentialChain should all have one output, got ${n.outputKeys.length} for ${n._chainType()}.`)}}async _call(n,r){let o=n[this.inputKey],i=0;for(let s of this.chains)i+=1,o=(await s.call({[s.inputKeys[0]]:o,signal:n.signal},r?.getChild(`step_${i}`)))[s.outputKeys[0]],this.trimOutputs&&(o=o.trim()),await r?.handleText(o);return{[this.outputKey]:o}}_chainType(){return"simple_sequential_chain"}static async deserialize(n){let r=[],o=n.chains;for(let i of o){let s=await mc.deserialize(i);r.push(s)}return new T7e({chains:r})}serialize(){let n=[];for(let r of this.chains)n.push(r.serialize());return{_type:this._chainType(),chains:n}}}});var k9={};zn(k9,{MapReduceDocumentsChain:()=>P7e,RefineDocumentsChain:()=>A7e,StuffDocumentsChain:()=>A9});var A9,P7e,A7e,pj=C(()=>{MR();pP();ph();A9=class I7e extends mc{constructor(n){super(n);I(this,"llmChain");I(this,"inputKey","input_documents");I(this,"documentVariableName","context");this.llmChain=n.llmChain,this.documentVariableName=n.documentVariableName??this.documentVariableName,this.inputKey=n.inputKey??this.inputKey}static lc_name(){return"StuffDocumentsChain"}get inputKeys(){return[this.inputKey,...this.llmChain.inputKeys].filter(n=>n!==this.documentVariableName)}get outputKeys(){return this.llmChain.outputKeys}_prepInputs(n){if(!(this.inputKey in n))throw new Error(`Document key ${this.inputKey} not found.`);let{[this.inputKey]:r,...o}=n,s=r.map(({pageContent:a})=>a).join(`

`);return{...o,[this.documentVariableName]:s}}async _call(n,r){return await this.llmChain.call(this._prepInputs(n),r?.getChild("combine_documents"))}_chainType(){return"stuff_documents_chain"}static async deserialize(n){if(!n.llm_chain)throw new Error("Missing llm_chain");return new I7e({llmChain:await Ka.deserialize(n.llm_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize()}}},P7e=class E7e extends mc{constructor(n){super(n);I(this,"llmChain");I(this,"inputKey","input_documents");I(this,"documentVariableName","context");I(this,"returnIntermediateSteps",!1);I(this,"maxTokens",3e3);I(this,"maxIterations",10);I(this,"ensureMapStep",!1);I(this,"combineDocumentChain");this.llmChain=n.llmChain,this.combineDocumentChain=n.combineDocumentChain,this.documentVariableName=n.documentVariableName??this.documentVariableName,this.ensureMapStep=n.ensureMapStep??this.ensureMapStep,this.inputKey=n.inputKey??this.inputKey,this.maxTokens=n.maxTokens??this.maxTokens,this.maxIterations=n.maxIterations??this.maxIterations,this.returnIntermediateSteps=n.returnIntermediateSteps??!1}static lc_name(){return"MapReduceDocumentsChain"}get inputKeys(){return[this.inputKey,...this.combineDocumentChain.inputKeys]}get outputKeys(){return this.combineDocumentChain.outputKeys}async _call(n,r){if(!(this.inputKey in n))throw new Error(`Document key ${this.inputKey} not found.`);let{[this.inputKey]:o,...i}=n,s=o,a=[];for(let u=0;u<this.maxIterations;u+=1){let d=s.map(h=>({[this.documentVariableName]:h.pageContent,...i}));if(u!==0||!this.ensureMapStep){let h=await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({[this.combineDocumentChain.inputKey]:s,...i}));if(await this.combineDocumentChain.llmChain._getNumTokens(h)<this.maxTokens)break}let p=await this.llmChain.apply(d,r?Array.from({length:d.length},(h,g)=>r.getChild(`map_${g+1}`)):void 0),{outputKey:m}=this.llmChain;this.returnIntermediateSteps&&(a=a.concat(p.map(h=>h[m]))),s=p.map(h=>({pageContent:h[m],metadata:{}}))}let l={[this.combineDocumentChain.inputKey]:s,...i},c=await this.combineDocumentChain.call(l,r?.getChild("combine_documents"));return this.returnIntermediateSteps?{...c,intermediateSteps:a}:c}_chainType(){return"map_reduce_documents_chain"}static async deserialize(n){if(!n.llm_chain)throw new Error("Missing llm_chain");if(!n.combine_document_chain)throw new Error("Missing combine_document_chain");return new E7e({llmChain:await Ka.deserialize(n.llm_chain),combineDocumentChain:await A9.deserialize(n.combine_document_chain)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),combine_document_chain:this.combineDocumentChain.serialize()}}},A7e=class k7e extends mc{constructor(n){super(n);I(this,"llmChain");I(this,"inputKey","input_documents");I(this,"outputKey","output_text");I(this,"documentVariableName","context");I(this,"initialResponseName","existing_answer");I(this,"refineLLMChain");I(this,"documentPrompt",this.defaultDocumentPrompt);this.llmChain=n.llmChain,this.refineLLMChain=n.refineLLMChain,this.documentVariableName=n.documentVariableName??this.documentVariableName,this.inputKey=n.inputKey??this.inputKey,this.outputKey=n.outputKey??this.outputKey,this.documentPrompt=n.documentPrompt??this.documentPrompt,this.initialResponseName=n.initialResponseName??this.initialResponseName}static lc_name(){return"RefineDocumentsChain"}get defaultDocumentPrompt(){return new ki({inputVariables:["page_content"],template:"{page_content}"})}get inputKeys(){return[...new Set([this.inputKey,...this.llmChain.inputKeys,...this.refineLLMChain.inputKeys])].filter(n=>n!==this.documentVariableName&&n!==this.initialResponseName)}get outputKeys(){return[this.outputKey]}async _constructInitialInputs(n,r){let o={page_content:n.pageContent,...n.metadata},i={};return this.documentPrompt.inputVariables.forEach(l=>{i[l]=o[l]}),{...{[this.documentVariableName]:await this.documentPrompt.format({...i})},...r}}async _constructRefineInputs(n,r){let o={page_content:n.pageContent,...n.metadata},i={};this.documentPrompt.inputVariables.forEach(l=>{i[l]=o[l]});let s={[this.documentVariableName]:await this.documentPrompt.format({...i})};return{[this.initialResponseName]:r,...s}}async _call(n,r){if(!(this.inputKey in n))throw new Error(`Document key ${this.inputKey} not found.`);let{[this.inputKey]:o,...i}=n,s=o,a=await this._constructInitialInputs(s[0],i),l=await this.llmChain.predict({...a},r?.getChild("answer")),c=[l];for(let u=1;u<s.length;u+=1){let f={...await this._constructRefineInputs(s[u],l),...i};l=await this.refineLLMChain.predict({...f},r?.getChild("refine")),c.push(l)}return{[this.outputKey]:l}}_chainType(){return"refine_documents_chain"}static async deserialize(n){let r=n.llm_chain;if(!r)throw new Error("Missing llm_chain");let o=n.refine_llm_chain;if(!o)throw new Error("Missing refine_llm_chain");return new k7e({llmChain:await Ka.deserialize(r),refineLLMChain:await Ka.deserialize(o)})}serialize(){return{_type:this._chainType(),llm_chain:this.llmChain.serialize(),refine_llm_chain:this.refineLLMChain.serialize()}}}});var M9=C(()=>{Rb()});function hj(t){return t._modelType()==="base_chat_model"}var M7e,mj,N7e=C(()=>{M7e=class{async getPromptAsync(t,e){return this.getPrompt(t).partial(e?.partialVariables??{})}},mj=class extends M7e{constructor(e,n=[]){super();I(this,"defaultPrompt");I(this,"conditionals");this.defaultPrompt=e,this.conditionals=n}getPrompt(e){for(let[n,r]of this.conditionals)if(n(e))return r;return this.defaultPrompt}}});var R7e=C(()=>{M9()});var L7e=C(()=>{Yge();M9()});var N9=C(()=>{$n();M9();N7e();R7e();L7e()});var rHt,oHt,iHt,sHt,D7e,$7e=C(()=>{ph();N9();rHt=new ki({template:`Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.

{context}

Question: {question}
Helpful Answer:`,inputVariables:["context","question"]}),oHt=`Use the following pieces of context to answer the users question. 
If you don't know the answer, just say that you don't know, don't try to make up an answer.
----------------
{context}`,iHt=[fh.fromTemplate(oHt),ff.fromTemplate("{question}")],sHt=ou.fromMessages(iHt),D7e=new mj(rHt,[[hj,sHt]])});var F7e=C(()=>{ph();N9()});var U7e=C(()=>{ph();N9()});function B7e(t,e={}){let{prompt:n=D7e.getPrompt(t),verbose:r}=e,o=new Ka({prompt:n,llm:t,verbose:r});return new A9({llmChain:o,verbose:r})}var z7e=C(()=>{pP();pj();$7e();F7e();U7e()});var V7e={};zn(V7e,{VectorDBQAChain:()=>aHt});var aHt,W7e=C(()=>{MR();z7e();aHt=class j7e extends mc{constructor(n){super(n);I(this,"k",4);I(this,"inputKey","query");I(this,"vectorstore");I(this,"combineDocumentsChain");I(this,"returnSourceDocuments",!1);this.vectorstore=n.vectorstore,this.combineDocumentsChain=n.combineDocumentsChain,this.inputKey=n.inputKey??this.inputKey,this.k=n.k??this.k,this.returnSourceDocuments=n.returnSourceDocuments??this.returnSourceDocuments}static lc_name(){return"VectorDBQAChain"}get inputKeys(){return[this.inputKey]}get outputKeys(){return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments?["sourceDocuments"]:[])}async _call(n,r){if(!(this.inputKey in n))throw new Error(`Question key ${this.inputKey} not found.`);let o=n[this.inputKey],i=await this.vectorstore.similaritySearch(o,this.k,n.filter,r?.getChild("vectorstore")),s={question:o,input_documents:i},a=await this.combineDocumentsChain.call(s,r?.getChild("combine_documents"));return this.returnSourceDocuments?{...a,sourceDocuments:i}:a}_chainType(){return"vector_db_qa"}static async deserialize(n,r){if(!("vectorstore"in r))throw new Error("Need to pass in a vectorstore to deserialize VectorDBQAChain");let{vectorstore:o}=r;if(!n.combine_documents_chain)throw new Error("VectorDBQAChain must have combine_documents_chain in serialized data");return new j7e({combineDocumentsChain:await mc.deserialize(n.combine_documents_chain),k:n.k,vectorstore:o})}serialize(){return{_type:this._chainType(),combine_documents_chain:this.combineDocumentsChain.serialize(),k:this.k}}static fromLLM(n,r,o){let i=B7e(n);return new this({vectorstore:r,combineDocumentsChain:i,...o})}}});var H7e,K7e,lHt,q7e,G7e=C(()=>{ph();H7e=`You are given the below API Documentation:
{api_docs}
Using this documentation, generate the full API url to call for answering the user question.
You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call.

Question:{question}
API url:`,K7e=new ki({inputVariables:["api_docs","question"],template:H7e}),lHt=`${H7e} {api_url}

Here is the response from the API:

{api_response}

Summarize this response to answer the original question.

Summary:`,q7e=new ki({inputVariables:["api_docs","question","api_url","api_response"],template:lHt})});var Z7e={};zn(Z7e,{APIChain:()=>cHt});var cHt,J7e=C(()=>{MR();pP();G7e();cHt=class Y7e extends mc{constructor(n){super(n);I(this,"apiAnswerChain");I(this,"apiRequestChain");I(this,"apiDocs");I(this,"headers",{});I(this,"inputKey","question");I(this,"outputKey","output");this.apiRequestChain=n.apiRequestChain,this.apiAnswerChain=n.apiAnswerChain,this.apiDocs=n.apiDocs,this.inputKey=n.inputKey??this.inputKey,this.outputKey=n.outputKey??this.outputKey,this.headers=n.headers??this.headers}get inputKeys(){return[this.inputKey]}get outputKeys(){return[this.outputKey]}async _call(n,r){let o=n[this.inputKey],i=await this.apiRequestChain.predict({question:o,api_docs:this.apiDocs},r?.getChild("request")),a=await(await fetch(i,{headers:this.headers})).text(),l=await this.apiAnswerChain.predict({question:o,api_docs:this.apiDocs,api_url:i,api_response:a},r?.getChild("response"));return{[this.outputKey]:l}}_chainType(){return"api_chain"}static async deserialize(n){let{api_request_chain:r,api_answer_chain:o,api_docs:i}=n;if(!r)throw new Error("LLMChain must have api_request_chain");if(!o)throw new Error("LLMChain must have api_answer_chain");if(!i)throw new Error("LLMChain must have api_docs");return new Y7e({apiAnswerChain:await Ka.deserialize(o),apiRequestChain:await Ka.deserialize(r),apiDocs:i})}serialize(){return{_type:this._chainType(),api_answer_chain:this.apiAnswerChain.serialize(),api_request_chain:this.apiRequestChain.serialize(),api_docs:this.apiDocs}}static fromLLMAndAPIDocs(n,r,o={}){let{apiUrlPrompt:i=K7e,apiResponsePrompt:s=q7e}=o,a=new Ka({prompt:i,llm:n}),l=new Ka({prompt:s,llm:n});return new this({apiAnswerChain:l,apiRequestChain:a,apiDocs:r,...o})}}});var mc,MR=C(()=>{jm();qd();ac();Hb();mc=class extends nU{get lc_namespace(){return["langchain","chains",this._chainType()]}constructor(t,e,n){if(arguments.length===1&&typeof t=="object"&&!("saveContext"in t)){let{memory:r,callbackManager:o,...i}=t;super({...i,callbacks:o??i.callbacks}),this.memory=r}else super({verbose:e,callbacks:n}),this.memory=t}_selectMemoryInputs(t){let e={...t};return"signal"in e&&delete e.signal,"timeout"in e&&delete e.timeout,e}async invoke(t,e){let n=fr(e),r=await this._formatValues(t),i=await(await Ws.configure(n?.callbacks,this.callbacks,n?.tags,this.tags,n?.metadata,this.metadata,{verbose:this.verbose}))?.handleChainStart(this.toJSON(),r,void 0,void 0,void 0,void 0,n?.runName),s;try{if(r.signal){let a;s=await Promise.race([this._call(r,i,n),new Promise((l,c)=>{a=()=>{c(new Error("AbortError"))},r.signal?.addEventListener("abort",a)})]).finally(()=>{r.signal&&a&&r.signal.removeEventListener("abort",a)})}else s=await this._call(r,i,n)}catch(a){throw await i?.handleChainError(a),a}return this.memory!=null&&await this.memory.saveContext(this._selectMemoryInputs(t),s),await i?.handleChainEnd(s),Object.defineProperty(s,iM,{value:i?{runId:i?.runId}:void 0,configurable:!0}),s}_validateOutputs(t){let e=this.outputKeys.filter(n=>!(n in t));if(e.length)throw new Error(`Missing output keys: ${e.join(", ")} from chain ${this._chainType()}`)}async prepOutputs(t,e,n=!1){return this._validateOutputs(e),this.memory&&await this.memory.saveContext(t,e),n?e:{...t,...e}}serialize(){throw new Error("Method not implemented.")}async run(t,e){let n=this.inputKeys.filter(a=>!this.memory?.memoryKeys.includes(a));if(!(n.length<=1))throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `);let o=n.length?{[n[0]]:t}:{},i=await this.call(o,e),s=Object.keys(i);if(s.length===1)return i[s[0]];throw new Error("return values have multiple keys, `run` only supported when one key currently")}async _formatValues(t){let e={...t};if(e.timeout&&!e.signal&&(e.signal=AbortSignal.timeout(e.timeout),delete e.timeout),this.memory!=null){let n=await this.memory.loadMemoryVariables(this._selectMemoryInputs(t));for(let[r,o]of Object.entries(n))e[r]=o}return e}async call(t,e,n){let r={tags:n,...Wb(e)};return this.invoke(t,r)}async apply(t,e){return Promise.all(t.map(async(n,r)=>this.call(n,e?.[r])))}static async deserialize(t,e={}){switch(t._type){case"llm_chain":{let{LLMChain:n}=await Promise.resolve().then(()=>(pP(),X7e));return n.deserialize(t)}case"sequential_chain":{let{SequentialChain:n}=await Promise.resolve().then(()=>(Qxe(),Xxe));return n.deserialize(t)}case"simple_sequential_chain":{let{SimpleSequentialChain:n}=await Promise.resolve().then(()=>(Qxe(),Xxe));return n.deserialize(t)}case"stuff_documents_chain":{let{StuffDocumentsChain:n}=await Promise.resolve().then(()=>(pj(),k9));return n.deserialize(t)}case"map_reduce_documents_chain":{let{MapReduceDocumentsChain:n}=await Promise.resolve().then(()=>(pj(),k9));return n.deserialize(t)}case"refine_documents_chain":{let{RefineDocumentsChain:n}=await Promise.resolve().then(()=>(pj(),k9));return n.deserialize(t)}case"vector_db_qa":{let{VectorDBQAChain:n}=await Promise.resolve().then(()=>(W7e(),V7e));return n.deserialize(t,e)}case"api_chain":{let{APIChain:n}=await Promise.resolve().then(()=>(J7e(),Z7e));return n.deserialize(t)}default:throw new Error(`Invalid prompt type in config: ${t._type}`)}}}});var Q7e,eJe=C(()=>{Uw();Q7e=class extends Fw{constructor(){super(...arguments);I(this,"lc_namespace",["langchain","output_parsers","default"]);I(this,"lc_serializable",!0)}static lc_name(){return"NoOpOutputParser"}parse(e){return Promise.resolve(e)}getFormatInstructions(){return""}}});var X7e={};zn(X7e,{LLMChain:()=>Ka});function uHt(t){return typeof t._llmType=="function"}function O9(t){if(uHt(t))return t;if("bound"in t&&gr.isRunnable(t.bound))return O9(t.bound);if("runnable"in t&&"fallbacks"in t&&gr.isRunnable(t.runnable))return O9(t.runnable);if("default"in t&&gr.isRunnable(t.default))return O9(t.default);throw new Error("Unable to extract BaseLanguageModel from llmLike object.")}var Ka,pP=C(()=>{MR();eJe();ph();jm();qd();Ka=class tJe extends mc{constructor(n){super(n);I(this,"lc_serializable",!0);I(this,"prompt");I(this,"llm");I(this,"llmKwargs");I(this,"outputKey","text");I(this,"outputParser");if(this.prompt=n.prompt,this.llm=n.llm,this.llmKwargs=n.llmKwargs,this.outputKey=n.outputKey??this.outputKey,this.outputParser=n.outputParser??new Q7e,this.prompt.outputParser){if(n.outputParser)throw new Error("Cannot set both outputParser and prompt.outputParser");this.outputParser=this.prompt.outputParser}}static lc_name(){return"LLMChain"}get inputKeys(){return this.prompt.inputVariables}get outputKeys(){return[this.outputKey]}getCallKeys(){return"callKeys"in this.llm?this.llm.callKeys:[]}_selectMemoryInputs(n){let r=super._selectMemoryInputs(n),o=this.getCallKeys();for(let i of o)i in n&&delete r[i];return r}async _getFinalOutput(n,r,o){let i;return this.outputParser?i=await this.outputParser.parseResultWithPrompt(n,r,o?.getChild()):i=n[0].text,i}call(n,r){return super.call(n,r)}async _call(n,r){let o={...n},i={...this.llmKwargs},s=this.getCallKeys();for(let u of s)u in n&&i&&(i[u]=n[u],delete o[u]);let a=await this.prompt.formatPromptValue(o);if("generatePrompt"in this.llm){let{generations:u}=await this.llm.generatePrompt([a],i,r?.getChild());return{[this.outputKey]:await this._getFinalOutput(u[0],a,r)}}let c=await(this.outputParser?this.llm.pipe(this.outputParser):this.llm).invoke(a,r?.getChild());return{[this.outputKey]:c}}async predict(n,r){return(await this.call(n,r))[this.outputKey]}_chainType(){return"llm"}static async deserialize(n){let{llm:r,prompt:o}=n;if(!r)throw new Error("LLMChain must have llm");if(!o)throw new Error("LLMChain must have prompt");return new tJe({llm:await mI.deserialize(r),prompt:await fy.deserialize(o)})}serialize(){let n="serialize"in this.llm?this.llm.serialize():void 0;return{_type:`${this._chainType()}_chain`,llm:n,prompt:this.prompt.serialize()}}_getNumTokens(n){return O9(this.llm).getNumTokens(n)}}});function k_(t){try{let e=new URL(t),n=e.hostname.replace(/^www\./,"").replace(/^m\./,"");return n==="youtube.com"&&e.pathname==="/watch"?e.searchParams.get("v"):n==="youtu.be"&&e.pathname.length>1?e.pathname.slice(1).split("/")[0]:(n==="youtube.com"&&e.pathname.startsWith("/shorts/")||n==="youtube.com"&&e.pathname.startsWith("/embed/"))&&e.pathname.split("/")[2]||null}catch{return null}}function jCe(t){return k_(t)!==null}var dZ=C(()=>{});function t4(t){if(!t)return!1;let e=t.view;return!e||typeof e!="object"?!1:typeof e.getViewType=="function"&&e.getViewType()===DP}function sL(t){let e=t.view?.webview;if(!e||typeof e!="object"||typeof e.executeJavaScript!="function")throw new VCe("Web Viewer webview is unavailable. The view may not be fully initialized.");return e}var DP,mZ,gf,fZ,pZ,VCe,M_,aL=C(()=>{DP="webviewer",mZ={OPEN:"webviewer:open",SAVE_TO_VAULT:"webviewer:save-to-vault"},gf=class t extends Error{constructor(e){super(e),this.name="WebViewerError",Object.setPrototypeOf(this,t.prototype)}},fZ=class t extends gf{constructor(e){super(e),this.name="WebViewerUnsupportedError",Object.setPrototypeOf(this,t.prototype)}},pZ=class t extends gf{constructor(e){super(e),this.name="WebViewerLeafNotFoundError",Object.setPrototypeOf(this,t.prototype)}},VCe=class t extends gf{constructor(e){super(e),this.name="WebviewUnavailableError",Object.setPrototypeOf(this,t.prototype)}},M_=class t extends gf{constructor(e){super(e),this.name="WebViewerTimeoutError",Object.setPrototypeOf(this,t.prototype)}}});function mGt(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)n.hasOwnProperty(r)&&(t[r]=n[r])}return t}function qCe(t,e){return Array(e+1).join(t)}function brt(t){return t.replace(/^\n*/,"")}function Crt(t){for(var e=t.length;e>0&&t[e-1]===`
`;)e--;return t.substring(0,e)}function _rt(t){return Crt(brt(t))}function GCe(t){return YCe(t,hGt)}function Trt(t){return YCe(t,Srt)}function gGt(t){return Prt(t,Srt)}function yGt(t){return YCe(t,Irt)}function wGt(t){return Prt(t,Irt)}function YCe(t,e){return e.indexOf(t.nodeName)>=0}function Prt(t,e){return t.getElementsByTagName&&e.some(function(n){return t.getElementsByTagName(n).length})}function hZ(t){return t?t.replace(/(\n+\s*)+/g,`
`):""}function Ert(t){this.options=t,this._keep=[],this._remove=[],this.blankRule={replacement:t.blankReplacement},this.keepReplacement=t.keepReplacement,this.defaultRule={replacement:t.defaultReplacement},this.array=[];for(var e in t.rules)this.array.push(t.rules[e])}function WCe(t,e,n){for(var r=0;r<t.length;r++){var o=t[r];if(vGt(o,e,n))return o}}function vGt(t,e,n){var r=t.filter;if(typeof r=="string"){if(r===e.nodeName.toLowerCase())return!0}else if(Array.isArray(r)){if(r.indexOf(e.nodeName.toLowerCase())>-1)return!0}else if(typeof r=="function"){if(r.call(t,e,n))return!0}else throw new TypeError("`filter` needs to be a string, array, or function")}function xGt(t){var e=t.element,n=t.isBlock,r=t.isVoid,o=t.isPre||function(d){return d.nodeName==="PRE"};if(!(!e.firstChild||o(e))){for(var i=null,s=!1,a=null,l=vrt(a,e,o);l!==e;){if(l.nodeType===3||l.nodeType===4){var c=l.data.replace(/[ \r\n\t]+/g," ");if((!i||/ $/.test(i.data))&&!s&&c[0]===" "&&(c=c.substr(1)),!c){l=HCe(l);continue}l.data=c,i=l}else if(l.nodeType===1)n(l)||l.nodeName==="BR"?(i&&(i.data=i.data.replace(/ $/,"")),i=null,s=!1):r(l)||o(l)?(i=null,s=!0):i&&(s=!1);else{l=HCe(l);continue}var u=vrt(a,l,o);a=l,l=u}i&&(i.data=i.data.replace(/ $/,""),i.data||HCe(i))}}function HCe(t){var e=t.nextSibling||t.parentNode;return t.parentNode.removeChild(t),e}function vrt(t,e,n){return t&&t.parentNode===e||n(e)?e.nextSibling||e.parentNode:e.firstChild||e.nextSibling||e.parentNode}function bGt(){var t=ZCe.DOMParser,e=!1;try{new t().parseFromString("","text/html")&&(e=!0)}catch{}return e}function CGt(){var t=function(){};return _Gt()?t.prototype.parseFromString=function(e){var n=new window.ActiveXObject("htmlfile");return n.designMode="on",n.open(),n.write(e),n.close(),n}:t.prototype.parseFromString=function(e){var n=document.implementation.createHTMLDocument("");return n.open(),n.write(e),n.close(),n},t}function _Gt(){var t=!1;try{document.implementation.createHTMLDocument("").open()}catch{ZCe.ActiveXObject&&(t=!0)}return t}function TGt(t,e){var n;if(typeof t=="string"){var r=IGt().parseFromString('<x-turndown id="turndown-root">'+t+"</x-turndown>","text/html");n=r.getElementById("turndown-root")}else n=t.cloneNode(!0);return xGt({element:n,isBlock:GCe,isVoid:Trt,isPre:e.preformattedCode?PGt:null}),n}function IGt(){return KCe=KCe||new SGt,KCe}function PGt(t){return t.nodeName==="PRE"||t.nodeName==="CODE"}function EGt(t,e){return t.isBlock=GCe(t),t.isCode=t.nodeName==="CODE"||t.parentNode.isCode,t.isBlank=AGt(t),t.flankingWhitespace=kGt(t,e),t}function AGt(t){return!Trt(t)&&!yGt(t)&&/^\s*$/i.test(t.textContent)&&!gGt(t)&&!wGt(t)}function kGt(t,e){if(t.isBlock||e.preformattedCode&&t.isCode)return{leading:"",trailing:""};var n=MGt(t.textContent);return n.leadingAscii&&xrt("left",t,e)&&(n.leading=n.leadingNonAscii),n.trailingAscii&&xrt("right",t,e)&&(n.trailing=n.trailingNonAscii),{leading:n.leading,trailing:n.trailing}}function MGt(t){var e=t.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:e[1],leadingAscii:e[2],leadingNonAscii:e[3],trailing:e[4],trailingNonAscii:e[5],trailingAscii:e[6]}}function xrt(t,e,n){var r,o,i;return t==="left"?(r=e.previousSibling,o=/ $/):(r=e.nextSibling,o=/^ /),r&&(r.nodeType===3?i=o.test(r.nodeValue):n.preformattedCode&&r.nodeName==="CODE"?i=!1:r.nodeType===1&&!GCe(r)&&(i=o.test(r.textContent))),i}function gZ(t){if(!(this instanceof gZ))return new gZ(t);var e={rules:yc,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:"  ",preformattedCode:!1,blankReplacement:function(n,r){return r.isBlock?`

`:""},keepReplacement:function(n,r){return r.isBlock?`

`+r.outerHTML+`

`:r.outerHTML},defaultReplacement:function(n,r){return r.isBlock?`

`+n+`

`:n}};this.options=mGt({},e,t),this.rules=new Ert(this.options)}function Art(t){var e=this;return NGt.call(t.childNodes,function(n,r){r=new EGt(r,e.options);var o="";return r.nodeType===3?o=r.isCode?r.nodeValue:e.escape(r.nodeValue):r.nodeType===1&&(o=LGt.call(e,r)),krt(n,o)},"")}function RGt(t){var e=this;return this.rules.forEach(function(n){typeof n.append=="function"&&(t=krt(t,n.append(e.options)))}),t.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function LGt(t){var e=this.rules.forNode(t),n=Art.call(this,t),r=t.flankingWhitespace;return(r.leading||r.trailing)&&(n=n.trim()),r.leading+e.replacement(n,t,this.options)+r.trailing}function krt(t,e){var n=Crt(t),r=brt(e),o=Math.max(t.length-n.length,e.length-r.length),i=`

`.substring(0,o);return n+i+r}function DGt(t){return t!=null&&(typeof t=="string"||t.nodeType&&(t.nodeType===1||t.nodeType===9||t.nodeType===11))}var hGt,Srt,Irt,yc,ZCe,SGt,KCe,NGt,OGt,Mrt,Nrt=C(()=>{hGt=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];Srt=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];Irt=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];yc={};yc.paragraph={filter:"p",replacement:function(t){return`

`+t+`

`}};yc.lineBreak={filter:"br",replacement:function(t,e,n){return n.br+`
`}};yc.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(t,e,n){var r=Number(e.nodeName.charAt(1));if(n.headingStyle==="setext"&&r<3){var o=qCe(r===1?"=":"-",t.length);return`

`+t+`
`+o+`

`}else return`

`+qCe("#",r)+" "+t+`

`}};yc.blockquote={filter:"blockquote",replacement:function(t){return t=_rt(t).replace(/^/gm,"> "),`

`+t+`

`}};yc.list={filter:["ul","ol"],replacement:function(t,e){var n=e.parentNode;return n.nodeName==="LI"&&n.lastElementChild===e?`
`+t:`

`+t+`

`}};yc.listItem={filter:"li",replacement:function(t,e,n){var r=n.bulletListMarker+"   ",o=e.parentNode;if(o.nodeName==="OL"){var i=o.getAttribute("start"),s=Array.prototype.indexOf.call(o.children,e);r=(i?Number(i)+s:s+1)+".  "}var a=/\n$/.test(t);return t=_rt(t)+(a?`
`:""),t=t.replace(/\n/gm,`
`+" ".repeat(r.length)),r+t+(e.nextSibling?`
`:"")}};yc.indentedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="indented"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,n){return`

    `+e.firstChild.textContent.replace(/\n/g,`
    `)+`

`}};yc.fencedCodeBlock={filter:function(t,e){return e.codeBlockStyle==="fenced"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,e,n){for(var r=e.firstChild.getAttribute("class")||"",o=(r.match(/language-(\S+)/)||[null,""])[1],i=e.firstChild.textContent,s=n.fence.charAt(0),a=3,l=new RegExp("^"+s+"{3,}","gm"),c;c=l.exec(i);)c[0].length>=a&&(a=c[0].length+1);var u=qCe(s,a);return`

`+u+o+`
`+i.replace(/\n$/,"")+`
`+u+`

`}};yc.horizontalRule={filter:"hr",replacement:function(t,e,n){return`

`+n.hr+`

`}};yc.inlineLink={filter:function(t,e){return e.linkStyle==="inlined"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e){var n=e.getAttribute("href");n&&(n=n.replace(/([()])/g,"\\$1"));var r=hZ(e.getAttribute("title"));return r&&(r=' "'+r.replace(/"/g,'\\"')+'"'),"["+t+"]("+n+r+")"}};yc.referenceLink={filter:function(t,e){return e.linkStyle==="referenced"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,e,n){var r=e.getAttribute("href"),o=hZ(e.getAttribute("title"));o&&(o=' "'+o+'"');var i,s;switch(n.linkReferenceStyle){case"collapsed":i="["+t+"][]",s="["+t+"]: "+r+o;break;case"shortcut":i="["+t+"]",s="["+t+"]: "+r+o;break;default:var a=this.references.length+1;i="["+t+"]["+a+"]",s="["+a+"]: "+r+o}return this.references.push(s),i},references:[],append:function(t){var e="";return this.references.length&&(e=`

`+this.references.join(`
`)+`

`,this.references=[]),e}};yc.emphasis={filter:["em","i"],replacement:function(t,e,n){return t.trim()?n.emDelimiter+t+n.emDelimiter:""}};yc.strong={filter:["strong","b"],replacement:function(t,e,n){return t.trim()?n.strongDelimiter+t+n.strongDelimiter:""}};yc.code={filter:function(t){var e=t.previousSibling||t.nextSibling,n=t.parentNode.nodeName==="PRE"&&!e;return t.nodeName==="CODE"&&!n},replacement:function(t){if(!t)return"";t=t.replace(/\r?\n|\r/g," ");for(var e=/^`|^ .*?[^ ].* $|`$/.test(t)?" ":"",n="`",r=t.match(/`+/gm)||[];r.indexOf(n)!==-1;)n=n+"`";return n+e+t+e+n}};yc.image={filter:"img",replacement:function(t,e){var n=hZ(e.getAttribute("alt")),r=e.getAttribute("src")||"",o=hZ(e.getAttribute("title")),i=o?' "'+o+'"':"";return r?"!["+n+"]("+r+i+")":""}};Ert.prototype={add:function(t,e){this.array.unshift(e)},keep:function(t){this._keep.unshift({filter:t,replacement:this.keepReplacement})},remove:function(t){this._remove.unshift({filter:t,replacement:function(){return""}})},forNode:function(t){if(t.isBlank)return this.blankRule;var e;return(e=WCe(this.array,t,this.options))||(e=WCe(this._keep,t,this.options))||(e=WCe(this._remove,t,this.options))?e:this.defaultRule},forEach:function(t){for(var e=0;e<this.array.length;e++)t(this.array[e],e)}};ZCe=typeof window<"u"?window:{};SGt=bGt()?ZCe.DOMParser:CGt();NGt=Array.prototype.reduce,OGt=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];gZ.prototype={turndown:function(t){if(!DGt(t))throw new TypeError(t+" is not a string, or an element/document/fragment node.");if(t==="")return"";var e=Art.call(this,new TGt(t,this.options));return RGt.call(this,e)},use:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)this.use(t[e]);else if(typeof t=="function")t(this);else throw new TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(t,e){return this.rules.add(t,e),this},keep:function(t){return this.rules.keep(t),this},remove:function(t){return this.rules.remove(t),this},escape:function(t){return OGt.reduce(function(e,n){return e.replace(n[0],n[1])},t)}};Mrt=gZ});function lL(t){return typeof t=="object"&&t!==null}function cL(t){if(typeof t=="string")return t;if(t==null)return"";try{return typeof t=="object"?JSON.stringify(t):typeof t=="function"||typeof t=="symbol"||typeof t=="bigint"?t.toString():typeof t=="number"||typeof t=="boolean"?String(t):""}catch{return""}}function Drt(t){return t instanceof Error?t.message:cL(t)}async function $Gt(t){await new Promise(e=>window.setTimeout(e,t))}async function $rt(t,e,n,r){let o=Date.now();for(;;){if(t())return;if(Date.now()-o>=e)throw new gf(`${r} timed out after ${e}ms`);await $Gt(n)}}function Ort(t,e){let n=(t??"").trim();if(!n)return"";if(!e)return n;try{return new URL(n,e).href}catch{return n}}function Rrt(t){let e=(t??"").trim();return e?/[\s)]/.test(e)?`<${e}>`:e:""}function FGt(t){let e=new Mrt({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined"});return e.remove(["script","style","noscript"]),e.addRule("webviewer-link",{filter:"a",replacement:(n,r)=>{let o=r,i=o.getAttribute("href")??"",s=Rrt(Ort(i,t)),a=n?.trim()||o.textContent||s;return s?`[${a}](${s})`:a}}),e.addRule("webviewer-image",{filter:"img",replacement:(n,r)=>{let o=r,i=o.getAttribute("alt")??"",s=o.getAttribute("src")??"",a=Rrt(Ort(s,t));return a?`![${i}](${a})`:""}}),e}function JCe(t,e){if(!t.trim())return"";let n=FGt(e),i=new DOMParser().parseFromString(`<div>${t}</div>`,"text/html").body.firstElementChild;return i?n.turndown(i).replace(/\n{3,}/g,`

`).trim():""}function XCe(t){let e=t.commands;return!e||!lL(e)||typeof e.executeCommandById!="function"?null:e}function Frt(t,e){let n=XCe(t);if(!n)return!1;if(n.commands){if(n.commands instanceof Map)return n.commands.has(e);if(typeof n.commands=="object")return e in n.commands}return typeof n.listCommands=="function"?n.listCommands().some(o=>o.id===e):!1}function Urt(t,e){return t.workspace.getLeavesOfType(DP).includes(e)}function Lrt(t){if(!lL(t)||t.enabled!==!0)return null;let e=t.instance;if(!e||!lL(e))return null;let n=e;return typeof n.openUrl=="function"||typeof n.handleOpenUrl=="function"?n:null}function Brt(t,e){let n=t.internalPlugins;if(!n||!lL(n))return null;let r=n.plugins;if(!r)return null;let o=r instanceof Map?r.get(DP):lL(r)?r[DP]:null;if(o){let s=Lrt(o);if(s)return s}let i;if(r instanceof Map)i=Array.from(r.values());else if(lL(r))i=Object.values(r);else return e&&e(),null;for(let s of i){let a=Lrt(s);if(a)return a}return null}var yZ=C(()=>{Nrt();aL()});function uL(t){return{url:typeof t.view?.url=="string"?t.view.url:"",title:typeof t.view?.title=="string"?t.view.title:"",faviconUrl:typeof t.view?.faviconUrl=="string"?t.view.faviconUrl:"",mode:t.view?.mode==="reader"?"reader":"webview"}}async function zrt(t,e={}){let{signal:n}=e;if(n?.aborted)throw new M_("Operation was aborted");try{let r=Promise.resolve(t.view.getReaderModeContent());if(!n){let i=await r;return typeof i?.md=="string"?i.md:""}let o=await new Promise((i,s)=>{let a=()=>{s(new M_("Operation was aborted"))};n.addEventListener("abort",a,{once:!0}),r.then(l=>{n.removeEventListener("abort",a),i(l)}).catch(l=>{n.removeEventListener("abort",a),s(l instanceof Error?l:new Error(String(l)))})});return typeof o?.md=="string"?o.md:""}catch(r){throw r instanceof M_||z("Failed to get reader mode content:",r),r}}async function wZ(t,e=!0){let n=sL(t),r='(() => { try { return window.getSelection?.()?.toString?.() ?? ""; } catch { return ""; } })()';try{let o=await n.executeJavaScript(r),i=cL(o);return e?i.trim():i}catch(o){throw z("Failed to get selected text:",o),o}}async function vZ(t){let e=sL(t),n="";try{n=typeof e.getURL=="function"?e.getURL():""}catch{n=t.view?.url??""}let r=`(() => {
  const sel = window.getSelection();
  if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return "";
  const div = document.createElement("div");
  for (let i = 0; i < sel.rangeCount; i++) div.appendChild(sel.getRangeAt(i).cloneContents());
  return div.innerHTML;
})()`,o="";try{let i=await e.executeJavaScript(r);o=cL(i)}catch(i){throw z("Failed to get selection HTML:",i),i}try{return JCe(o,n)}catch(i){throw z("Failed to convert HTML to Markdown:",i),i}}async function jrt(t){let e=sL(t),n="";try{n=typeof e.getURL=="function"?e.getURL():""}catch{n=t.view?.url??""}let r=`(() => {
    const clone = document.body.cloneNode(true);
    clone.querySelectorAll('script, style, noscript').forEach(el => el.remove());
    return clone.innerHTML;
  })()`,o="";try{let i=await e.executeJavaScript(r);o=cL(i)}catch(i){throw z("Failed to get page HTML:",i),i}try{return JCe(o,n)}catch(i){throw z("Failed to convert page HTML to Markdown:",i),i}}async function Vrt(t,e=!0){let n=sL(t),r=e?'(() => { try { return document.documentElement?.outerHTML ?? ""; } catch { return ""; } })()':'(() => { try { return document.body?.outerHTML ?? ""; } catch { return ""; } })()';try{let o=await n.executeJavaScript(r);return cL(o)}catch(o){throw z("Failed to get HTML:",o),o}}function UGt(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.videoId=="string"&&typeof e.title=="string"&&typeof e.channel=="string"&&(e.description===void 0||typeof e.description=="string")&&(e.uploadDate===void 0||typeof e.uploadDate=="string")&&(e.duration===void 0||typeof e.duration=="string")&&(e.genre===void 0||typeof e.genre=="string")&&Array.isArray(e.transcript)&&e.transcript.every(n=>typeof n=="object"&&n!==null&&typeof n.timestamp=="string"&&typeof n.text=="string")}async function Wrt(t,e={}){let n=sL(t),{timeoutMs:r=1e4}=e,o=Math.ceil(r/500),i="";try{i=typeof n.getURL=="function"?n.getURL():""}catch{i=""}i||(i=t.view?.url??"");let s=k_(i);if(!s)throw new Error("Not a YouTube video page");let a=`(async () => {
    const videoId = ${JSON.stringify(s)};

    // =========================================================================
    // Step 1: Extract video metadata from JSON-LD (structured data)
    // JSON-LD is more reliable than DOM selectors as it's machine-readable
    // =========================================================================
    let title = '';
    let channel = '';
    let description = '';
    let uploadDate = '';
    let duration = '';
    let genre = '';

    // Helper to extract fields from a VideoObject schema
    const extractVideoObject = (data) => {
      if (!data || data['@type'] !== 'VideoObject') return;
      if (!title && data.name && typeof data.name === 'string') {
        title = data.name;
      }
      if (!description && data.description && typeof data.description === 'string') {
        description = data.description;
      }
      if (!uploadDate && data.uploadDate && typeof data.uploadDate === 'string') {
        uploadDate = data.uploadDate;
      }
      // JSON-LD duration is ISO 8601 format (e.g., "PT12M34S"), convert to readable format
      if (!duration && data.duration && typeof data.duration === 'string') {
        const match = data.duration.match(/PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?/);
        if (match) {
          const h = match[1] ? match[1] + ':' : '';
          const m = match[2] || '0';
          const s = match[3] || '0';
          duration = h + (h ? m.padStart(2, '0') : m) + ':' + s.padStart(2, '0');
        }
      }
      if (!genre && data.genre) {
        genre = Array.isArray(data.genre) ? data.genre.join(', ') : String(data.genre);
      }
      // author can be string, object {name}, or array [{name}]
      if (!channel && data.author) {
        const author = data.author;
        if (typeof author === 'string') {
          channel = author;
        } else if (Array.isArray(author) && author[0]?.name) {
          channel = String(author[0].name);
        } else if (author?.name) {
          channel = String(author.name);
        }
      }
    };

    // Parse all JSON-LD scripts, handling various formats (@graph, array, single object)
    const ldJsonEls = document.querySelectorAll('script[type="application/ld+json"]');
    for (const el of ldJsonEls) {
      try {
        const data = JSON.parse(el.textContent || '');
        if (Array.isArray(data)) {
          for (const item of data) {
            extractVideoObject(item);
          }
        } else if (data['@graph'] && Array.isArray(data['@graph'])) {
          for (const item of data['@graph']) {
            extractVideoObject(item);
          }
        } else {
          extractVideoObject(data);
        }
        // Stop if we have all essential fields
        if (title && channel && description) break;
      } catch {}
    }

    // =========================================================================
    // Step 2: Fallback to DOM selectors for missing metadata
    // =========================================================================
    if (!title) {
      title = document.querySelector('h1.ytd-watch-metadata yt-formatted-string')?.textContent?.trim()
           || document.querySelector('#title h1')?.textContent?.trim() || '';
    }
    if (!channel) {
      channel = document.querySelector('#owner #channel-name a')?.textContent?.trim()
             || document.querySelector('#channel-name a')?.textContent?.trim()
             || document.querySelector('#channel-name')?.textContent?.trim() || '';
    }
    if (!duration) {
      duration = document.querySelector('#ytd-player .ytp-time-duration')?.textContent?.trim() || '';
    }

    // =========================================================================
    // Step 3: Find or open the transcript panel
    // Reason: YouTube has two coexisting transcript panel DOM structures:
    // - Classic ("In this video"): ytd-transcript-segment-renderer
    // - Modern ("Transcript"): transcript-segment-view-model
    // YouTube selects the panel type server-side per video. We must support both.
    // All segment queries are scoped to the panel to avoid false matches.
    // =========================================================================

    // Reason: Find panel by checking for transcript segment elements inside it,
    // rather than relying on fragile target-id strings that YouTube changes.
    // Prefer visible panels to avoid picking up hidden/stale panels YouTube
    // leaves in the DOM during page transitions.
    const findTranscriptPanel = () => {
      const panels = document.querySelectorAll('ytd-engagement-panel-section-list-renderer');
      for (const panel of panels) {
        const hasSegments = panel.querySelector('ytd-transcript-segment-renderer')
                         || panel.querySelector('transcript-segment-view-model');
        if (!hasSegments) continue;
        const style = window.getComputedStyle(panel);
        if (style.display !== 'none' && style.visibility !== 'hidden') return panel;
      }
      return null;
    };

    // Reason: Auto-detect classic vs modern layout and use the correct selectors
    // for each. Queries are scoped to the panel to prevent matching unrelated UI.
    const extractFromPanel = (panel) => {
      const classicSegs = panel.querySelectorAll('ytd-transcript-segment-renderer');
      if (classicSegs.length > 0) {
        return [...classicSegs].map(seg => ({
          timestamp: seg.querySelector('.segment-timestamp')?.textContent?.trim() || '',
          text: seg.querySelector('yt-formatted-string.segment-text, .segment-text')?.textContent?.trim() || ''
        })).filter(t => t.timestamp && t.text);
      }
      const modernSegs = panel.querySelectorAll('transcript-segment-view-model');
      if (modernSegs.length > 0) {
        return [...modernSegs].map(seg => ({
          timestamp: seg.querySelector('.ytwTranscriptSegmentViewModelTimestamp')?.textContent?.trim() || '',
          text: [...seg.querySelectorAll('span.yt-core-attributed-string')].map(s => s.textContent || '').join('').trim() || ''
        })).filter(t => t.timestamp && t.text);
      }
      return null;
    };

    let panel = findTranscriptPanel();
    let needClose = false;

    if (!panel) {
      const btn = document.querySelector('ytd-video-description-transcript-section-renderer button')
                || document.querySelector('ytd-video-description-transcript-section-renderer [role="button"]');
      if (btn) {
        btn.click();
        needClose = true;

        // Poll for the panel container to appear (not individual segments)
        for (let i = 0; i < ${o}; i++) {
          await new Promise(r => setTimeout(r, 500));
          panel = findTranscriptPanel();
          if (panel) break;
        }
      }
    }

    // =========================================================================
    // Step 4: Extract transcript segments from the panel
    // =========================================================================

    // Reason: Close via captured panel element rather than hardcoded target-id.
    // This is resilient to YouTube changing the target-id string.
    const closePanel = () => {
      if (!needClose || !panel) return;
      const closeBtn = panel.querySelector('#visibility-button button')
                    || panel.querySelector('#visibility-button [role="button"]');
      if (closeBtn) closeBtn.click();
    };

    try {
      const transcript = panel ? (extractFromPanel(panel) || []) : [];
      return { videoId, title, channel, description, uploadDate, duration, genre, transcript };
    } finally {
      closePanel();
    }
  })()`,l=await n.executeJavaScript(a);if(!UGt(l))throw new Error("Invalid transcript data structure");return l}async function Hrt(t,e,n={}){let{preferCommand:r=!0,focusLeafBeforeCommand:o=!0}=n;if(r)try{return await e(mZ.SAVE_TO_VAULT,{leaf:t,focusLeaf:o}),k("Saved via webviewer:save-to-vault command"),{method:"command"}}catch(i){ee("save-to-vault command failed, falling back:",i)}try{return await Promise.resolve(t.view.saveAsMarkdown()),k("Saved via view.saveAsMarkdown()"),{method:"view.saveAsMarkdown"}}catch(i){throw z("Failed to save Web Viewer page:",i),i}}var QCe=C(()=>{ye();dZ();aL();yZ();dZ()});function wc(t){if(typeof t!="string")return null;let e=t.trim();return e||null}function dL(t){if(typeof t!="string")return null;let e=t.trim();if(!e)return null;try{let n=new URL(e);n.hash="",(n.protocol==="http:"&&n.port==="80"||n.protocol==="https:"&&n.port==="443")&&(n.port=""),n.pathname!=="/"&&(n.pathname=n.pathname.replace(/\/+$/,""));let r=Array.from(n.searchParams.entries());return r.length>0?(r.sort(([o,i],[s,a])=>o!==s?o.localeCompare(s):i.localeCompare(a)),n.search=`?${new URLSearchParams(r).toString()}`):n.search="",n.toString()}catch{return e}}function qrt(t){return wc(t)??void 0}function e_e(t){let e=wc(t.url);if(!e)return null;let n=qrt(t.title),r=qrt(t.faviconUrl);return{url:e,title:n,faviconUrl:r,isLoaded:t.isLoaded,isActive:t.isActive?!0:void 0}}function $P(t){let e=new Map;for(let n of t){let r=e_e(n);if(!r)continue;let o=e.get(r.url);if(!o){e.set(r.url,r);continue}e.set(r.url,{...o,title:r.title??o.title,faviconUrl:r.faviconUrl??o.faviconUrl,isLoaded:r.isLoaded??o.isLoaded,isActive:o.isActive||r.isActive?!0:void 0})}return Array.from(e.values())}function Grt(t){let e=$P(t),n=!1;return e.map(r=>{if(!r.isActive)return r;if(!n)return n=!0,r;let{isActive:o,...i}=r;return i})}var fL=C(()=>{});var BGt,xZ,Yrt=C(()=>{ye();yZ();aL();fL();BGt=["did-finish-load","page-favicon-updated","page-title-updated"],xZ=class t{constructor(e){this.lastActiveLeaf=null;this.activeWebTabState={activeWebTabForMentions:null,activeOrLastWebTab:null};this.activeWebTabLeaf=null;this.activeWebTabListeners=new Set;this.activeWebTabTrackingRefs=null;this.activeWebTabTrackingPreserveViewTypes=[];this.webviewLoadListeners=new Map;this.webviewLoadCallbacks=new Set;this.cancelScheduledWebviewLoadNotify=null;this.app=e.app,this.isSupportedPlatform=e.isSupportedPlatform,this.getActiveLeaf=e.getActiveLeaf,this.getLeaves=e.getLeaves,this.getPageInfo=e.getPageInfo}getLastActiveLeaf(){let e=this.lastActiveLeaf;return!e||!t4(e)?(this.lastActiveLeaf=null,null):Urt(this.app,e)?e:(this.lastActiveLeaf=null,null)}findLeafByUrl(e,n={}){let r=e.trim();if(!r)return null;let o=this.getLeaves();for(let u of o)if(u?.view?.url===r)return u;let i=dL(r);if(!i)return null;let s=[];for(let u of o){let d=u?.view?.url;if(!d)continue;dL(d)===i&&s.push(u)}if(s.length===0)return null;if(s.length===1)return s[0];let a=(n.title??"").trim();if(a){let u=a.toLowerCase(),d=[];for(let f of s)try{let m=(this.getPageInfo(f).title||"").trim();m&&m.toLowerCase()===u&&d.push(f)}catch{}if(d.length===1)return d[0];if(d.length>1){let f=this.getActiveLeaf();if(f&&d.includes(f))return f;let p=this.getLastActiveLeaf();return p&&d.includes(p)?p:(ee("[WebViewerStateManager] Multiple leaves matched URL + title; returning first match.",{url:r,title:a,matches:d.length}),d[0])}}let l=this.getActiveLeaf();if(l&&s.includes(l))return l;let c=this.getLastActiveLeaf();return c&&s.includes(c)?c:(ee("[WebViewerStateManager] Multiple leaves matched URL; returning first match as fallback.",{url:r,matches:s.length}),s[0])}getActiveWebTabState(){return this.activeWebTabState}subscribeActiveWebTabState(e){return this.activeWebTabListeners.add(e),()=>{this.activeWebTabListeners.delete(e)}}subscribeToWebviewLoad(e){return this.webviewLoadCallbacks.add(e),()=>{this.webviewLoadCallbacks.delete(e)}}startActiveWebTabTracking(e={}){this.activeWebTabTrackingRefs&&this.stopActiveWebTabTracking(),this.activeWebTabTrackingPreserveViewTypes=[...e.preserveOnViewTypes??[]];let n=this.app.workspace.on("active-leaf-change",o=>{try{t4(o)&&(this.lastActiveLeaf=o)}catch(i){ee("WebViewerStateManager failed to track active leaf:",i)}this.recomputeActiveWebTabState({trigger:"active-leaf-change",activeLeaf:o}),this.subscribeToWebviewLoadEvents()}),r=this.app.workspace.on("layout-change",()=>{this.recomputeActiveWebTabState({trigger:"layout-change"}),this.subscribeToWebviewLoadEvents()});return this.activeWebTabTrackingRefs={activeLeafRef:n,layoutRef:r},this.recomputeActiveWebTabState({trigger:"active-leaf-change",activeLeaf:this.app.workspace.activeLeaf??null}),this.subscribeToWebviewLoadEvents(),this.activeWebTabTrackingRefs}subscribeToWebviewLoadEvents(){if(!this.isSupportedPlatform()){this.cleanupWebviewLoadListeners();return}try{let e=this.getLeaves(),n=new Set;for(let o of e){let i=o.view?.webview;if(i&&typeof i.addEventListener=="function"&&typeof i.removeEventListener=="function"){n.add(i);let s=this.webviewLoadListeners.get(i);if(s&&s.leaf===o)continue;if(s){for(let c of s.events)i.removeEventListener(c,s.handler);this.webviewLoadListeners.delete(i)}let a=()=>{this.recomputeActiveWebTabState({trigger:"webview-metadata",loadedLeaf:o}),this.scheduleWebviewLoadCallbackNotification()},l={leaf:o,handler:a,events:BGt};for(let c of l.events)i.addEventListener(c,a);this.webviewLoadListeners.set(i,l)}}let r=[];for(let o of this.webviewLoadListeners.keys())n.has(o)||r.push(o);for(let o of r){let i=this.webviewLoadListeners.get(o);if(i){try{for(let s of i.events)o.removeEventListener(s,i.handler)}catch{}this.webviewLoadListeners.delete(o)}}}catch{}}cleanupWebviewLoadListeners(){for(let[e,{handler:n,events:r}]of this.webviewLoadListeners)try{if(typeof e.removeEventListener=="function")for(let o of r)e.removeEventListener(o,n)}catch{}this.webviewLoadListeners.clear()}scheduleWebviewLoadCallbackNotification(){if(this.cancelScheduledWebviewLoadNotify)return;let e=n=>{if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){let o=window.requestAnimationFrame(()=>n());return()=>window.cancelAnimationFrame(o)}let r=window.setTimeout(n,0);return()=>window.clearTimeout(r)};this.cancelScheduledWebviewLoadNotify=e(()=>{this.cancelScheduledWebviewLoadNotify=null,this.notifyWebviewLoadCallbacks()})}notifyWebviewLoadCallbacks(){for(let e of this.webviewLoadCallbacks)try{e()}catch{}}stopActiveWebTabTracking(){this.activeWebTabTrackingRefs=null,this.cleanupWebviewLoadListeners(),this.cancelScheduledWebviewLoadNotify?.(),this.cancelScheduledWebviewLoadNotify=null,this.activeWebTabState={activeWebTabForMentions:null,activeOrLastWebTab:null},this.activeWebTabLeaf=null,this.lastActiveLeaf=null,this.activeWebTabTrackingPreserveViewTypes=[]}recomputeActiveWebTabState(e){if(!this.isSupportedPlatform()){this.setActiveWebTabState({activeWebTabForMentions:null,activeOrLastWebTab:null}),this.activeWebTabLeaf=null;return}let n=this.getActiveLeaf();if(e.trigger==="webview-metadata"){let s=e.loadedLeaf;if(!(s===this.activeWebTabLeaf||s===n))return}let r=this.activeWebTabLeaf,o=this.activeWebTabState.activeWebTabForMentions;if(n)r=n,o=this.toWebTabContext(n);else if(e.trigger==="active-leaf-change"){let s=e.activeLeaf?.view?.getViewType();!!(s&&this.activeWebTabTrackingPreserveViewTypes.includes(s))||(r=null,o=null)}if(e.trigger!=="webview-metadata"&&r&&(this.getLeaves().includes(r)||(r=null,o=null)),e.trigger==="layout-change")r&&(o=this.toWebTabContext(r));else if(e.trigger==="webview-metadata"){let s=e.loadedLeaf;r=s,o=this.toWebTabContext(s)}this.activeWebTabLeaf=r;let i=this.computeActiveOrLastWebTabContext();this.setActiveWebTabState({activeWebTabForMentions:o,activeOrLastWebTab:i})}computeActiveOrLastWebTabContext(){try{let e=this.getActiveLeaf()??this.getLastActiveLeaf();return e?this.toWebTabContext(e):null}catch{return null}}toWebTabContext(e){try{let n=this.getPageInfo(e),r=(n.url||"").trim();if(!r)return null;let o=(n.title||"").trim(),i=(n.faviconUrl||"").trim();return{url:r,title:o||void 0,faviconUrl:i||void 0}}catch{return null}}setActiveWebTabState(e){let n=this.activeWebTabState;t.areWebTabContextsEqual(n.activeWebTabForMentions,e.activeWebTabForMentions)&&t.areWebTabContextsEqual(n.activeOrLastWebTab,e.activeOrLastWebTab)||(this.activeWebTabState=e,this.notifyActiveWebTabListeners())}notifyActiveWebTabListeners(){for(let e of this.activeWebTabListeners)try{e(this.activeWebTabState)}catch(n){ee("[WebViewerStateManager] Error in Active Web Tab listener:",n)}}static areWebTabContextsEqual(e,n){return e===n?!0:!e||!n?!1:e.url===n.url&&e.title===n.title&&e.faviconUrl===n.faviconUrl}}});var Zrt,bZ,Jrt=C(()=>{Zrt=require("obsidian");ye();QCe();yZ();Yrt();aL();bZ=class{constructor(e){this.internalPluginApi=null;this.internalApiWarned=!1;this.app=e,this.stateManager=new xZ({app:e,isSupportedPlatform:()=>this.isSupportedPlatform(),getActiveLeaf:()=>this.getActiveLeaf(),getLeaves:()=>this.getLeaves(),getPageInfo:n=>uL(n)})}isSupportedPlatform(){return Zrt.Platform.isDesktopApp===!0}getAvailability(){let e=this.isSupportedPlatform()?"desktop":"mobile";return this.isSupportedPlatform()?this.getLeaves().length>0?{supported:!0,available:!0,platform:e}:this.getInternalPluginApi()?{supported:!0,available:!0,platform:e}:Frt(this.app,mZ.OPEN)?{supported:!0,available:!0,platform:e,reason:"No Web Viewer leaves open, but Web Viewer commands are registered."}:{supported:!0,available:!1,platform:e,reason:"Web Viewer does not appear available."}:{supported:!1,available:!1,platform:e,reason:"Web Viewer is not supported on mobile platforms."}}assertAvailable(){let e=this.getAvailability();if(!e.supported)throw new fZ(e.reason??"Web Viewer unsupported.");if(!e.available)throw new gf(e.reason??"Web Viewer is not available.")}getLeaves(){return this.isSupportedPlatform()?this.app.workspace.getLeavesOfType(DP):[]}getActiveLeaf(){let e=this.app.workspace.getMostRecentLeaf();return t4(e)?e:null}getLastActiveLeaf(){return this.stateManager.getLastActiveLeaf()}async resolveLeaf(e={}){this.assertAvailable();let{strategy:n="active-or-last",focus:r=!1,requireWebviewReady:o=!1,timeoutMs:i=15e3}=e,s=this.getActiveLeaf();if(s)return r&&this.app.workspace.setActiveLeaf(s,{focus:!0}),o&&await this.waitForWebviewReady(s,i),s;if(n==="active-or-last"||n==="active-or-last-or-any"){let a=this.getLastActiveLeaf();if(a)return r&&this.app.workspace.setActiveLeaf(a,{focus:!0}),o&&await this.waitForWebviewReady(a,i),a}if(n==="active-or-last-or-any"){let a=this.getLeaves()[0];if(a)return r&&this.app.workspace.setActiveLeaf(a,{focus:!0}),o&&await this.waitForWebviewReady(a,i),a}throw new pZ("No Web Viewer leaf found.")}async waitForWebviewReady(e,n){let r=e.view;r.webviewMounted===void 0||r.webviewFirstLoadFinished===void 0||r.webviewMounted&&r.webviewFirstLoadFinished||await $rt(()=>!!(r.webviewMounted&&r.webviewFirstLoadFinished),n,100,"Waiting for Web Viewer webview ready")}findLeafByUrl(e,n={}){return this.stateManager.findLeafByUrl(e,n)}getActiveWebTabState(){return this.stateManager.getActiveWebTabState()}subscribeActiveWebTabState(e){return this.stateManager.subscribeActiveWebTabState(e)}subscribeToWebviewLoad(e){return this.stateManager.subscribeToWebviewLoad(e)}startActiveWebTabTracking(e={}){return this.stateManager.startActiveWebTabTracking(e)}stopActiveWebTabTracking(){this.stateManager.stopActiveWebTabTracking()}async executeCommand(e,n={}){let r=XCe(this.app);if(!r)throw new gf("Command manager unavailable.");let{leaf:o,focusLeaf:i=!1}=n;o&&i&&this.app.workspace.setActiveLeaf(o,{focus:!0});try{if(r.executeCommandById(e)===!1)throw new gf(`Command returned false: ${e}`)}catch(s){throw z(`Failed to execute command ${e}:`,s),new gf(`Failed to execute command ${e}: ${Drt(s)}`)}}getInternalPluginApi(){if(this.internalPluginApi)return this.internalPluginApi;let e=Brt(this.app,()=>{this.internalApiWarned||(this.internalApiWarned=!0,ee("[WebViewerService] internalPlugins.plugins has unexpected structure. Web Viewer integration may not work correctly."))});return e&&(this.internalPluginApi=e),e}getPageInfo(e){return uL(e)}async getReaderModeMarkdown(e,n){return zrt(e,n)}async getSelectedText(e,n=!0){return wZ(e,n)}async getSelectedMarkdown(e){return vZ(e)}async getPageMarkdown(e){return jrt(e)}async getHtml(e,n=!0){return Vrt(e,n)}getYouTubeVideoId(e){return k_(e)}isYouTubeVideoUrl(e){return jCe(e)}async getYouTubeTranscript(e,n){return Wrt(e,n)}async saveToVault(e,n={}){return Hrt(e,(r,o)=>this.executeCommand(r,o),n)}}});var Qrt={};zn(Qrt,{getWebViewerMarkdown:()=>zGt,getWebViewerPageInfo:()=>WGt,getWebViewerSelectedMarkdown:()=>VGt,getWebViewerSelectedText:()=>jGt,getWebViewerService:()=>ls,resolveWebViewerLeaf:()=>pL,saveWebViewerToVault:()=>HGt,startActiveWebTabTracking:()=>t_e});function ls(t){let e=Xrt.get(t);if(e)return e;let n=new bZ(t);return Xrt.set(t,n),n}function t_e(t,e){return ls(t).startActiveWebTabTracking(e)}async function pL(t,e){return ls(t).resolveLeaf(e)}async function zGt(t,e){let n=await pL(t,e);return ls(t).getReaderModeMarkdown(n)}async function jGt(t,e=!0,n){let r=await pL(t,n);return ls(t).getSelectedText(r,e)}async function VGt(t,e){let n=await pL(t,e);return ls(t).getSelectedMarkdown(n)}async function WGt(t,e){let n=await pL(t,e);return ls(t).getPageInfo(n)}async function HGt(t,e,n){let r=await pL(t,{...n,focus:!0});return ls(t).saveToVault(r,e)}var Xrt,FP=C(()=>{Jrt();Xrt=new WeakMap});var W4=Tt((_ut,fJ)=>{((t,e)=>{typeof define=="function"&&define.amd?define([],e):typeof fJ=="object"&&fJ.exports?fJ.exports=e():t.fuzzysort=e()})(_ut,t=>{"use strict";var e=(j,G)=>{if(!j||!G)return H;var J=p(j);W(G)||(G=f(G));var M=J.bitflags;return(M&G._bitflags)!==M?H:h(J,G)},n=(j,G,J)=>{if(!j)return J?.all?m(G,J):V;var M=p(j),E=M.bitflags,R=M.containsSpace,L=u(J?.threshold||0),K=J?.limit||F,Y=0,re=0,ae=G.length;function ve($r){Y<K?(me.add($r),++Y):(++re,$r._score>me.peek()._score&&me.replaceTop($r))}if(J?.key)for(var Te=J.key,Ee=0;Ee<ae;++Ee){var nt=G[Ee],rt=B(nt,Te);if(rt&&(W(rt)||(rt=f(rt)),(E&rt._bitflags)===E)){var Jt=h(M,rt);Jt!==H&&(Jt._score<L||(Jt.obj=nt,ve(Jt)))}}else if(J?.keys){var ke=J.keys,Ln=ke.length;e:for(var Ee=0;Ee<ae;++Ee){var nt=G[Ee];{for(var He=0,Ie=0;Ie<Ln;++Ie){var Te=ke[Ie],rt=B(nt,Te);if(!rt){D[Ie]=te;continue}W(rt)||(rt=f(rt)),D[Ie]=rt,He|=rt._bitflags}if((E&He)!==E)continue}if(R)for(let Bn=0;Bn<M.spaceSearches.length;Bn++)A[Bn]=Z;for(var Ie=0;Ie<Ln;++Ie){if(rt=D[Ie],rt===te){$[Ie]=te;continue}if($[Ie]=h(M,rt,!1,R),$[Ie]===H){$[Ie]=te;continue}if(R)for(let Tr=0;Tr<M.spaceSearches.length;Tr++){if(O[Tr]>-1e3&&A[Tr]>Z){var dt=(A[Tr]+O[Tr])/4;dt>A[Tr]&&(A[Tr]=dt)}O[Tr]>A[Tr]&&(A[Tr]=O[Tr])}}if(R){for(let Bn=0;Bn<M.spaceSearches.length;Bn++)if(A[Bn]===Z)continue e}else{var Me=!1;for(let Bn=0;Bn<Ln;Bn++)if($[Bn]._score!==Z){Me=!0;break}if(!Me)continue}var Ue=new a(Ln);for(let Bn=0;Bn<Ln;Bn++)Ue[Bn]=$[Bn];if(R){var it=0;for(let Bn=0;Bn<M.spaceSearches.length;Bn++)it+=A[Bn]}else{var it=Z;for(let Tr=0;Tr<Ln;Tr++){var Jt=Ue[Tr];if(Jt._score>-1e3&&it>Z){var dt=(it+Jt._score)/4;dt>it&&(it=dt)}Jt._score>it&&(it=Jt._score)}}if(Ue.obj=nt,Ue._score=it,J?.scoreFn){if(it=J.scoreFn(Ue),!it)continue;it=u(it),Ue._score=it}it<L||ve(Ue)}}else for(var Ee=0;Ee<ae;++Ee){var rt=G[Ee];if(rt&&(W(rt)||(rt=f(rt)),(E&rt._bitflags)===E)){var Jt=h(M,rt);Jt!==H&&(Jt._score<L||ve(Jt))}}if(Y===0)return V;for(var St=new Array(Y),Ee=Y-1;Ee>=0;--Ee)St[Ee]=me.poll();return St.total=Y+re,St},r=(j,G="<b>",J="</b>")=>{for(var M=typeof G=="function"?G:void 0,E=j.target,R=E.length,L=j.indexes,K="",Y=0,re=0,ae=!1,ve=[],Te=0;Te<R;++Te){var Ee=E[Te];if(L[re]===Te){if(++re,ae||(ae=!0,M?(ve.push(K),K=""):K+=G),re===L.length){M?(K+=Ee,ve.push(M(K,Y++)),K="",ve.push(E.substr(Te+1))):K+=Ee+J+E.substr(Te+1);break}}else ae&&(ae=!1,M?(ve.push(M(K,Y++)),K=""):K+=J);K+=Ee}return M?ve:K},o=j=>{typeof j=="number"?j=""+j:typeof j!="string"&&(j="");var G=w(j);return l(j,{_targetLower:G._lower,_targetLowerCodes:G.lowerCodes,_bitflags:G.bitflags})},i=()=>{b.clear(),_.clear()};class s{get indexes(){return this._indexes.slice(0,this._indexes.len).sort((G,J)=>G-J)}set indexes(G){return this._indexes=G}highlight(G,J){return r(this,G,J)}get score(){return c(this._score)}set score(G){this._score=u(G)}}class a extends Array{get score(){return c(this._score)}set score(G){this._score=u(G)}}var l=(j,G)=>{let J=new s;return J.target=j,J.obj=G.obj??H,J._score=G._score??Z,J._indexes=G._indexes??[],J._targetLower=G._targetLower??"",J._targetLowerCodes=G._targetLowerCodes??H,J._nextBeginningIndexes=G._nextBeginningIndexes??H,J._bitflags=G._bitflags??0,J},c=j=>j===Z?0:j>1?j:Math.E**(((-j+1)**.04307-1)*-2),u=j=>j===0?Z:j>1?j:1-Math.pow(Math.log(j)/-2+1,1/.04307),d=j=>{typeof j=="number"?j=""+j:typeof j!="string"&&(j=""),j=j.trim();var G=w(j),J=[];if(G.containsSpace){var M=j.split(/\s+/);M=[...new Set(M)];for(var E=0;E<M.length;E++)if(M[E]!==""){var R=w(M[E]);J.push({lowerCodes:R.lowerCodes,_lower:M[E].toLowerCase(),containsSpace:!1})}}return{lowerCodes:G.lowerCodes,_lower:G._lower,containsSpace:G.containsSpace,bitflags:G.bitflags,spaceSearches:J}},f=j=>{if(j.length>999)return o(j);var G=b.get(j);return G!==void 0||(G=o(j),b.set(j,G)),G},p=j=>{if(j.length>999)return d(j);var G=_.get(j);return G!==void 0||(G=d(j),_.set(j,G)),G},m=(j,G)=>{var J=[];J.total=j.length;var M=G?.limit||F;if(G?.key)for(var E=0;E<j.length;E++){var R=j[E],L=B(R,G.key);if(L!=H){W(L)||(L=f(L));var K=l(L.target,{_score:L._score,obj:R});if(J.push(K),J.length>=M)return J}}else if(G?.keys)for(var E=0;E<j.length;E++){for(var R=j[E],Y=new a(G.keys.length),re=G.keys.length-1;re>=0;--re){var L=B(R,G.keys[re]);if(!L){Y[re]=te;continue}W(L)||(L=f(L)),L._score=Z,L._indexes.len=0,Y[re]=L}if(Y.obj=R,Y._score=Z,J.push(Y),J.length>=M)return J}else for(var E=0;E<j.length;E++){var L=j[E];if(L!=H&&(W(L)||(L=f(L)),L._score=Z,L._indexes.len=0,J.push(L),J.length>=M))return J}return J},h=(j,G,J=!1,M=!1)=>{if(J===!1&&j.containsSpace)return g(j,G,M);for(var E=j._lower,R=j.lowerCodes,L=R[0],K=G._targetLowerCodes,Y=R.length,re=K.length,Ee=0,ae=0,ve=0;;){var Te=L===K[ae];if(Te){if(T[ve++]=ae,++Ee,Ee===Y)break;L=R[Ee]}if(++ae,ae>=re)return H}var Ee=0,nt=!1,rt=0,Jt=G._nextBeginningIndexes;Jt===H&&(Jt=G._nextBeginningIndexes=x(G.target)),ae=T[0]===0?0:Jt[T[0]-1];var ke=0;if(ae!==re)for(;;)if(ae>=re){if(Ee<=0||(++ke,ke>200))break;--Ee;var Ln=S[--rt];ae=Jt[Ln]}else{var Te=R[Ee]===K[ae];if(Te){if(S[rt++]=ae,++Ee,Ee===Y){nt=!0;break}++ae}else ae=Jt[ae]}var He=Y<=1?-1:G._targetLower.indexOf(E,T[0]),Ie=!!~He,dt=Ie?He===0||G._nextBeginningIndexes[He-1]===He:!1;if(Ie&&!dt){for(var Me=0;Me<Jt.length;Me=Jt[Me])if(!(Me<=He)){for(var Ue=0;Ue<Y&&R[Ue]===G._targetLowerCodes[Me+Ue];Ue++);if(Ue===Y){He=Me,dt=!0;break}}}var it=Bn=>{for(var Tr=0,Px=0,Zi=1;Zi<Y;++Zi)Bn[Zi]-Bn[Zi-1]!==1&&(Tr-=Bn[Zi],++Px);var Hh=Bn[Y-1]-Bn[0]-(Y-1);if(Tr-=(12+Hh)*Px,Bn[0]!==0&&(Tr-=Bn[0]*Bn[0]*.2),!nt)Tr*=1e3;else{for(var _d=1,Zi=Jt[0];Zi<re;Zi=Jt[Zi])++_d;_d>24&&(Tr*=(_d-24)*10)}return Tr-=(re-Y)/2,Ie&&(Tr/=1+Y*Y*1),dt&&(Tr/=1+Y*Y*1),Tr-=(re-Y)/2,Tr};if(nt)if(dt){for(var Me=0;Me<Y;++Me)T[Me]=He+Me;var St=T,$r=it(T)}else var St=S,$r=it(S);else{if(Ie)for(var Me=0;Me<Y;++Me)T[Me]=He+Me;var St=T,$r=it(St)}G._score=$r;for(var Me=0;Me<Y;++Me)G._indexes[Me]=St[Me];G._indexes.len=Y;let oo=new s;return oo.target=G.target,oo._score=G._score,oo._indexes=G._indexes,oo},g=(j,G,J)=>{for(var M=new Set,E=0,R=H,L=0,K=j.spaceSearches,Y=K.length,re=0,ae=()=>{for(let dt=re-1;dt>=0;dt--)G._nextBeginningIndexes[P[dt*2+0]]=P[dt*2+1]},ve=!1,Ie=0;Ie<Y;++Ie){O[Ie]=Z;var Te=K[Ie];if(R=h(Te,G),J){if(R===H)continue;ve=!0}else if(R===H)return ae(),H;var Ee=Ie===Y-1;if(!Ee){var nt=R._indexes,rt=!0;for(let Me=0;Me<nt.len-1;Me++)if(nt[Me+1]-nt[Me]!==1){rt=!1;break}if(rt){var Jt=nt[nt.len-1]+1,ke=G._nextBeginningIndexes[Jt-1];for(let Me=Jt-1;Me>=0&&ke===G._nextBeginningIndexes[Me];Me--)G._nextBeginningIndexes[Me]=Jt,P[re*2+0]=Me,P[re*2+1]=ke,re++}}E+=R._score/Y,O[Ie]=R._score/Y,R._indexes[0]<L&&(E-=(L-R._indexes[0])*2),L=R._indexes[0];for(var Ln=0;Ln<R._indexes.len;++Ln)M.add(R._indexes[Ln])}if(J&&!ve)return H;ae();var He=h(j,G,!0);if(He!==H&&He._score>E){if(J)for(var Ie=0;Ie<Y;++Ie)O[Ie]=He._score/Y;return He}J&&(R=G),R._score=E;var Ie=0;for(let dt of M)R._indexes[Ie++]=dt;return R._indexes.len=Ie,R},y=j=>j.replace(/\p{Script=Latin}+/gu,G=>G.normalize("NFD")).replace(/[\u0300-\u036f]/g,""),w=j=>{j=y(j);for(var G=j.length,J=j.toLowerCase(),M=[],E=0,R=!1,L=0;L<G;++L){var K=M[L]=J.charCodeAt(L);if(K===32){R=!0;continue}var Y=K>=97&&K<=122?K-97:K>=48&&K<=57?26:K<=127?30:31;E|=1<<Y}return{lowerCodes:M,bitflags:E,containsSpace:R,_lower:J}},v=j=>{for(var G=j.length,J=[],M=0,E=!1,R=!1,L=0;L<G;++L){var K=j.charCodeAt(L),Y=K>=65&&K<=90,re=Y||K>=97&&K<=122||K>=48&&K<=57,ae=Y&&!E||!R||!re;E=Y,R=re,ae&&(J[M++]=L)}return J},x=j=>{j=y(j);for(var G=j.length,J=v(j),M=[],E=J[0],R=0,L=0;L<G;++L)E>L?M[L]=E:(E=J[++R],M[L]=E===void 0?G:E);return M},b=new Map,_=new Map,T=[],S=[],P=[],A=[],O=[],D=[],$=[],B=(j,G)=>{var J=j[G];if(J!==void 0)return J;if(typeof G=="function")return G(j);var M=G;Array.isArray(G)||(M=G.split("."));for(var E=M.length,R=-1;j&&++R<E;)j=j[M[R]];return j},W=j=>typeof j=="object"&&typeof j._bitflags=="number",F=1/0,Z=-F,V=[];V.total=0;var H=null,te=o(""),fe=j=>{var G=[],J=0,M={},E=R=>{for(var L=0,K=G[L],Y=1;Y<J;){var re=Y+1;L=Y,re<J&&G[re]._score<G[Y]._score&&(L=re),G[L-1>>1]=G[L],Y=1+(L<<1)}for(var ae=L-1>>1;L>0&&K._score<G[ae]._score;ae=(L=ae)-1>>1)G[L]=G[ae];G[L]=K};return M.add=R=>{var L=J;G[J++]=R;for(var K=L-1>>1;L>0&&R._score<G[K]._score;K=(L=K)-1>>1)G[L]=G[K];G[L]=R},M.poll=R=>{if(J!==0){var L=G[0];return G[0]=G[--J],E(),L}},M.peek=R=>{if(J!==0)return G[0]},M.replaceTop=R=>{G[0]=R,E()},M},me=fe();return{single:e,go:n,prepare:o,cleanup:i}})});var Sht={};zn(Sht,{ContextCompactor:()=>v0e});var v0e,Tht=C(()=>{ye();eP();Kr();v0e=class t{constructor(){this.MIN_ITEM_SIZE=5e4;this.MAX_CONCURRENCY=3;this.TEMPERATURE=.1;this.MAX_ITEM_SIZE=5e5;this.BLOCK_TYPES=["note_context","active_note","url_content","selected_text","embedded_note","embedded_pdf","web_tab_context","active_web_tab","youtube_video_context"];this.PROMPT=`Summarize the following content, preserving:
- Key concepts and main ideas
- Important facts, names, and dates
- Technical details relevant for Q&A

Keep the summary concise but information-dense. Output only the summary.

Title: {title}
Path: {path}

Content:
{content}

Summary:`;this.URL_BASED_TYPES=["url_content","web_tab_context","active_web_tab","youtube_video_context"];this.chatModelManager=Np.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async compact(e){let n=e.length;k(`[ContextCompactor] Starting compaction of ${n} chars`);let r=this.parseItems(e);if(r.length===0)return this.noOpResult(e);let o=await this.summarizeItems(r);if(o.size===0)return this.noOpResult(e);let i=this.rebuild(e,r,o);return k(`[ContextCompactor] Done: ${n} -> ${i.length} chars (${((1-i.length/n)*100).toFixed(0)}% reduction)`),{content:i,wasCompacted:!0,originalCharCount:n,compactedCharCount:i.length,itemsProcessed:r.length,itemsSummarized:o.size}}noOpResult(e){return{content:e,wasCompacted:!1,originalCharCount:e.length,compactedCharCount:e.length,itemsProcessed:0,itemsSummarized:0}}parseItems(e){let n=[];for(let r of this.BLOCK_TYPES){let o=new RegExp(`<${r}>[\\s\\S]*?<\\/${r}>`,"g"),i;for(;(i=o.exec(e))!==null;){let s=this.parseBlock(i[0],r,i.index);s&&n.push(s)}}return n.sort((r,o)=>r.startIndex-o.startIndex),n.filter((r,o)=>!n.some((i,s)=>o!==s&&i.startIndex<=r.startIndex&&i.endIndex>=r.endIndex))}parseBlock(e,n,r){let o=c=>new RegExp(`<${c}>([^<]*)</${c}>`).exec(e)?.[1]||"",i=()=>/<content>([\s\S]*?)<\/content>/.exec(e)?.[1]||"",s=o("path")||o("url"),a=o("title")||s.split("/").pop()||"Untitled",l=i();return{type:n,path:s,title:a,content:l,metadata:{ctime:o("ctime"),mtime:o("mtime")},originalXml:e,startIndex:r,endIndex:r+e.length}}async summarizeItems(e){let n=new Map,r=e.map((o,i)=>({index:i,item:o})).filter(({item:o})=>o.content.length>=this.MIN_ITEM_SIZE);if(r.length===0)return n;k(`[ContextCompactor] Summarizing ${r.length} items`);for(let o=0;o<r.length;o+=this.MAX_CONCURRENCY){let i=r.slice(o,o+this.MAX_CONCURRENCY);(await Promise.all(i.map(async({index:a,item:l})=>{try{return{index:a,summary:await this.summarize(l)}}catch(c){return k(`[ContextCompactor] Failed to summarize item ${a}:`,c),{index:a,summary:null}}}))).forEach(({index:a,summary:l})=>{l&&n.set(a,l)})}return n.size<r.length*.5?(k("[ContextCompactor] High failure rate, aborting compaction"),new Map):n}async summarize(e){let n=e.content;n.length>this.MAX_ITEM_SIZE&&(n=n.slice(0,this.MAX_ITEM_SIZE)+`
[TRUNCATED]`);let r=this.PROMPT.replace("{title}",e.title).replace("{path}",e.path).replace("{content}",n),i=await(await this.chatModelManager.getChatModelWithTemperature(this.TEMPERATURE)).invoke([new Zo(r)]);return typeof i.content=="string"?i.content.trim():""}rebuild(e,n,r){let o=e;return Array.from(r.keys()).sort((i,s)=>s-i).forEach(i=>{let s=n[i],a=r.get(i),l=this.buildBlock(s,a);o=o.slice(0,s.startIndex)+l+o.slice(s.endIndex)}),o}buildBlock(e,n){let r=[`<${e.type}>`];if(e.title&&r.push(`<title>${e.title}</title>`),e.path){let o=this.URL_BASED_TYPES.includes(e.type)?"url":"path";r.push(`<${o}>${e.path}</${o}>`)}return e.metadata.ctime&&r.push(`<ctime>${e.metadata.ctime}</ctime>`),e.metadata.mtime&&r.push(`<mtime>${e.metadata.mtime}</mtime>`),r.push(`<content>[SUMMARIZED]
${n}</content>`),r.push(`</${e.type}>`),r.join(`
`)}}});var Son={};zn(Son,{default:()=>WQ});module.exports=fwt(Son);Zg();Ir();ye();TC();var JN=class t{constructor(e){this.memoryCache=new Map;this.cacheDir=e}static getInstance(e=".copilot/file-content-cache"){return t.instance||(t.instance=new t(e)),t.instance}async ensureCacheDir(){await app.vault.adapter.exists(this.cacheDir)||(k("Creating file cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e,n){let r=`${e.path}:${e.stat.size}:${e.stat.mtime}${n?`:${n}`:""}`;return Jc(r)}getCachePath(e){return`${this.cacheDir}/${e}.md`}async get(e){try{let n=this.memoryCache.get(e);if(n)return k("Memory cache hit for file:",e),n.content;let r=this.getCachePath(e);if(await app.vault.adapter.exists(r)){k("File cache hit:",e);let o=await app.vault.adapter.read(r),i,s=o.trim();if(s.startsWith("{")&&s.endsWith("}")||s.startsWith("[")&&s.endsWith("]"))try{i=JSON.parse(o)}catch{i=o}else i=o;let a={content:i,timestamp:Date.now()};return this.memoryCache.set(e,a),a.content}return k("Cache miss for file:",e),null}catch(n){return z("Error reading from file cache:",n),null}}async set(e,n){try{await this.ensureCacheDir();let r=this.getCachePath(e),o=Date.now(),i={content:n,timestamp:o};this.memoryCache.set(e,i);let s;typeof n=="string"?s=n:s=JSON.stringify(n,null,2),await app.vault.adapter.write(r,s),k("Cached file content:",e)}catch(r){z("Error writing to file cache:",r)}}async remove(e){try{this.memoryCache.delete(e);let n=this.getCachePath(e);await app.vault.adapter.exists(n)&&(await app.vault.adapter.remove(n),k("Removed file from cache:",e))}catch(n){z("Error removing file from cache:",n)}}async clear(){try{if(this.memoryCache.clear(),await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);k("Clearing file cache, removing files:",e.files.length);for(let n of e.files)await app.vault.adapter.remove(n)}}catch(e){z("Error clearing file cache:",e)}}};ye();fc();Id();Id();var mG=require("obsidian"),Ba=Jh(),za=Oo([]),H2t=Oo(t=>t(za).map(e=>e.project));function L5e(){return Wl(H2t,{store:Ba})}function Sp(){return Ba.get(za)}function QN(){return Ba.get(za).map(t=>t.project)}function ef(t){return Ba.get(za).find(e=>e.project.id===t)}function eO(t){return Ba.get(za).find(e=>e.filePath===t)}function uB(t){Ba.set(za,t)}function uye(t,e){let n=Ba.get(za),r=n.findIndex(o=>o.filePath===t);if(r!==-1){let o=n.filter((s,a)=>a===r||s.project.id!==e.project.id),i=o.findIndex(s=>s.filePath===t);o[i]=e,Ba.set(za,o)}else{let o=n.filter(i=>i.project.id!==e.project.id);Ba.set(za,[...o,e])}}function m0(t){let e=Ba.get(za),n=e.findIndex(r=>r.project.id===t.project.id);if(n!==-1){let r=[...e];r[n]=t,Ba.set(za,r)}else Ba.set(za,[...e,t])}function D5e(t){let e=Ba.get(za);Ba.set(za,e.filter(n=>n.project.id!==t))}function AC(t){let e=Ba.get(za);Ba.set(za,e.filter(n=>n.filePath!==t))}function $5e(t){return Ba.sub(za,()=>{t(Ba.get(za))})}var XN=new Map;function tf(t){let e=(0,mG.normalizePath)(t);XN.set(e,(XN.get(e)??0)+1)}function Ju(t){let e=(0,mG.normalizePath)(t),n=(XN.get(e)??0)-1;n<=0?XN.delete(e):XN.set(e,n)}function th(t){return(XN.get((0,mG.normalizePath)(t))??0)>0}TC();var hG=require("obsidian");Hx();Uge();var K2t=".copilot/file-content-cache";function dye(t,e){let n=t?.fileContexts?.[e];return!n?.cacheKey||typeof n.cacheKey!="string"||!n.cacheKey.trim()?null:{cacheKey:n.cacheKey,cachePath:`${K2t}/${n.cacheKey}.md`}}var kC=class kC{constructor(){this.cacheDir=".copilot/project-context-cache";this.memoryCache=new Map;this.projectMutexMap=new Map;this.mutexCreationMutex=new f0;this.handleFileEvent=e=>{e instanceof hG.TFile&&this.debouncedHandleFileChange(e)};this.handleFileChange=async e=>{try{if(e.extension!=="md")return;let n=QN();for(let r of n){let{inclusions:o,exclusions:i}=Bo({inclusions:r.contextSource.inclusions,exclusions:r.contextSource.exclusions,isProject:!0});Qr(e,o,i,!0)&&(await this.invalidateMarkdownContext(r),k(`Invalidated markdown context for project ${r.name} due to file change: ${e.path}`))}}catch(n){z("Error handling file change for project context cache:",n)}};this.debouncedHandleFileChange=Li(e=>{this.handleFileChange(e)},kC.DEBOUNCE_DELAY,{leading:!0,trailing:!0});this.vault=app.vault,this.fileCache=JN.getInstance(),this.initializeEventListeners()}static getInstance(){return kC.instance||(kC.instance=new kC),kC.instance}cleanup(){this.debouncedHandleFileChange.cancel(),this.vault.off("create",this.handleFileEvent),this.vault.off("modify",this.handleFileEvent),this.vault.off("delete",this.handleFileEvent),this.vault.off("rename",this.handleFileEvent),this.projectMutexMap.clear()}initializeEventListeners(){this.vault.on("create",this.handleFileEvent),this.vault.on("modify",this.handleFileEvent),this.vault.on("delete",this.handleFileEvent),this.vault.on("rename",this.handleFileEvent)}async ensureCacheDir(){await this.vault.adapter.exists(this.cacheDir)||(k("Creating project context cache directory:",this.cacheDir),await this.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){return Jc(e.id)}getCachePath(e){return`${this.cacheDir}/${e}.json`}async getOrCreateProjectMutex(e){let n=e.id,r=this.projectMutexMap.get(n);return r||await this.mutexCreationMutex.runExclusive(async()=>{let o=this.projectMutexMap.get(n);if(o)return o;let i=new f0;return this.projectMutexMap.set(n,i),k(`Created new mutex for project: ${e.name} (ID: ${n})`),i})}async get(e){try{let n=this.getCacheKey(e),r=this.memoryCache.get(n);if(r)return k("Memory cache hit for project:",e.name),r;let o=this.getCachePath(n);if(await this.vault.adapter.exists(o)){k("File cache hit for project:",e.name);let i=await this.vault.adapter.read(o),s=JSON.parse(i);return this.memoryCache.set(n,s),s}return k("Cache miss for project:",e.name),null}catch(n){return z("Error reading from project context cache:",n),null}}async getOrInitializeCache(e){let n=await this.get(e);if(n)return k(`[getOrInitializeCache] Project ${e.name}: Existing cache found. MarkdownNeedsReload: ${n.markdownNeedsReload}`),n;k(`[getOrInitializeCache] Project ${e.name}: No existing cache found, building fresh context.`);let r=this.createEmptyCache();return await this.setWithoutMutex(e,r),r}getSync(e){try{let n=this.getCacheKey(e),r=this.memoryCache.get(n);return r?(k("Memory cache hit for project:",e.name),r):(k("Memory cache miss for project:",e.name),null)}catch(n){return z("Error reading from project context memory cache:",n),null}}async set(e,n){let r=await this.getOrCreateProjectMutex(e);return r.isLocked()&&k(`Waiting for project cache lock for project: ${e.name}`),await r.runExclusive(async()=>(k(`Acquired cache lock for project: ${e.name}`),await this.setWithoutMutex(e,n)))}async setWithoutMutex(e,n){try{await this.ensureCacheDir();let r=this.getCacheKey(e),o=this.getCachePath(r);k("Caching context for project:",e.name);let i=JSON.parse(JSON.stringify(n));this.memoryCache.set(r,i),await this.vault.adapter.write(o,JSON.stringify(i))}catch(r){throw z("Error writing to project context cache:",r),r}}createEmptyCache(){return{markdownContext:"",webContexts:{},youtubeContexts:{},fileContexts:{},timestamp:Date.now(),markdownNeedsReload:!0}}async clearAllCache(){try{let e=new Set;for(let n of Array.from(this.memoryCache.values()))if(n?.fileContexts)for(let r in n.fileContexts)n.fileContexts[r]?.cacheKey&&e.add(n.fileContexts[r].cacheKey);if(this.memoryCache.clear(),await this.vault.adapter.exists(this.cacheDir)){let n=await this.vault.adapter.list(this.cacheDir);k("Clearing project context cache, removing files:",n.files.length),await Promise.all(n.files.map(r=>this.vault.adapter.remove(r)))}for(let n of e)await this.fileCache.remove(n);k(`Cleared ${e.size} file content cache entries associated with projects`)}catch(e){z("Error clearing project context cache:",e)}}async clearForProject(e){try{k(`[clearForProject] Starting for project: ${e.name} (ID: ${e.id})`);let n=this.getCacheKey(e),r=await this.get(e),o=0;if(r?.fileContexts){let s=Object.keys(r.fileContexts);if(s.length>0){k(`[clearForProject] Project ${e.name}: Found ${s.length} file contexts to remove from FileCache.`);for(let a in r.fileContexts){let l=r.fileContexts[a];l&&l.cacheKey?(await this.fileCache.remove(l.cacheKey),o++):ee(`[clearForProject] Project ${e.name}: Skipped removing FileCache entry for file ${a} due to missing cacheKey.`)}k(`[clearForProject] Project ${e.name}: Attempted to clear ${o} entries from FileCache.`)}}else k(`[clearForProject] Project ${e.name}: No fileContexts found in existing project cache to clear from FileCache.`);this.memoryCache.delete(n),k(`[clearForProject] Project ${e.name}: Removed from ProjectContextCache memory.`);let i=this.getCachePath(n);await this.vault.adapter.exists(i)?(await this.vault.adapter.remove(i),k(`[clearForProject] Project ${e.name}: Successfully removed main project cache file: ${i}`)):k(`[clearForProject] Project ${e.name}: Main project cache file not found (already deleted or never existed): ${i}`),this.projectMutexMap.delete(e.id),k(`[clearForProject] Cleaned up mutex for project: ${e.name}`),k(`[clearForProject] Completed for project: ${e.name}`)}catch(n){z(`[clearForProject] Error for project ${e.name} (ID: ${e.id}):`,n)}}async invalidateMarkdownContext(e,n=!1){await this.updateCacheSafely(e,r=>{r.markdownContext="",r.markdownNeedsReload=!0,n&&(r.webContexts={},r.youtubeContexts={},k(`Flagged Web/YouTube contexts for full reload for project ${e.name}`));let o=this.cleanupFileReferencesInCache(e,r);return k(`Invalidated markdown context for project ${e.name}`),o},!0)}async updateMarkdownContext(e,n){return await this.updateCacheSafely(e,r=>(r.markdownContext=n,r.markdownNeedsReload=!1,k(`Updated markdown context for project ${e.name}`),r))}async clearMarkdownContext(e){await this.updateCacheSafely(e,n=>(n.markdownContext="",n.markdownNeedsReload=!0,n))}async getOrReuseFileContext(e,n){try{let r=await this.getFileContext(e,n);if(r)return r;let o=await this.searchOtherProjectsForFile(n);return o?(await this.associateCacheWithProject(e,n,o.cacheKey),k(`Reused cached content from other project for: ${n} in project ${e.name}`),o.content):null}catch(r){return z(`Error in getOrReuseFileContext for ${n} in project ${e.name}:`,r),null}}async getFileContext(e,n){try{if(!n||typeof n!="string")return z("Error getting file context: filePath is invalid.",{project:e.name,filePath:n}),null;let r=await this.get(e);if(!r||!r.fileContexts||!r.fileContexts[n])return null;let o=r.fileContexts[n];if(!o||!o.cacheKey||typeof o.cacheKey!="string"||o.cacheKey.trim()==="")return ee(`Missing, invalid, or empty cacheKey for filePath: ${n} in project ${e.name}. Entry will be treated as a cache miss.`,{project:e.name,filePath:n,fileContextEntry:o}),null;let{cacheKey:i}=o;return typeof i!="string"?(ee(`cacheKey is not a string for filePath: ${n} in project ${e.name}. Treating as cache miss.`,{project:e.name,filePath:n,cacheKey:i}),null):await this.fileCache.get(i)}catch(r){return z(`Error getting file context for ${n} in project ${e.name}:`,r),null}}async setFileContext(e,n,r){return await this.updateCacheSafelyAsync(e,async o=>{o.fileContexts||(o.fileContexts={});let i=this.vault.getAbstractFileByPath(n);if(!(i instanceof hG.TFile))throw new Error(`File not found: ${n}`);let s=this.fileCache.getCacheKey(i,e.id);return await this.fileCache.set(s,r),o.fileContexts[n]={timestamp:Date.now(),cacheKey:s},k(`Added/updated file context for ${n} in project ${e.name}`),o})}async removeFileContext(e,n){return await this.updateCacheSafelyAsync(e,async r=>{if(r.fileContexts&&r.fileContexts[n]){let{cacheKey:o}=r.fileContexts[n];delete r.fileContexts[n],await this.fileCache.remove(o),k(`Removed file context for ${n} in project ${e.name}`)}return r})}async searchOtherProjectsForFile(e){try{let n=QN();if(n.length===0)return null;k(`Searching other projects for file: ${e}`);for(let r of n){let o=await this.get(r);if(!(!o||!o.fileContexts)&&o.fileContexts[e]){let{cacheKey:i}=o.fileContexts[e];if(!i)continue;let s=await this.fileCache.get(i);if(s)return k(`Found content for file ${e} in project ${r.name}`),{content:s,cacheKey:i}}}return k(`No content found in any project for file: ${e}`),null}catch(n){return z(`Error searching other projects for file ${e}:`,n),null}}async associateCacheWithProject(e,n,r){return await this.updateCacheSafelyAsync(e,async o=>(o.fileContexts||(o.fileContexts={}),o.fileContexts[n]={timestamp:Date.now(),cacheKey:r},k(`Associated cache with project ${e.name} for file: ${n}`),o))}cleanupFileReferencesInCache(e,n){if(!n.fileContexts)return n;let{inclusions:r,exclusions:o}=Bo({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0}),i=0,s={};for(let a in n.fileContexts){let l=this.vault.getAbstractFileByPath(a);!(l instanceof hG.TFile)||!Qr(l,r,o,!0)?i++:s[a]=n.fileContexts[a]}return i>0&&(n.fileContexts=s,k(`Removed ${i} file references from project ${e.name} that no longer match inclusion patterns`)),n}async cleanupProjectFileReferences(e){k(`[cleanupProjectFileReferences] Starting for project: ${e.name}`);try{await this.updateCacheSafely(e,n=>this.cleanupFileReferencesInCache(e,n),!0)}catch(n){z(`Error cleaning up project file references for ${e.name}:`,n)}}async updateProjectFilesFromPatterns(e,n){try{k(`[updateProjectFilesFromPatterns] Starting for project: ${e.name}`),n.fileContexts||(n.fileContexts={});let{inclusions:r,exclusions:o}=Bo({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0}),i=this.vault.getFiles(),s=0;for(let a of i)if(Qr(a,r,o,!0)){if(n.fileContexts[a.path])continue;let l=this.fileCache.getCacheKey(a,e.id);n.fileContexts[a.path]={timestamp:Date.now(),cacheKey:l},s++}s>0&&k(`[updateProjectFilesFromPatterns] Project ${e.name}: Added ${s} new file references to context (in memory).`),k(`[updateProjectFilesFromPatterns] Completed for project: ${e.name}. Total fileContexts in memory: ${Object.keys(n.fileContexts).length}`)}catch(r){z(`[updateProjectFilesFromPatterns] Error for project ${e.name}:`,r)}return n}updateProjectMarkdownFilesFromPatterns(e,n,r){try{n.fileContexts||(n.fileContexts={});let o=r.filter(s=>s.extension==="md"),i=0;for(let s of o){if(n.fileContexts[s.path])continue;let a=this.fileCache.getCacheKey(s,e.id);n.fileContexts[s.path]={timestamp:Date.now(),cacheKey:a},i++}i>0&&k(`[updateProjectFilesFromPatterns] Project ${e.name}: Added ${i} new file references to context (in memory).`),k(`[updateProjectFilesFromPatterns] Completed for project: ${e.name}. Total markdown fileContexts in memory: ${Object.keys(n.fileContexts).length}`)}catch(o){z(`[updateProjectFilesFromPatterns] Error for project ${e.name}:`,o)}return n}async removeWebUrls(e,n){n.length&&await this.updateCacheSafely(e,r=>{if(r.webContexts){for(let o of n)r.webContexts[o]&&delete r.webContexts[o];k(`Removed web contexts for URLs ${n.join(", ")} in project ${e.name}`)}return r})}async updateWebUrl(e,n,r){return await this.updateCacheSafely(e,o=>(o.webContexts||(o.webContexts={}),o.webContexts[n]=r,k(`Updated web context for URL ${n} in project ${e.name}`),o))}async removeYoutubeUrls(e,n){n.length&&await this.updateCacheSafely(e,r=>{if(r.youtubeContexts){for(let o of n)r.youtubeContexts[o]&&delete r.youtubeContexts[o];k(`removeYoutubeUrls: Removed YouTube contexts for URLs ${n.join(", ")} in project ${e.name}`)}return r})}async updateYoutubeUrl(e,n,r){return await this.updateCacheSafely(e,o=>(o.youtubeContexts||(o.youtubeContexts={}),o.youtubeContexts[n]=r,k(`Updated YouTube context for URL ${n} in project ${e.name}`),o))}async updateCacheSafely(e,n,r=!1){return await(await this.getOrCreateProjectMutex(e)).runExclusive(async()=>{try{let i=await this.get(e);if(!i){if(r)return;throw new Error(`Project: ${e.name} context cache not found, please invoke getOrInitializeCache method before invoke update context cache`)}let s=n(i);await this.setWithoutMutex(e,s)}catch(i){throw z(`Error updating cache for project ${e.name}:`,i),i}})}async updateCacheSafelyAsync(e,n,r=!1){return await(await this.getOrCreateProjectMutex(e)).runExclusive(async()=>{try{let i=await this.get(e);if(!i){if(r)return;throw new Error(`Project: ${e.name} context cache not found, please invoke getOrInitializeCache method before invoke update context cache`)}let s=await n(i);await this.setWithoutMutex(e,s)}catch(i){throw z(`Error updating cache for project ${e.name}:`,i),i}})}async setCacheSafely(e,n){return await(await this.getOrCreateProjectMutex(e)).runExclusive(async()=>(k(`External safe set for project: ${e.name}`),await this.setWithoutMutex(e,n)))}};kC.DEBOUNCE_DELAY=5e3;var ti=kC;Qi();It();ye();ye();qe();pG();var h0=require("obsidian"),ry=class{static async isImageUrl(e,n){try{let r,o=!1;try{let i=new URL(e),s=i.pathname,a=s.lastIndexOf("."),l=s.lastIndexOf("/");if(a>l&&a>-1&&(r=s.substring(a+1).toLowerCase()),r&&!this.IMAGE_EXTENSIONS.some(u=>u.toLowerCase()===`.${r}`))return z(`Unsupported image format from URL path: .${r}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;try{let u=(await fo(e,{method:"HEAD",headers:{}})).headers.get("content-type");return u?.startsWith("image/")?!0:(console.warn(`HEAD request succeeded for ${e} but Content-Type (${u}) is not image/*.`),!1)}catch(c){console.warn(`HEAD request failed for URL: ${e}. Proceeding to heuristic check.`,c);let u=i.searchParams,f=[u.has("w")||u.has("width"),u.has("h")||u.has("height"),u.has("format"),u.has("fit"),u.has("quality"),i.pathname.includes("/image/"),i.pathname.includes("/images/"),i.pathname.includes("/img/"),u.has("auto"),u.has("crop")].filter(Boolean).length;return f>=2?(z(`Identified as image based on URL heuristics (indicator count: ${f}): ${e}`),!0):!1}}catch{o=!0;let i=e.lastIndexOf(".");if(i>-1)r=e.substring(i+1).toLowerCase();else return!1}if(o)if(r&&this.IMAGE_EXTENSIONS.some(i=>i.toLowerCase()===`.${r}`)){let i=n.getAbstractFileByPath(e);return i instanceof h0.TFile?i.stat.size>this.MAX_IMAGE_SIZE?(z(`Vault file too large: ${i.stat.size} bytes for path: ${e}`),!1):!0:(z(`File with image extension not found in vault: ${e}.`),!1)}else return r&&z(`Unsupported image format for potential vault path: .${r}. Supported formats: ${this.IMAGE_EXTENSIONS.join(", ")}`,e),!1;return z(`Could not determine image status for URL/path: ${e}`),!1}catch(r){return z(`Unexpected error in isImageUrl for "${e}":`,r),!1}}static async handleVaultImage(e,n){try{if(e.stat.size>this.MAX_IMAGE_SIZE)return z(`Image too large: ${e.stat.size} bytes, skipping: ${e.path}`),null;let r=await n.readBinary(e),o=await this.getMimeType(r,e.extension);if(!o.startsWith("image/"))return z(`Invalid MIME type: ${o}, skipping: ${e.path}`),null;let i=EC(r);return`data:${o};base64,${i}`}catch(r){return z("Error processing vault image:",r),null}}static async handleWebImage(e){try{let n=await fo(e,{method:"GET",headers:{}});if(!n.ok)return z(`Failed to fetch image: ${n.statusText}, URL: ${e}`),null;let r=n.headers.get("content-type");if(!r?.startsWith("image/"))return z(`Invalid content type: ${r}, URL: ${e}`),null;let o=await n.arrayBuffer();if(o.byteLength>this.MAX_IMAGE_SIZE)return z(`Image too large: ${o.byteLength} bytes, URL: ${e}`),null;let i=EC(o);return`data:${r};base64,${i}`}catch(n){return z("Error converting web image to base64:",n),null}}static async handleLocalImage(e,n){try{let r=decodeURIComponent(e.replace("app://","")),o=n.getAbstractFileByPath(r);if(!o||!(o instanceof h0.TFile))return z(`Local image not found: ${r}`),null;if(o.stat.size>this.MAX_IMAGE_SIZE)return z(`Image too large: ${o.stat.size} bytes, path: ${r}`),null;let i=await n.readBinary(o),s=await this.getMimeType(i,o.extension);if(!s.startsWith("image/"))return z(`Invalid MIME type: ${s}, path: ${r}`),null;let a=EC(i);return`data:${s};base64,${a}`}catch(r){return z("Error processing local image:",r),null}}static async imageToBase64(e,n){if(e.startsWith("data:"))return e;if(e.startsWith("attachment:")){let o=e.substring(11),i=n.getAbstractFileByPath(o);return i instanceof h0.TFile?await this.handleVaultImage(i,n):(console.warn(`Could not find attachment file in vault: ${o}`),null)}if(e.startsWith("app://"))return await this.handleLocalImage(e,n);let r=n.getAbstractFileByPath(e);return r instanceof h0.TFile?await this.handleVaultImage(r,n):await this.handleWebImage(e)}static async convertToBase64(e,n){let r=await this.imageToBase64(e,n);return r?{type:"image_url",image_url:{url:r}}:(z(`Failed to convert image to base64: ${e}`),null)}static async getMimeType(e,n){let r=new Uint8Array(e.slice(0,4));if(r[0]===255&&r[1]===216)return"image/jpeg";if(r[0]===137&&r[1]===80)return"image/png";if(r[0]===71&&r[1]===73)return"image/gif";if(r[0]===82&&r[1]===73)return"image/webp";if(r[0]===66&&r[1]===77)return"image/bmp";if(r[0]===60&&r[1]===115)throw new Error("SVG files are not supported");let o=this.MIME_TYPES[n.toLowerCase()];if(!o){let i=`Unsupported image extension: ${n}`;throw z(i),new Error(i)}return o}};ry.IMAGE_EXTENSIONS=[".jpg",".jpeg",".png",".gif",".webp",".bmp"],ry.MAX_IMAGE_SIZE=3*1024*1024,ry.MIME_TYPES={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"};var g0=class t{static async processUrlBatch(e,n,r){try{let i=(await Promise.all(e.map(a=>t.processSingleUrl(a,n,r)))).filter(a=>a!==null),s=n.map(a=>`Image read failed for: ${a}`);return{successfulImages:i,failureDescriptions:s}}catch(o){return z("Error processing URL batch:",o),{successfulImages:[],failureDescriptions:e.map(i=>`Image read failed for: ${i}`)}}}static async processSingleUrl(e,n,r){try{if(!await ry.isImageUrl(e,r))return null;let o=await ry.convertToBase64(e,r);return o||(n.push(e),null)}catch(o){return z(`Failed to process image: ${e}`,o),n.push(e),null}}static async processChatImageBatch(e,n,r){try{let o=e.filter(l=>l.type==="image_url"&&!!l.image_url?.url),s=(await Promise.all(o.map(l=>t.processChatSingleImage(l,n,r)))).filter(l=>l!==null),a=n.map(l=>`Image read failed for: ${l}`);return{successfulImages:s,failureDescriptions:a}}catch(o){z("Error processing chat image batch:",o);let i=e.filter(s=>s.type==="image_url"&&!!s.image_url?.url).map(s=>s.image_url.url);return{successfulImages:[],failureDescriptions:i.map(s=>`Image read failed for: ${s}`)}}}static async processChatSingleImage(e,n,r){try{let o=await ry.convertToBase64(e.image_url.url,r);return o||(n.push(e.image_url.url),null)}catch(o){return z(`Failed to process chat image: ${e.image_url.url}`,o),n.push(e.image_url.url),null}}static showFailedImagesNotice(e){e.length>0&&new h0.Notice(`Failed to process images:
${e.join(`
`)}`)}};Zg();Su();ye();Se();qe();var q2t="https://api.firecrawl.dev/v2/search",G2t="https://api.perplexity.ai/chat/completions",U5e="https://api.supadata.ai/v1/transcript",Y2t=2e3,F5e=6e4;function B5e(){let t=q();switch(t.selfHostSearchProvider){case"perplexity":return!!t.perplexityApiKey;case"firecrawl":default:return!!t.firecrawlApiKey}}async function Z2t(t,e){let n=Date.now(),r=await Qy(q2t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({query:t,limit:5})});if(!r.ok){let u=await r.text();throw new Error(`Firecrawl search failed (${r.status}): ${u}`)}let i=(await r.json())?.data,s=Array.isArray(i)?i:Array.isArray(i?.web)?i.web:[],a=[],l=[];for(let u of s){let d=u.title||"Untitled",f=u.description||"",p=u.url||"";a.push(`### ${d}
${f}
Source: ${p}`),p&&l.push(p)}let c=Date.now()-n;return k(`[selfHostWebSearch] Firecrawl: ${s.length} results in ${c}ms`),{content:a.join(`

`),citations:l}}async function J2t(t,e){let n=await Qy(G2t,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({model:"sonar",messages:[{role:"user",content:t}]})});if(!n.ok){let s=await n.text();throw new Error(`Perplexity Sonar search failed (${n.status}): ${s}`)}let r=await n.json(),o=r?.choices?.[0]?.message?.content??"",i=Array.isArray(r?.citations)?r.citations:[];return{content:o,citations:i}}async function z5e(t){let e=q();switch(e.selfHostSearchProvider){case"perplexity":return J2t(t,await pn(e.perplexityApiKey));case"firecrawl":default:return Z2t(t,await pn(e.firecrawlApiKey))}}async function gG(t){let e=Date.now(),n=await pn(q().supadataApiKey),r=`${U5e}?url=${encodeURIComponent(t)}&mode=auto&text=true`,o=await Qy(r,{method:"GET",headers:{"x-api-key":n,Accept:"application/json"}});if(o.status===200){let s=await o.json(),a=Date.now()-e;return k(`[selfHostYoutube4llm] transcript received in ${a}ms`),{response:{transcript:s.content||""},elapsed_time_ms:a}}if(o.status===201||o.status===202){let a=(await o.json()).job_id;if(!a)throw new Error("Supadata returned async status but no job_id");return await X2t(a,n,e)}let i=await o.text();throw new Error(`Supadata transcript request failed (${o.status}): ${i}`)}async function X2t(t,e,n){let r=Date.now()+F5e,o=`${U5e}/${t}`;for(;Date.now()<r;){await new Promise(a=>window.setTimeout(a,Y2t));let i=await Qy(o,{method:"GET",headers:{"x-api-key":e,Accept:"application/json"}});if(i.status===200){let a=await i.json(),l=Date.now()-n;return k(`[selfHostYoutube4llm] async transcript completed in ${l}ms`),{response:{transcript:a.content||""},elapsed_time_ms:l}}if(i.status===202)continue;let s=await i.text();throw z(`[selfHostYoutube4llm] poll failed (${i.status}): ${s}`),new Error(`Supadata poll failed (${i.status}): ${s}`)}throw new Error(`Supadata transcript timed out after ${F5e}ms`)}qe();ye();ns();Se();var tO=class t{constructor(){this.mentions=new Map,this.brevilabsClient=di.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}extractAllUrls(e){let n=/https?:\/\/[^\s"'<>]+/g;return(e.match(n)||[]).map(r=>r.replace(/,+$/,"")).filter((r,o,i)=>i.indexOf(r)===o)}extractUrls(e){let n=/https?:\/\/[^\s"'<>]+/g;return(e.match(n)||[]).map(r=>r.replace(/,+$/,"")).filter((r,o,i)=>i.indexOf(r)===o)}async processUrl(e){try{return await this.brevilabsClient.url4llm(e)}catch(n){let r=Xt(n);return z(`Error processing URL ${e}: ${r}`),{response:e,elapsed_time_ms:0,error:r}}}async processYoutubeUrl(e){try{return{transcript:(pc()&&q().supadataApiKey?await gG(e):await this.brevilabsClient.youtube4llm(e)).response.transcript}}catch(n){let r=Xt(n);return z(`Error processing YouTube URL ${e}: ${r}`),{transcript:"",error:r}}}async processTwitterUrl(e){try{return await this.brevilabsClient.twitter4llm(e)}catch(n){let r=Xt(n);return z(`Error processing Twitter URL ${e}: ${r}`),{response:e,elapsed_time_ms:0,error:r}}}async processUrlList(e){let n="",r=[],o={};if(e.length===0)return{urlContext:n,imageUrls:r,processedErrorUrls:o};let i=e.map(async a=>{if(await ry.isImageUrl(a,app.vault))return r.push(a),{type:"image",url:a};if(DAe(a)){let c=this.mentions.get(a);if(!c||c.error){let u=await this.processYoutubeUrl(a);this.mentions.set(a,{type:"youtube",original:a,processed:u.transcript,error:u.error})}return{type:"youtube",data:this.mentions.get(a)}}if($Ae(a)){let c=this.mentions.get(a);if(!c||c.error){let u=await this.processTwitterUrl(a);this.mentions.set(a,{type:"twitter",original:a,processed:u.response,error:u.error})}return{type:"twitter",data:this.mentions.get(a)}}let l=this.mentions.get(a);if(!l||l.error){let c=await this.processUrl(a);this.mentions.set(a,{type:"url",original:a,processed:c.response,error:c.error})}return{type:"url",data:this.mentions.get(a)}});return(await Promise.all(i)).forEach(a=>{if(a.type==="image")return;let l=a.data;l&&(l.processed&&(a.type==="youtube"?n+=`

<youtube_video_context>
<url>${l.original}</url>
<content>
${l.processed}
</content>
</youtube_video_context>`:a.type==="twitter"?n+=`

<twitter_content>
<url>${l.original}</url>
<content>
${l.processed}
</content>
</twitter_content>`:n+=`

<url_content>
<url>${l.original}</url>
<content>
${l.processed}
</content>
</url_content>`),l.error&&(o[l.original]=l.error))}),{urlContext:n,imageUrls:r,processedErrorUrls:o}}async processUrls(e){let n=this.extractUrls(e);return this.processUrlList(n)}getMentions(){return this.mentions}clearMentions(){this.mentions.clear()}};fc();ye();var j5e={id:"",name:"",description:"",systemPrompt:"",projectModelKey:"",modelConfigs:{},contextSource:{},created:0,UsageTimestamps:0},Tp="copilot-project-id",y0="copilot-project-name",w0="copilot-project-description",v0="copilot-project-model-key",MC="copilot-project-temperature",NC="copilot-project-max-tokens",x0="copilot-project-created",nh="copilot-project-last-used",b0="copilot-project-inclusions",C0="copilot-project-exclusions",_0="copilot-project-web-urls",S0="copilot-project-youtube-urls",sv="project.md",nf="unsupported";Se();var OC=require("obsidian");function ja(){return(0,OC.normalizePath)(q().projectsFolder)}function yG(){return(0,OC.normalizePath)(`${ja()}/${nf}`)}function rf(t){return(0,OC.normalizePath)(`${ja()}/${t}`)}function RC(t,e){let n=e?(0,OC.normalizePath)(e):ja();return(0,OC.normalizePath)(`${n}/${t}/${sv}`)}function T0(t){if(!(t instanceof OC.TFile)||t.extension!=="md")return!1;let e=ja();if(!t.path.startsWith(e+"/"))return!1;let n=t.path.slice(e.length+1);if(n.startsWith(`${nf}/`))return!1;let r=n.split("/");return!(r.length!==2||r[1]!==sv)}function V5e(t){let e=ja();if(!t.startsWith(e+"/"))return null;let r=t.slice(e.length+1).split("/");return r.length!==2||r[1]!==sv?null:r[0]||null}function Xc(t){let n=(t||"").trim().replace(/[<>:"/\\|?*]/g,"_").replace(/[\x00-\x1F]/g,"_");return n=n.replace(/[. ]+$/g,""),(n==="."||n==="..")&&(n=n.replace(/\./g,"_")),/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(n)&&(n=`_${n}`),n||(n="_"),n}function W5e(t,e){let n=(e||"").trim()||t,r=Xc(n);return r.toLowerCase()===nf&&(r=`_${r}`),r}function rh(t){return(t||"").split(`
`).map(e=>e.trim()).filter(Boolean)}async function fye(t,e,n){try{let o=(await t.cachedRead(e)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!o)return"";let i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=o[1].match(new RegExp(`^${i}:\\s*(.+)$`,"m"));if(!s)return"";let a=s[1].trim();if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))a=a.slice(1,-1);else{let l=a.indexOf(" #");l>0&&(a=a.slice(0,l).trim())}return a}catch{return""}}qe();ye();var lv=require("obsidian");async function fB(t,e,n,r){let o=rh(e.contextSource?.webUrls||""),i=rh(e.contextSource?.youtubeUrls||"");await app.fileManager.processFrontMatter(t,s=>{s[Tp]=e.id.trim(),s[y0]=(e.name||n).trim(),s[w0]=(e.description||"").trim(),s[v0]=(e.projectModelKey||"").trim(),e.modelConfigs?.temperature!=null?s[MC]=e.modelConfigs.temperature:delete s[MC],e.modelConfigs?.maxTokens!=null?s[NC]=e.modelConfigs.maxTokens:delete s[NC],s[b0]=e.contextSource?.inclusions||"",s[C0]=e.contextSource?.exclusions||"",s[_0]=o,s[S0]=i,s[x0]=r.createdMs,s[nh]=r.lastUsedMs})}function wG(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let n=Number(t);if(Number.isFinite(n))return n}return e}function rO(t,e){return typeof t=="string"?t:e}function q5e(t){return Array.isArray(t)?t.filter(e=>typeof e=="string").map(e=>e.trim()).filter(Boolean):typeof t=="string"?t.split(`
`).map(e=>e.trim()).filter(Boolean):[]}function G5e(t){return t.replace(/\n\s*/g,"").replace(/\r/g,"")}function Y5e(t){return(t||[]).map(e=>e.trim()).filter(Boolean).join(`
`)}async function E0(t){let e=app.vault.getAbstractFileByPath(t.path),n=e instanceof lv.TFile,r=n?await app.vault.read(e):await app.vault.adapter.read(t.path),o=Qh(r,{trimStart:!1}),i,s=r.replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(s)try{let A=(0,lv.parseYaml)(s[1]);A&&typeof A=="object"&&(i=A)}catch{return ee(`[Projects] Failed to parse YAML frontmatter from file: ${t.path}`),null}!i&&n&&(i=app.metadataCache.getFileCache(e)?.frontmatter);let a=V5e(t.path);if(!a)return ee(`[Projects] Cannot extract folder name from path, ignoring file: ${t.path}`),null;let l=i?.[Tp],c=typeof l=="number"&&Number.isFinite(l)?String(l):rO(l,"");if(!c.trim())return ee(`[Projects] Missing ${Tp} in frontmatter, skipping file: ${t.path}`),null;let u=c.trim(),f=rO(i?.[y0],"").trim()||a,p=rO(i?.[w0],"").trim(),m=rO(i?.[v0],"").trim(),h=wG(i?.[MC],NaN),g=wG(i?.[NC],NaN),y=rO(i?.[b0],""),w=rO(i?.[C0],""),v=G5e(y),x=G5e(w),b=q5e(i?.[_0]),_=q5e(i?.[S0]),T=wG(i?.[x0],t.stat?.ctime??0),S=wG(i?.[nh],0),P={};return Number.isFinite(h)&&(P.temperature=h),Number.isFinite(g)&&g>0&&(P.maxTokens=g),{project:{...j5e,id:u,name:f,description:p||"",systemPrompt:o,projectModelKey:m,modelConfigs:P,contextSource:{inclusions:v||"",exclusions:x||"",webUrls:Y5e(b),youtubeUrls:Y5e(_)},created:Number.isFinite(T)&&T>0?T:0,UsageTimestamps:Number.isFinite(S)&&S>0?S:0},filePath:t.path,folderName:a}}async function vG(){let t=ja(),e=app.vault.getAbstractFileByPath(t),n=[];if(e instanceof lv.TFolder)for(let s of e.children){if(!(s instanceof lv.TFolder)||s.name===nf)continue;let a=s.children.find(l=>l instanceof lv.TFile&&l.name===sv);a instanceof lv.TFile&&n.push(a)}else if(await app.vault.adapter.exists(t)){let{resolveFileByPath:s}=await Promise.resolve().then(()=>(av(),K5e)),a=await app.vault.adapter.list(t);for(let l of a.folders){if((l.split("/").pop()??"")===nf)continue;let u=`${l}/${sv}`;if(await app.vault.adapter.exists(u)){let d=await s(app,u);d&&n.push(d)}}}n.sort((s,a)=>s.path.localeCompare(a.path));let r={},o=[],i=[];for(let s of n){let a;try{a=await E0(s)}catch(c){z(`[Projects] Failed to parse project file, skipping: ${s.path}`,c),o.push(s.path);continue}if(!a){o.push(s.path);continue}let l=a.project.id;if(r[l]||(r[l]=[]),r[l].push(s.path),r[l].length>1){ee(`[Projects] Duplicate project id="${l}": ${r[l].join(", ")}; keeping first: ${r[l][0]}`);continue}i.push(a)}return{records:i,diagnostics:{duplicateIdIndex:r,ignoredFiles:o}}}async function cv(){let{records:t}=await vG();return uB(t),t}async function Z5e(){let{records:t}=await vG();return t}async function pB(t,e){let n=th(t.path),r=Date.now(),o=Number.isFinite(e.project.created)&&e.project.created>0?e.project.created:r,i=Number.isFinite(e.project.UsageTimestamps)&&e.project.UsageTimestamps>0?e.project.UsageTimestamps:0,s=rh(e.project.contextSource?.webUrls||""),a=rh(e.project.contextSource?.youtubeUrls||"");try{n||tf(t.path),await app.fileManager.processFrontMatter(t,l=>{l[Tp]==null&&e.project.id&&(l[Tp]=e.project.id),l[y0]==null&&(l[y0]=e.project.name||e.folderName),l[w0]==null&&e.project.description&&(l[w0]=e.project.description),l[v0]==null&&e.project.projectModelKey&&(l[v0]=e.project.projectModelKey),l[MC]==null&&e.project.modelConfigs?.temperature!=null&&(l[MC]=e.project.modelConfigs.temperature),l[NC]==null&&e.project.modelConfigs?.maxTokens!=null&&(l[NC]=e.project.modelConfigs.maxTokens),l[b0]==null&&e.project.contextSource?.inclusions&&(l[b0]=e.project.contextSource.inclusions),l[C0]==null&&e.project.contextSource?.exclusions&&(l[C0]=e.project.contextSource.exclusions),l[_0]==null&&s.length>0&&(l[_0]=s),l[S0]==null&&a.length>0&&(l[S0]=a),l[x0]==null&&(l[x0]=o),l[nh]==null&&(l[nh]=i)})}finally{n||Ju(t.path)}}qe();Ky();av();var Ip=require("obsidian");rn();ye();ws();var J5e=require("obsidian"),A0=N(U());function Q2t({content:t,onConfirm:e,onCancel:n,confirmButtonText:r,cancelButtonText:o}){return A0.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-5"},A0.default.createElement("div",{className:"tw-whitespace-pre-wrap"},t),A0.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},o&&A0.default.createElement(X,{variant:"secondary",onClick:n},o),r&&A0.default.createElement(X,{variant:"default",onClick:e},r)))}var Cr=class extends J5e.Modal{constructor(n,r,o,i,s="Continue",a="Cancel",l){super(n);this.onConfirm=r;this.content=o;this.confirmButtonText=s;this.cancelButtonText=a;this.onCancel=l;this.confirmed=!1;this.setTitle(i)}onOpen(){let{contentEl:n}=this;this.root=sr(n,this.app);let r=()=>{this.confirmed=!0;let i=this.onConfirm();i instanceof Promise&&i.catch(s=>z("ConfirmModal onConfirm failed",s)),this.close()},o=()=>{this.close()};this.root.render(A0.default.createElement(Q2t,{content:this.content,onConfirm:r,onCancel:o,confirmButtonText:this.confirmButtonText,cancelButtonText:this.cancelButtonText}))}onClose(){if(!this.confirmed){let n=this.onCancel?.();n instanceof Promise&&n.catch(r=>z("ConfirmModal onCancel failed",r))}this.root.unmount()}};ye();Se();qe();var eu=require("obsidian");av();function X5e(t){return t.replace(/\r\n/g,`
`).replace(/\r/g,`
`)}async function k0(t,e,n){try{let r=yG();await Fr(r);let o=Xc(e.id||"unknown")||"unknown",i=`Project Migration Failed - ${o}`,s=`${r}/${i}.md`,a=2;for(;await t.adapter.exists(s);){if(a===2)try{let u=(await t.adapter.read(s)).match(/```json\s*\n([\s\S]*?)\n```/);if(u){let d=JSON.parse(u[1]);if(JSON.stringify(d)===JSON.stringify(e))return!1}}catch{}if(s=`${r}/${i} - ${a}.md`,a++,a>20)return ee(`[Projects] Too many backup collisions for safeId="${o}", giving up`),!1}let l=[`> Projects migration failed: ${n}`,">","> This file is an automatic backup (unsupported/), for manual recovery.","> You can recreate the project from the JSON below, or fix and re-migrate.","","```json",JSON.stringify(e,null,2),"```",""].join(`
`);return await t.create(s,l),!0}catch(r){return z(`[Projects] Failed to save unsupported backup for project id=${e.id||"unknown"}`,r),!1}}async function tqe(t,e,n){let r=t.vault;try{let o=r.getAbstractFileByPath(e);o instanceof eu.TFile?await Qc(t,o):await r.adapter.exists(e)&&await r.adapter.remove(e);let i=r.getAbstractFileByPath(n);if(i instanceof eu.TFolder&&i.children.length===0)await Qc(t,i);else if(await r.adapter.exists(n)){let s=await r.adapter.list(n);s.files.length===0&&s.folders.length===0&&await r.adapter.rmdir(n,!1)}}catch(o){z(`[Projects] Migration rollback failed for ${e}`,o)}}async function eUt(t,e,n){let r=t.vault,o=ja();await Fr(o),await Fr(`${o}/${n}`);let i=RC(n),s=`${o}/${n}`;tf(i);try{let a=await r.create(i,e.systemPrompt||""),l=Date.now(),c=Number.isFinite(e.created)&&e.created>0?e.created:l,u=Number.isFinite(e.UsageTimestamps)&&e.UsageTimestamps>0?e.UsageTimestamps:0;try{await fB(a,e,n,{createdMs:c,lastUsedMs:u})}catch(d){throw await tqe(t,i,s),d}return a}finally{Ju(i)}}async function Q5e(t,e,n){try{let r=e instanceof eu.TFile?await t.read(e):await t.adapter.read(e),o=Qh(r,{trimStart:!1}),i=X5e(o).replace(/^\n+/,""),s=X5e(n||"").replace(/^\n+/,"");return i!==s?(ee(`[Projects] Migration verify failed: content mismatch. Expected ${s.length} chars, got ${i.length} chars`),!1):!0}catch(r){return z("[Projects] Migration verify failed: unable to read back file",r),!1}}function eqe(t,e){return W5e(t,e)}async function tUt(t){let e=t.vault,r=q().projectList||[];if(r.length===0){k("[Projects] No legacy projects to migrate");return}k(`[Projects] Migrating ${r.length} legacy projects to vault files...`);let o=[],i=new Set,s=new Map;for(let f of r){let p=(f.id||"").trim();if(!p){ee("[Projects] Skip migrating project with empty id"),await k0(e,f,"empty project id");continue}if(i.has(p)){ee(`[Projects] Skip migrating duplicate project id: ${p}`),await k0(e,f,`duplicate project id: ${p}`);continue}i.add(p);let m=eqe(p,f.name),h=m.toLowerCase(),g=s.get(h);if(g){ee(`[Projects] Skip migrating project id="${p}": folder name "${m}" collides with id="${g}"`),await k0(e,f,`folder name collision: "${m}" already used by id="${g}"`);continue}s.set(h,p);let y=RC(m),w=e.getAbstractFileByPath(y);if(w instanceof eu.TFile||await e.adapter.exists(y)){let x="";if(w instanceof eu.TFile){let b=t.metadataCache.getFileCache(w);x=String(b?.frontmatter?.[Tp]??"").trim(),x||(x=await fye(e,w,Tp))}else try{let _=(await e.adapter.read(y)).replace(/^\uFEFF/,"").match(/^---\r?\n([\s\S]*?)\r?\n---/);if(_){let T=(0,eu.parseYaml)(_[1]);if(T&&typeof T=="object"){let S=T[Tp];x=(typeof S=="string"?S:"").trim()}}}catch{x=""}if(x===p){if(await Q5e(e,w instanceof eu.TFile?w:y,f.systemPrompt||"")){if(w instanceof eu.TFile)try{let _=eqe(p,f.name);await pB(w,{project:f,filePath:y,folderName:_})}catch(_){ee(`[Projects] Failed to repair frontmatter for id=${p}, continuing`,_)}k(`[Projects] Migration skip: target file already exists for id=${p} at ${y}`),o.push(f);continue}ee(`[Projects] Migration verify failed on existing file for id=${p} at ${y}`),await k0(e,f,`existing file content mismatch at ${y} (delete/rename the file and re-run migration)`);continue}ee(`[Projects] Migration conflict: ${y} exists with id="${x}" but expected "${p}"`),await k0(e,f,`target file exists at ${y} with mismatched id="${x}"`);continue}try{let x=await eUt(t,f,m);if(await Q5e(e,x,f.systemPrompt||""))o.push(f);else{let _=`${ja()}/${m}`;await tqe(t,x.path,_),await k0(e,f,"content verification mismatch")}}catch(x){let b=x instanceof Error?x.message:String(x);z(`[Projects] Failed to migrate project id=${p}`,x),await k0(e,f,b)}}pe("projectList",[]);let a=o.length,l=r.length-a,c=ja(),u=yG(),d=f=>{let p=e.getAbstractFileByPath(f);if(p instanceof eu.TFolder){let m=t.internalPlugins?.getPluginById?.("file-explorer");m?.enabled&&m.instance?.revealInFolder&&m.instance.revealInFolder(p)}else new eu.Notice(`Folder "${f}" is hidden and cannot be revealed in Obsidian's explorer.`)};l===0?(k(`[Projects] Migration succeeded: all ${a} project(s) migrated to vault files`),new Cr(t,()=>d(c),`Your projects have been upgraded to the new file-based format. They are now stored in: ${c}

You can now:
\u2022 Edit project settings directly in the file
\u2022 View and manage project files in the vault
\u2022 All ${a} project(s) were migrated successfully.`,"\u{1F680} Projects Upgraded","Show in Folder","OK").open()):a>0?(ee(`[Projects] Migration partially succeeded: ${a} migrated, ${l} failed`),new Cr(t,()=>d(c),`\u26A0\uFE0F Projects migration partially completed.

\u2705 ${a} project(s) migrated successfully.
\u274C ${l} project(s) failed \u2014 their data has been backed up to:
${u}

You can manually recover failed projects from the unsupported folder.`,"\u26A0\uFE0F Projects Migration: Partial Success","Show in Folder","OK").open()):(ee("[Projects] Migration failed: no projects were migrated"),new Cr(t,()=>d(u),`\u26A0\uFE0F Projects migration could not be completed.

Your project data has been backed up to:
${u}

To recover:
1. Open the files in the unsupported folder
2. Review the content
3. Recreate the projects manually`,"\u26A0\uFE0F Projects Migration Failed","Show in Folder","OK").open())}async function nUt(t){let{records:e}=await vG();if(e.length===0)return;let n=0,r=ja(),o=new Map;for(let i of e)o.set(i.folderName.toLowerCase(),i.project.id);for(let i of e){let s=(i.project.name||"").trim();if(!s)continue;let a=Xc(s),l=a.toLowerCase()===nf?`_${a}`:a;if(l===i.folderName)continue;let c=`${r}/${l}`,u=rf(i.folderName),d=i.filePath,f=RC(l),p=l.toLowerCase(),m=o.get(p);if(m&&m!==i.project.id){ee(`[Projects] Naming migration skip: folder "${l}" collides (case-insensitive) with project id="${m}" for project id="${i.project.id}"`);continue}if(!(c.toLowerCase()===u.toLowerCase())&&await t.adapter.exists(c)){ee(`[Projects] Naming migration skip: target folder "${c}" already exists for project id="${i.project.id}"`);continue}try{tf(d),tf(f);let g=t.getAbstractFileByPath(u);g instanceof eu.TFolder?await t.rename(g,c):await t.adapter.rename(u,c),n++,o.delete(i.folderName.toLowerCase()),o.set(p,i.project.id),k(`[Projects] Naming migration: renamed folder "${i.folderName}" \u2192 "${l}" for project "${s}" (id=${i.project.id})`)}catch(g){z(`[Projects] Naming migration failed for project id="${i.project.id}"`,g)}finally{Ju(d),Ju(f)}}n>0&&k(`[Projects] Naming migration complete: ${n} folder(s) renamed`)}async function nqe(t){(q().projectList||[]).length>0&&await tUt(t),await nUt(t.vault)}var Xu=class t{constructor(e){this.projectLastUsedManager=new sA;this.app=e,this.vault=e.vault}static getInstance(e){if(!t.instance){if(!e)throw new Error("App is required for first initialization");t.instance=new t(e)}return t.instance}async initialize(){k("[Projects] Initializing ProjectFileManager"),await nqe(this.app),await cv()}getProjects(){return Sp().map(e=>e.project)}getProjectRecords(){return Sp()}async reloadProjects(){return await cv()}async fetchProjects(){return await Z5e()}getProjectUsageTimestampsManager(){return this.projectLastUsedManager}sanitizeFolderName(e){let n=Xc(e);return n.toLowerCase()===nf?`_${n}`:n}async rollbackCreatedFile(e,n){try{let r=this.vault.getAbstractFileByPath(e);r instanceof Ip.TFile?await Qc(this.app,r):await this.vault.adapter.exists(e)&&await this.vault.adapter.remove(e);let o=this.vault.getAbstractFileByPath(n);if(o instanceof Ip.TFolder&&o.children.length===0)await Qc(this.app,o);else if(await this.vault.adapter.exists(n)){let i=await this.vault.adapter.list(n);i.files.length===0&&i.folders.length===0&&await this.vault.adapter.rmdir(n,!1)}}catch(r){z(`[Projects] Rollback failed for ${e}`,r)}}getLeadingFrontmatterBlock(e){let r=e.replace(/^\uFEFF/,"").match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return r?r[0]:null}buildProjectFileContent(e,n,r){let o=rh(e.contextSource?.webUrls||""),i=rh(e.contextSource?.youtubeUrls||""),s={[Tp]:e.id.trim(),[y0]:(e.name||n).trim(),[w0]:(e.description||"").trim(),[v0]:(e.projectModelKey||"").trim(),[b0]:e.contextSource?.inclusions||"",[C0]:e.contextSource?.exclusions||"",[_0]:o,[S0]:i,[x0]:r.createdMs,[nh]:r.lastUsedMs};return e.modelConfigs?.temperature!=null&&(s[MC]=e.modelConfigs.temperature),e.modelConfigs?.maxTokens!=null&&(s[NC]=e.modelConfigs.maxTokens),`---
${(0,Ip.stringifyYaml)(s)}---
${e.systemPrompt||""}`}async createProject(e){let n=(e.id||"").trim();if(!n)throw new Error("Project id cannot be empty");if(ef(n))throw new Error(`Project id already exists: ${n}`);let r=(e.name||"").trim();if(r&&Sp().some(d=>d.project.name.trim().toLowerCase()===r.toLowerCase()))throw new Error(`A project with the name "${r}" already exists`);let o=this.sanitizeFolderName(r||n),i=rf(o),s=RC(o),a=o.toLowerCase(),c=Sp().find(u=>u.folderName.toLowerCase()===a&&u.project.id!==n);if(c)throw new Error(`Folder name collision: project id "${n}" sanitizes to folder "${o}" which conflicts with existing project "${c.project.id}"`);try{if(tf(s),await Fr(ja()),await Fr(i),await this.vault.adapter.exists(s))throw new Error(`Project file already exists at "${s}". This may be a folder name collision \u2014 project id "${n}" sanitizes to folder "${o}"`);let u=Date.now(),d=Number.isFinite(e.created)&&e.created>0?e.created:u,f=Number.isFinite(e.UsageTimestamps)&&e.UsageTimestamps>0?e.UsageTimestamps:0,p=await this.vault.create(s,e.systemPrompt||"");try{await fB(p,e,o,{createdMs:d,lastUsedMs:f})}catch(h){throw await this.rollbackCreatedFile(s,i),h}let m={project:{...e,id:n,created:d,UsageTimestamps:f},filePath:s,folderName:o};return m0(m),k(`[Projects] Created project: ${n} -> ${s}`),m}finally{Ju(s)}}async updateProject(e,n){let r=(e||"").trim();if(!r)throw new Error("Project id cannot be empty");if((n.id||"").trim()!==r)throw new Error("Project id mismatch: cannot change id via update");let o=ef(r);if(!o)throw new Error(`Project not found: ${r}`);let i=(n.name||"").trim();if(i&&Sp().some(d=>d.project.id!==r&&d.project.name.trim().toLowerCase()===i.toLowerCase()))throw new Error(`A project with the name "${i}" already exists`);let s=o.filePath,a=o.folderName,l=this.sanitizeFolderName(i||r),c=null;if(l!==o.folderName){let u=rf(l),d=RC(l),f=l.toLowerCase(),p=Sp().find(h=>h.project.id!==r&&h.folderName.toLowerCase()===f);if(p)throw new Error(`Cannot rename project folder: "${l}" conflicts with project "${p.project.name}"`);if(!(u.toLowerCase()===rf(o.folderName).toLowerCase())&&await this.vault.adapter.exists(u))throw new Error(`Cannot rename project folder: "${u}" already exists on disk`);c=s,tf(c),tf(d);try{let h=rf(o.folderName),g=this.vault.getAbstractFileByPath(h);g instanceof Ip.TFolder?await this.vault.rename(g,u):await this.vault.adapter.rename(h,u)}catch(h){throw Ju(c),Ju(d),h}s=d,a=l,k(`[Projects] Renamed project folder: "${o.folderName}" \u2192 "${l}" for project ${r}`)}try{c||tf(s);let u=await I0(app,s),d=!1;if(!u){k(`[Projects] Materializing missing vault file for project: ${r}`);let w=rf(a);await Fr(ja()),await Fr(w),u=await this.vault.create(s,n.systemPrompt||""),d=!0}let f=Number.isFinite(o.project.created)&&o.project.created>0?o.project.created:Date.now(),p=Number.isFinite(o.project.UsageTimestamps)&&o.project.UsageTimestamps>0?o.project.UsageTimestamps:0,m=this.projectLastUsedManager.getLastTouchedAt(r)??0,h=Math.max(p,m),g={...n,created:f,UsageTimestamps:h};if(P0(app,s)){try{await fB(u,g,a,{createdMs:f,lastUsedMs:h})}catch(b){throw d&&await this.rollbackCreatedFile(s,rf(a)),b}let w=await this.vault.read(u),v=this.getLeadingFrontmatterBlock(w);if(!v)throw new Error(`Expected frontmatter block after update: ${u.path}`);let x=v.endsWith(`
`)?"":`
`;await this.vault.modify(u,v+x+(n.systemPrompt||""))}else{let w=this.buildProjectFileContent(g,a,{createdMs:f,lastUsedMs:h});await this.vault.adapter.write(s,w)}let y={project:{...n,created:f,UsageTimestamps:h},filePath:s,folderName:a};return m0(y),k(`[Projects] Updated project: ${r} -> ${s}`),y}catch(u){if(c&&a!==o.folderName)try{let d=rf(o.folderName),f=rf(a),p=this.vault.getAbstractFileByPath(f);p instanceof Ip.TFolder?await this.vault.rename(p,d):await this.vault.adapter.rename(f,d),ee(`[Projects] Rolled back folder rename "${a}" \u2192 "${o.folderName}" after write failure`)}catch(d){z(`[Projects] Failed to rollback folder rename for ${r}`,d)}throw u}finally{Ju(s),c&&Ju(c)}}async deleteProject(e){let n=(e||"").trim(),r=ef(n);if(!r){ee(`[Projects] deleteProject: not found: ${n}`);return}let o=rf(r.folderName);try{tf(r.filePath);let i=this.vault.getAbstractFileByPath(r.filePath);i instanceof Ip.TFile?await Qc(this.app,i):await this.vault.adapter.exists(r.filePath)&&await this.vault.adapter.remove(r.filePath),D5e(n);try{let s=this.vault.getAbstractFileByPath(o);if(s instanceof Ip.TFolder&&s.children.length===0)await Qc(this.app,s);else if(await this.vault.adapter.exists(o)){let a=await this.vault.adapter.list(o);a.files.length===0&&a.folders.length===0&&await this.vault.adapter.rmdir(o,!1)}}catch(s){ee(`[Projects] Failed to clean up empty project folder: ${o}`,s)}await ti.getInstance().clearForProject(r.project).catch(s=>z("[Projects] Failed to clear context cache on delete",s)),k(`[Projects] Deleted project: ${n} -> ${o}`),cv().catch(s=>z("[Projects] Rescan after delete failed",s))}finally{Ju(r.filePath)}}async touchProjectLastUsed(e){let n=(e||"").trim(),r=ef(n);if(r)try{this.projectLastUsedManager.touch(n);let o=this.projectLastUsedManager.shouldPersist(n,r.project.UsageTimestamps);if(o===null)return;let i=(0,Ip.normalizePath)(r.filePath),s=await I0(app,i);if(!s)return;let a=th(i),l=o;try{if(a||tf(i),P0(app,i))await app.fileManager.processFrontMatter(s,u=>{let d=Number(u[nh]),f=Number.isFinite(d)&&d>0?d:0;l=Math.max(f,o),f!==l&&(u[nh]=l)});else{let u=await oy(app,i),d=Number(u?.[nh]),f=Number.isFinite(d)&&d>0?d:0;l=Math.max(f,o),f!==l&&await LC(app,i,{[nh]:l})}}finally{a||Ju(i)}this.projectLastUsedManager.markPersisted(n,l);let c=ef(n);c&&m0({...c,project:{...c.project,UsageTimestamps:l}})}catch(o){z(`[Projects] Failed to touch last-used for projectId=${e}`,o)}}};Se();ye();TC();var xG=class t{constructor(){this.cacheDir=".copilot/pdf-cache"}static getInstance(){return t.instance||(t.instance=new t),t.instance}async ensureCacheDir(){await app.vault.adapter.exists(this.cacheDir)||(k("Creating PDF cache directory:",this.cacheDir),await app.vault.adapter.mkdir(this.cacheDir))}getCacheKey(e){let n=`${e.path}:${e.stat.size}:${e.stat.mtime}`,r=Jc(n);return k("Generated cache key for PDF:",{path:e.path,key:r}),r}getCachePath(e){return`${this.cacheDir}/${e}.json`}async get(e){try{let n=this.getCacheKey(e),r=this.getCachePath(n);if(await app.vault.adapter.exists(r)){k("Cache hit for PDF:",e.path);let o=await app.vault.adapter.read(r);return JSON.parse(o)}return k("Cache miss for PDF:",e.path),null}catch(n){return z("Error reading from PDF cache:",n),null}}async set(e,n){try{await this.ensureCacheDir();let r=this.getCacheKey(e),o=this.getCachePath(r);k("Caching PDF response for:",e.path),await app.vault.adapter.write(o,JSON.stringify(n))}catch(r){z("Error writing to PDF cache:",r)}}async clear(){try{if(await app.vault.adapter.exists(this.cacheDir)){let e=await app.vault.adapter.list(this.cacheDir);k("Clearing PDF cache, removing files:",e.files.length);for(let n of e.files)await app.vault.adapter.remove(n)}}catch(e){z("Error clearing PDF cache:",e)}}};ye();RN();yp();ns();Se();ye();qe();async function rqe(t,e,n,r){let o=r?.trim();if(o&&t.extension!=="md"&&!(!e||e.startsWith("[Error:")))try{await Fr(o);let i=`${o}/${t.basename}.md`;if(await n.adapter.exists(i)){let a=await n.adapter.read(i);if(a&&!a.startsWith(`<!-- source: ${t.path} -->`)){let l=t.path.replace(/\.[^.]+$/,"").replace(/[/\\]/g,"__");if(i=`${o}/${l}.md`,await n.adapter.exists(i)){let c=await n.adapter.read(i);if(c&&!c.startsWith(`<!-- source: ${t.path} -->`)){ee(`Skipping converted doc output for ${t.path}: collision at ${i}`);return}}}}let s=`<!-- source: ${t.path} -->
${e}`;if(await n.adapter.exists(i)&&await n.adapter.read(i)===s)return;await n.adapter.write(i,s),k(`Saved converted doc output: ${i}`)}catch(i){z(`Failed to save converted doc output for ${t.path}:`,i)}}function uv(t){if(!t||typeof t!="object")return!1;let e=t,n=e.message||"";return n.includes("Request rate limit exceeded")||n.includes("RATE_LIMIT_EXCEEDED")||n.includes("429")||e.status===429}function oqe(t){let r=(t?.message||"").match(/Try again in ([\d\w\s]+)/);return r?r[1]:"some time"}var aqe=require("obsidian");var iqe=require("obsidian");var CG,sqe,bG=class{constructor(e){this.vault=e;GQ(this,CG)}async load(e){let n=await this.vault.read(e),{nodes:r=[],edges:o=[]}=JSON.parse(n),i=await Promise.all(r.map(async l=>{if(l.type==="file"&&l.file){let c=this.vault.getAbstractFileByPath(l.file),u=c instanceof iqe.TFile?await this.vault.read(c):"";return{...l,content:u}}return l.type==="text"?{...l,content:l.text??""}:{...l,content:""}})),s=[...o];sPe(this,CG,sqe).call(this,i,s);let a=Object.fromEntries(i.map(l=>[l.id,l]));return{nodes:i,edges:s,byId:a}}buildPrompt(e){let n=new Map,r=e.nodes.filter(a=>a.type==="group");for(let a of r){let l=e.nodes.filter(c=>{if(c.id===a.id)return!1;let u=c.x+c.width/2,d=c.y+c.height/2;return u>=a.x&&d>=a.y&&u<=a.x+a.width&&d<=a.y+a.height});n.set(a.label||a.id,l)}let o=`This canvas contains the following elements:

`,i=a=>{switch(a.type){case"file":return`- File: ${a.file}
Content:
${a.content}
`;case"text":return`- Text: "${a.text}"
`;case"link":return`- Link: ${a.url}
`;default:return""}};r.forEach(a=>{let l=a.label||a.id,c=n.get(l)||[];o+=`Group "${l}" contains:
`,c.forEach(u=>{o+=i(u)}),o+=`
`});let s=e.nodes.filter(a=>a.type==="group"?!1:!Array.from(n.values()).flat().some(l=>l.id===a.id));return s.length>0&&(o+=`Elements outside of groups:
`,s.forEach(a=>{o+=i(a)})),o+=`
When describing this canvas, please:
`,o+=`- Use the actual titles/names of elements instead of their IDs
`,o+=`- Pay attention to the content and relationships between elements
`,o+=`- Describe files by their names, links by their URLs, and text nodes by their content
`,o}};CG=new WeakSet,sqe=function(e,n){let r=e.filter(o=>o.type==="group");for(let o of r)for(let i of e){if(i.id===o.id)continue;let s=i.x+i.width/2,a=i.y+i.height/2;s>=o.x&&a>=o.y&&s<=o.x+o.width&&a<=o.y+o.height&&n.push({id:crypto.randomUUID(),fromNode:o.id,toNode:i.id,label:"contains"})}};async function DC(t,e,n){let r=q().convertedDocOutputFolder??"";await rqe(t,e,n,r)}var _G=class{constructor(){this.miyoClient=new wp}async parsePdf(e,n){let r=q();if(!r.enableMiyo||e.extension.toLowerCase()!=="pdf")return null;try{let o=await this.miyoClient.resolveBaseUrl(Jm(r)),i=n.getName(),s=await this.miyoClient.parseDoc(o,i,e.path);return typeof s.text!="string"||s.text.trim().length===0?{error:"Miyo parse-doc returned empty text"}:(k(`[SelfHostPdfParser] Parsed PDF via Miyo: ${e.path}`),{content:s.text})}catch(o){let i=o instanceof Error?o.message:String(o);return ee(`[SelfHostPdfParser] Failed to parse ${e.path} via Miyo parse-doc: ${i}`),{error:i}}}},pye=class{constructor(){this.supportedExtensions=["md","base"]}async parseFile(e,n){return await n.read(e)}},SG=class{constructor(e){this.supportedExtensions=["pdf"];this.brevilabsClient=e,this.pdfCache=xG.getInstance(),this.selfHostPdfParser=new _G}async parseFile(e,n){try{k("Parsing PDF file:",e.path);let r=await this.pdfCache.get(e);if(r)return k("Using cached PDF content for:",e.path),await DC(e,r.response,n),r.response;let o=q();if(pc()&&o.enableMiyo&&e.extension.toLowerCase()==="pdf"){let a=await this.selfHostPdfParser.parsePdf(e,n);if(a&&"content"in a)return await this.pdfCache.set(e,{response:a.content,elapsed_time_ms:0}),await DC(e,a.content,n),a.content;if(a&&"error"in a)return ee(`[PDFParser] Miyo parse failed for ${e.path}: ${a.error}`),`[Error: Could not extract content from PDF ${e.basename}. ${a.error}]`}let i=await n.readBinary(e);k("Calling pdf4llm API for:",e.path);let s=await this.brevilabsClient.pdf4llm(i);return await this.pdfCache.set(e,s),await DC(e,s.response,n),s.response}catch(r){return z(`Error extracting content from PDF ${e.path}:`,r),`[Error: Could not extract content from PDF ${e.basename}]`}}async clearCache(){k("Clearing PDF cache"),await this.pdfCache.clear()}},mye=class{constructor(){this.supportedExtensions=["canvas"]}async parseFile(e,n){try{k("Parsing Canvas file:",e.path);let r=new bG(n),o=await r.load(e);return r.buildPrompt(o)}catch(r){return z(`Error parsing Canvas file ${e.path}:`,r),`[Error: Could not parse Canvas file ${e.basename}]`}}},lqe=["pdf","602","abw","cgm","cwk","doc","docx","docm","dot","dotm","hwp","key","lwp","mw","mcw","pages","pbd","ppt","pptm","pptx","pot","potm","potx","rtf","sda","sdd","sdp","sdw","sgl","sti","sxi","sxw","stw","sxg","txt","uof","uop","uot","vor","wpd","wps","xml","zabw","epub","jpg","jpeg","png","gif","bmp","svg","tiff","webp","web","htm","html","xlsx","xls","xlsm","xlsb","xlw","csv","dif","sylk","slk","prn","numbers","et","ods","fods","uos1","uos2","dbf","wk1","wk2","wk3","wk4","wks","123","wq1","wq2","wb1","wb2","wb3","qpw","xlr","eth","tsv","mp3","mp4","mpeg","mpga","m4a","wav","webm"],oO=class oO{constructor(e,n=null){this.supportedExtensions=[...lqe];this.brevilabsClient=e,this.projectContextCache=ti.getInstance(),this.selfHostPdfParser=new _G,this.currentProject=n}static resetRateLimitNoticeTimer(){oO.lastRateLimitNoticeTime=0}async parseFile(e,n){try{if(k(`[Docs4LLMParser] Project ${this.currentProject?.name}: Parsing ${e.extension} file: ${e.path}`),!this.currentProject)throw z("[Docs4LLMParser] No project context for parsing file: ",e.path),new Error("No project context provided for file parsing");let r=await this.projectContextCache.getOrReuseFileContext(this.currentProject,e.path);if(r)return k(`[Docs4LLMParser] Project ${this.currentProject.name}: Using cached content for: ${e.path}`),await DC(e,r,n),r;if(k(`[Docs4LLMParser] Project ${this.currentProject.name}: Cache miss for: ${e.path}. Proceeding to API call.`),pc()&&q().enableMiyo&&e.extension.toLowerCase()==="pdf"){let a=await this.selfHostPdfParser.parsePdf(e,n);if(a&&"content"in a)return await this.projectContextCache.setFileContext(this.currentProject,e.path,a.content),await DC(e,a.content,n),k(`[Docs4LLMParser] Project ${this.currentProject.name}: Parsed PDF via Miyo: ${e.path}`),a.content;if(a&&"error"in a)throw new Error(`Miyo failed to parse ${e.basename}: ${a.error}`)}let o=await n.readBinary(e);k(`[Docs4LLMParser] Project ${this.currentProject.name}: Calling docs4llm API for: ${e.path}`);let i=await this.brevilabsClient.docs4llm(o,e.extension);if(!i||!i.response)throw new Error("Empty response from docs4llm API");let s="";if(typeof i.response=="string")s=i.response;else if(Array.isArray(i.response)){let a=[];for(let l of i.response){let c=l;c?.content&&(c.content.md?a.push(c.content.md):c.content.text&&a.push(c.content.text))}s=a.join(`

`)}else if(typeof i.response=="object"){let a=i.response;a.md?s=a.md:a.text?s=a.text:a.content?s=a.content:s=JSON.stringify(i.response,null,2)}else s=JSON.stringify(i.response);return await this.projectContextCache.setFileContext(this.currentProject,e.path,s),await DC(e,s,n),k(`[Docs4LLMParser] Project ${this.currentProject.name}: Successfully processed and cached: ${e.path}`),s}catch(r){throw z(`[Docs4LLMParser] Project ${this.currentProject?.name}: Error processing file ${e.path}:`,r),uv(r)&&this.showRateLimitNotice(r),r}}showRateLimitNotice(e){let n=Date.now();if(n-oO.lastRateLimitNoticeTime<6e4)return;oO.lastRateLimitNoticeTime=n;let r=oqe(e);new aqe.Notice(`\u26A0\uFE0F Rate limit exceeded for document processing. Please try again in ${r}. Having fewer non-markdown files in the project will help.`,1e4)}async clearCache(){k("Cache clearing is now handled at the project level")}};oO.lastRateLimitNoticeTime=0;var mB=oO,iy=class{constructor(e,n,r=!1,o=null){this.parsers=new Map;this.registerParser(new pye),this.registerParser(new mB(e,o)),r||this.registerParser(new SG(e)),this.registerParser(new mye)}static getProjectSupportedExtensions(){let e=new Set;e.add("md");for(let n of lqe)e.add(n);return e.add("canvas"),e}registerParser(e){for(let n of e.supportedExtensions)this.parsers.set(n,e)}async parseFile(e,n){let r=this.parsers.get(e.extension);if(!r)throw new Error(`No parser found for file type: ${e.extension}`);return await r.parseFile(e,n)}supportsExtension(e){return this.parsers.has(e)}async clearPDFCache(){let e=this.parsers.get("pdf");e instanceof SG&&await e.clearCache()}};qe();var mP=require("obsidian");Zg();Ir();Qi();It();It();ye();var sy=class{static convert(e,n={}){let{includeSystemMessage:r=!0,mergeUserContent:o=!0,debug:i=!1}=n,s=[],a=e.layers.find(f=>f.id==="L1_SYSTEM"),l=e.layers.find(f=>f.id==="L2_PREVIOUS"),c=e.layers.find(f=>f.id==="L3_TURN"),u=e.layers.find(f=>f.id==="L4_STRIP"),d=e.layers.find(f=>f.id==="L5_USER");if(r&&a&&a.text){let f=[a.text];l&&l.text&&(f.push(`
## Context Library

The following notes are available for reference:

`+l.text),i&&k("[LayerToMessagesConverter] Added L2 (cumulative context) to system")),s.push({role:"system",content:f.join(`
`)}),i&&k("[LayerToMessagesConverter] Added L1 (System) + L2 (Cumulative) as stable prefix")}if(u&&u.text&&i&&k("[LayerToMessagesConverter] L4 (Strip) found but skipped (using LangChain memory)"),o){let f=[];if(c&&c.segments.length>0&&l){let p=new Set(l.segments.map(g=>g.id)),m=[],h=[];for(let g of c.segments)p.has(g.id)?m.push(g.id):h.push(g);if(m.length>0||h.length>0){let g=[];m.length>0&&g.push(`Context attached to this message:
`+m.map(y=>`- ${y}`).join(`
`)+`

Find them in the Context Library in the system prompt above.`),h.length>0&&g.push(h.map(y=>y.content).join(`
`)),f.push(g.join(`

`)),i&&k(`[LayerToMessagesConverter] Added L3: ${m.length} references, ${h.length} new items`)}}else c&&c.text&&(f.push(c.text),i&&k("[LayerToMessagesConverter] Added L3 (all new context)"));f.length>0&&d&&d.text&&f.push(`---

[User query]:`),d&&d.text&&(f.push(d.text),i&&k("[LayerToMessagesConverter] Added L5 (user message)")),f.length>0&&s.push({role:"user",content:f.join(`

`)})}else c&&c.text&&s.push({role:"user",content:c.text}),d&&d.text&&s.push({role:"user",content:d.text});return i&&(k(`[LayerToMessagesConverter] Converted envelope to ${s.length} messages`),s.forEach((f,p)=>{let m=f.content.substring(0,100);k(`  Message ${p+1} [${f.role}]: ${m}...`)})),s}static extractUserContent(e){let n=e.layers.find(i=>i.id==="L3_TURN"),r=e.layers.find(i=>i.id==="L5_USER"),o=[];return n&&n.text&&o.push(n.text),r&&r.text&&o.push(r.text),o.join(`

`)}static extractFullContext(e){let n=e.layers.find(s=>s.id==="L2_PREVIOUS"),r=e.layers.find(s=>s.id==="L3_TURN"),o=e.layers.find(s=>s.id==="L5_USER"),i=[];return n&&n.text&&i.push(n.text),r&&r.text&&i.push(r.text),o&&o.text&&i.push(o.text),i.join(`

`)}static extractSystemMessage(e){return e.layers.find(r=>r.id==="L1_SYSTEM")?.text||""}static getLayerHashes(e){return e.layerHashes}};ye();Se();qe();It();ye();qe();var $C=class{constructor(e){this.chainManager=e}async handleResponse(e,n,r,o,i,s,a,l){if((e||l?.wasTruncated)&&!(r.signal.aborted&&r.signal.reason==="new-chat")){let p=n.contextEnvelope?.layers.find(y=>y.id==="L5_USER")?.text||n.originalMessage||n.message,m=a||e||"[Response truncated - no content generated]";await this.chainManager.memoryManager.saveContext({input:p},{output:m});let g={message:e||(l?.wasTruncated?"_[The response was truncated before any content could be generated. Try increasing the max tokens limit.]_":""),sender:Sd,isVisible:!0,timestamp:ll(new Date),sources:s,responseMetadata:l};o(g),i("")}else r.signal.reason==="new-chat"&&i("");let u=this.chainManager.memoryManager.getMemory().chatHistory.messages;k(`Chat memory updated:
`,{turns:Array.isArray(u)?u.length:0});let d=2e3;try{let{parseToolCallMarkers:f}=await Promise.resolve().then(()=>(yye(),uqe)),m=f(e).segments.map(g=>g.type==="text"?g.content:"").join("").trim();m||(m=e||"");let h=m.length>d?m.slice(0,d)+"... (truncated)":m;k(`Final AI response (truncated):
`,h)}catch{let f=typeof e=="string"?e:String(e??""),p=f.length>d?f.slice(0,d)+"... (truncated)":f;k(`Final AI response (truncated):
`,p)}return e}async handleError(e,n){let r=Xt(e);z("Error during LLM invocation:",r);let o=e?.response?.data?.error||r,i=o?.code||r,s="";e?.message?.includes("Invalid license key")?s="Invalid Copilot Plus license key. Please check your license key in settings.":i==="model_not_found"?s="You do not have access to this model or the model does not exist, please check with your API provider.":s=`${i}`,z(o),n(this.enhancedErrorMsg(s,r,e))}enhancedErrorMsg(e,n,r){let o=e.search("Troubleshooting URL");return e=o!==-1?e.slice(0,o):e,this.isAuthenticationError(r,n)&&(e=`Something went wrong. Please check if you have set your API key.
Path: Settings > copilot plugin > Basic Tab > Set Keys.
Or check model config
Error Details: `+e),e}isAuthenticationError(e,n){let r=e?.response,o=r?.data?.error??e?.error,i=r?.status??o?.status,s=typeof i=="string"?Number.parseInt(i,10):i,a=typeof o=="object"&&o!==null?o:void 0,l=(typeof a?.message=="string"?a.message:n).toLowerCase(),c=typeof a?.code=="string"?a.code.toLowerCase():"",u=typeof a?.type=="string"?a.type.toLowerCase():"";return s===401?!0:["api key","apikey","unauthorized","authentication","invalid authentication"].some(f=>l.includes(f)||c.includes(f)||u.includes(f))}};ye();function wye(t){let e=[];for(let n of t){if(!n)continue;let r=n;if(typeof r._getType=="function"){let o=r._getType();o==="human"?e.push({role:"user",content:r.content}):o==="ai"&&e.push({role:"assistant",content:r.content})}else if(r.content!==void 0){let o=lUt(r);o&&e.push({role:o,content:r.content})}}return e}function lUt(t){return t.role==="human"||t.role==="user"||t.sender==="user"?"user":t.role==="ai"||t.role==="assistant"||t.sender==="AI"?"assistant":null}function cUt(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&n.type==="text").map(n=>n.text||"").join(" ")||"[Image content]":String(t||"")}function dqe(t){return t.map(e=>({role:e.role,content:cUt(e.content)}))}async function FC(t,e){let r=(await t.loadMemoryVariables({})).history||[],o=r.length?wye(r):[];for(let l of o)e.push({role:l.role,content:l.content});let i=0;for(let l of e)typeof l.content=="string"&&l.role==="system"&&(i+=l.content.length);let s=0;for(let l of o)typeof l.content=="string"&&(s+=l.content.length);let a=i+s;return a>2e6&&k("[Token Budget] Large payload detected (excluding user message):",{"L1+L2 (system)":`${Math.round(i/4e3)}k tokens`,"L4 (history)":`${Math.round(s/4e3)}k tokens (${o.length} msgs)`,total:`${Math.round(a/4e3)}k tokens`}),o}ye();var Vi=class t{constructor(){this.tools=new Map}static getInstance(){return t.instance||(t.instance=new t),t.instance}register(e){this.tools.set(e.metadata.id,e)}registerAll(e){e.forEach(n=>this.register(n))}getAllTools(){return Array.from(this.tools.values())}getEnabledTools(e,n){let r=[];for(let[o,i]of this.tools){let{metadata:s,tool:a}=i;if(s.isAlwaysEnabled){(!s.requiresVault||n)&&r.push(a);continue}e.has(o)&&(!s.requiresVault||n)&&r.push(a)}return r}getToolsByCategory(){let e=new Map;for(let n of this.tools.values()){let r=n.metadata.category;e.has(r)||e.set(r,[]),e.get(r).push(n)}return e}getConfigurableTools(){return Array.from(this.tools.values()).filter(e=>!e.metadata.isAlwaysEnabled)}getCopilotCommandMappings(){let e=new Map;for(let n of this.tools.values()){let r=n.metadata.copilotCommands;if(r)for(let o of r){let i=o.toLowerCase();e.has(i)||e.set(i,n)}}return e}getToolMetadata(e){return this.tools.get(e)?.metadata}getToolDefinition(e){return this.tools.get(e)}clear(){this.tools.clear()}};var iO=null;function uUt(t){let e=new WeakSet;return JSON.stringify(t,(n,r)=>{if(typeof r=="object"&&r!==null){if(e.has(r))return"[Circular]";e.add(r)}return typeof r=="bigint"?r.toString():r},2)}function dUt(t,e){let n=[];e&&(n.push(`msg:${e.messageId??"N/A"} | conv:${e.conversationId??"N/A"} | v${e.version}`),n.push(""));let r=Vi.getInstance(),o=new Set(r.getAllTools().map(u=>u.tool.name)),i=u=>{let d=[],f=/<(\w+)>([\s\S]*?)<\/\1>/g,p;for(;(p=f.exec(u))!==null;){let m=p[1],h=p[2];if(o.has(m)){let g=h.length>200?h.substring(0,200).trim()+"...[truncated]":h.trim();d.push({tool:m,preview:g})}}return d},s=u=>typeof u.content=="string"?u.content:Array.isArray(u.content)?u.content.filter(f=>f.type==="text").map(f=>f.text??"").join(`
`):"",a=Array.isArray(t)?t:[],l=0;for(let u=0;u<a.length;u++){let d=a[u],f=s(d);if(d.role==="system"){n.push("\u2501\u2501\u2501 SYSTEM MESSAGE \u2501\u2501\u2501"),n.push("");let p=e?.layers.find(h=>h.id==="L1_SYSTEM"),m=e?.layers.find(h=>h.id==="L2_PREVIOUS");if(p&&f.includes(p.text)){let h=p.hash.substring(0,8);n.push(`\u{1F512} L1_SYSTEM (${h}) [CACHEABLE]`);let g=f.indexOf(p.text)+p.text.length,y=p.text.length>300?p.text.substring(0,300)+"...[truncated]":p.text;if(n.push(y),n.push(""),m&&m.text){let x=m.hash.substring(0,8);n.push(`\u{1F512} L2_PREVIOUS (${x}) [CACHEABLE]`);let b=m.text.length>300?m.text.substring(0,300)+"...[truncated]":m.text;n.push(b),n.push("")}let w=f.substring(g),v=i(w);if(v.length>0){n.push("--- PER-TURN ADDITIONS (not cached) ---"),n.push("");for(let x of v)n.push(`\u{1F4E6} TOOL: ${x.tool} (turn-specific RAG)`),n.push(x.preview),n.push("")}}else{let h=i(f);if(h.length>0){let g=f.match(/<(\w+)>/);if(g){let y=f.substring(0,g.index);if(y.trim()){let w=y.length>300?y.substring(0,300)+"...[truncated]":y;n.push(w),n.push("")}}n.push("--- PER-TURN ADDITIONS (not cached) ---"),n.push("");for(let y of h)n.push(`\u{1F4E6} TOOL: ${y.tool}`),n.push(y.preview),n.push("")}else{let g=f.length>300?f.substring(0,300)+"...[truncated]":f;n.push(g),n.push("")}}}else(d.role==="user"||d.role==="assistant")&&u<a.length-1&&l++}l>0&&(n.push("\u2501\u2501\u2501 CHAT HISTORY (L4) \u2501\u2501\u2501"),n.push(""),n.push(`${l} message(s)`),n.push(""));let c=a[a.length-1];if(c&&c.role==="user"){n.push("\u2501\u2501\u2501 USER MESSAGE \u2501\u2501\u2501"),n.push("");let u=s(c),d=i(u);if(d.length>0){n.push("--- PER-TURN TOOL RESULTS ---"),n.push("");for(let m of d)n.push(`\u{1F4E6} TOOL: ${m.tool}`),n.push(m.preview),n.push("")}let f=e?.layers.find(m=>m.id==="L3_TURN"),p=e?.layers.find(m=>m.id==="L5_USER");if(f&&f.text&&u.includes(f.text)){let m=f.hash.substring(0,8);n.push(`\u26A1 L3_TURN (${m})`);let h=f.text.length>300?f.text.substring(0,300)+"...[truncated]":f.text;n.push(h),n.push("")}if(p&&p.text&&u.includes(p.text)){let m=p.hash.substring(0,8);n.push(`\u26A1 L5_USER (${m})`),n.push(p.text),n.push("")}}return n.join(`
`)}function UC(t){let{messages:e,modelName:n,contextEnvelope:r}=t;try{iO={timestamp:new Date().toISOString(),modelName:n,serializedMessages:uUt(e),messagesArray:e,contextEnvelope:r}}catch{iO={timestamp:new Date().toISOString(),modelName:n,serializedMessages:String(e),messagesArray:e,contextEnvelope:r}}}function sO(){iO=null}async function TG(){if(!iO)return;let{timestamp:t,modelName:e,serializedMessages:n,messagesArray:r,contextEnvelope:o}=iO,i=[`### Prompt \u2014 ${t}${e?` \u2014 ${e}`:""}`,"","**Actual Messages Sent to LLM:**","","```json",n,"```",""],s=dUt(r,o);i.push("**Layered Context Metadata:**"),i.push(""),i.push("```"),i.push(s),i.push("```"),i.push(""),jW(i),iO=null}function fqe(t){let e=t.response_metadata||{};return e.finish_reason==="length"?{wasTruncated:!0,message:"Response truncated due to token limit"}:e.stop_reason==="max_tokens"?{wasTruncated:!0,message:"Response truncated due to max_tokens limit"}:e.finishReason==="MAX_TOKENS"||e.finish_reason==="MAX_TOKENS"?{wasTruncated:!0,message:"Response truncated due to MAX_TOKENS limit"}:{wasTruncated:!1,message:null}}function pqe(t){let e=t.response_metadata||{};if(e.tokenUsage){let n=e.tokenUsage;return{inputTokens:n.promptTokens,outputTokens:n.completionTokens,totalTokens:n.totalTokens}}if(e.usage){let n=e.usage;return{inputTokens:n.input_tokens||n.inputTokens||n.inputTokenCount||n.prompt_tokens,outputTokens:n.output_tokens||n.outputTokens||n.outputTokenCount||n.completion_tokens,totalTokens:n.total_tokens||n.totalTokens||(n.input_tokens||n.inputTokenCount||0)+(n.output_tokens||n.outputTokenCount||0)}}return t.usage_metadata?{inputTokens:t.usage_metadata.input_tokens,outputTokens:t.usage_metadata.output_tokens,totalTokens:t.usage_metadata.total_tokens}:null}function fUt(t){return`<errorChunk>${t}</errorChunk>`}function IG(t,e){let n=fUt(t);return e?`${e}
${n}`:`
${n}`}Kr();ye();function vye(t,e,n){return new Wd({content:n,tool_call_id:t,name:e})}function PG(){let t=Date.now(),e=Math.random().toString(36).substring(2,11);return`call_${t}_${e}`}function mqe(t,e){let n=e.index??0,r=t.get(n)||{name:"",args:""};e.id&&(r.id=e.id);let o=e.name??e.functionCall?.name;o&&(r.name+=o),e.args&&(r.args+=e.args),t.set(n,r)}function EG(t){let e=[];for(let n of t.values()){if(!n.name)continue;let r={};if(n.args)try{r=JSON.parse(n.args)}catch{z(`[ToolCall] Failed to parse args for tool "${n.name}": ${n.args}`),r={}}e.push({id:n.id||PG(),name:n.name,args:r})}return e}function hqe(t,e){return new kn({content:t,tool_calls:e.map(n=>({id:n.id,name:n.name,args:n.args,type:"tool_call"}))})}ye();var pUt=["<|im_end|>","<|im_start|>","<|eot_id|>","<|start_header_id|>","<|end_header_id|>","<end_of_turn>","<start_of_turn>","<|end|>","<|assistant|>","<|user|>","<|system|>","</s>","[INST]","[/INST]","<|endoftext|>","<|end\u2581of\u2581sentence|>","<|END_OF_TURN_TOKEN|>","<|START_OF_TURN_TOKEN|>"],mUt=new RegExp(pUt.map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),"g");function xye(t){return t.replace(mUt,"")}var of=class{constructor(e,n=!1){this.updateCurrentAiMessage=e;this.excludeThinking=n;this.hasOpenThinkBlock=!1;this.fullResponse="";this.errorResponse="";this.wasTruncated=!1;this.tokenUsage=null;this.hasHandledTextLevelThinkTag=!1;this.excludedThinkBlockStart=-1;this.toolCallChunks=new Map;this.accumulatedToolCalls=[];k(`[ThinkBlockStreamer] Created with excludeThinking=${n}`)}handleTextLevelThinkTags(){if(this.excludeThinking){this.handleExcludedThinkTags();return}let e=this.fullResponse.includes("</think>"),n=this.fullResponse.includes("<think>");e&&!n&&!this.hasHandledTextLevelThinkTag&&(this.hasHandledTextLevelThinkTag=!0,ee("Detected </think> closing tag without opening <think> tag. This may indicate a misconfigured chat template in LM Studio. Adding opening tag."),this.fullResponse="<think>"+this.fullResponse)}handleExcludedThinkTags(){if(this.excludedThinkBlockStart>=0){let r=this.fullResponse.indexOf("</think>",this.excludedThinkBlockStart);if(r!==-1){let o=this.fullResponse.substring(0,this.excludedThinkBlockStart),i=this.fullResponse.substring(r+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,this.excludedThinkBlockStart);return}let e=this.fullResponse.indexOf("<think>");if(e!==-1){this.excludedThinkBlockStart=e;let r=this.fullResponse.indexOf("</think>",e);if(r!==-1){let o=this.fullResponse.substring(0,e),i=this.fullResponse.substring(r+8);this.fullResponse=(o+i).trimStart(),this.excludedThinkBlockStart=-1}else this.fullResponse=this.fullResponse.substring(0,e);return}let n=this.fullResponse.indexOf("</think>");n!==-1&&(this.fullResponse=this.fullResponse.substring(n+8).trimStart())}handleClaudeChunk(e){let n="",r=!1;for(let o of e)switch(o.type){case"text":n+=o.text;break;case"thinking":if(r=!0,this.excludeThinking)break;this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),o.thinking!==void 0&&(this.fullResponse+=o.thinking),this.updateCurrentAiMessage(this.fullResponse);break}return n&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),n&&(this.fullResponse+=xye(n)),r}handleDeepseekChunk(e){return typeof e.content=="string"&&(this.fullResponse+=xye(e.content)),e.additional_kwargs?.reasoning_content?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),e.additional_kwargs.reasoning_content!==void 0&&(this.fullResponse+=e.additional_kwargs.reasoning_content)),!0):!1}handleOpenRouterChunk(e){return e.additional_kwargs?.delta?.reasoning?(this.excludeThinking||(this.hasOpenThinkBlock||(this.fullResponse+=`
<think>`,this.hasOpenThinkBlock=!0),this.fullResponse+=e.additional_kwargs.delta.reasoning),!0):(typeof e.content=="string"&&e.content&&this.hasOpenThinkBlock&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),typeof e.content=="string"&&e.content&&(this.fullResponse+=e.content),!1)}handleToolCallChunks(e){let n=e.tool_call_chunks;if(!(!n||!Array.isArray(n)))for(let r of n){let o=r.index??0,i=this.toolCallChunks.get(o)||{name:"",args:""};r.id&&(i.id=r.id),r.name&&(i.name+=r.name),r.args&&(i.args+=r.args),this.toolCallChunks.set(o,i)}}processChunk(e){fqe(e).wasTruncated&&(this.wasTruncated=!0);let r=pqe(e);r&&(this.tokenUsage=r),this.handleToolCallChunks(e);let o=Array.isArray(e.content)||e.additional_kwargs?.delta?.reasoning||e.additional_kwargs?.reasoning_details&&Array.isArray(e.additional_kwargs.reasoning_details)&&e.additional_kwargs.reasoning_details.length>0||e.additional_kwargs?.reasoning_content;this.hasOpenThinkBlock&&!o&&(this.fullResponse+="</think>",this.hasOpenThinkBlock=!1),Array.isArray(e.content)?this.handleClaudeChunk(e.content):e.additional_kwargs?.reasoning_content?this.handleDeepseekChunk(e):o?this.handleOpenRouterChunk(e):this.handleDeepseekChunk(e),this.handleTextLevelThinkTags(),this.updateCurrentAiMessage(this.fullResponse)}processErrorChunk(e){this.errorResponse=IG(e)}getToolCalls(){return this.accumulatedToolCalls.length>0?this.accumulatedToolCalls:EG(this.toolCallChunks)}hasToolCalls(){return this.toolCallChunks.size>0||this.accumulatedToolCalls.length>0}setToolCalls(e){this.accumulatedToolCalls=e}buildAIMessage(){let e=this.getToolCalls();return hqe(this.fullResponse,e)}close(){return this.hasOpenThinkBlock&&(this.fullResponse+="</think>"),this.handleTextLevelThinkTags(),this.errorResponse&&(this.fullResponse+=this.errorResponse),this.updateCurrentAiMessage(this.fullResponse),{content:this.fullResponse,wasTruncated:this.wasTruncated,tokenUsage:this.tokenUsage}}};Ir();var hB=class extends $C{async constructMessages(e){if(!e.contextEnvelope)throw new Error("[LLMChainRunner] Context envelope is required but not available. Cannot proceed with LLM chain.");k("[LLMChainRunner] Using envelope-based context");let n=sy.convert(e.contextEnvelope,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),r=[],o=n.find(a=>a.role==="system");o&&r.push(o);let i=this.chainManager.memoryManager.getMemory();await FC(i,r);let s=n.find(a=>a.role==="user");if(s)if(e.content&&Array.isArray(e.content)){let a=e.content.map(l=>l.type==="text"?{...l,text:s.content}:l);r.push({role:"user",content:a})}else r.push(s);return r}async run(e,n,r,o,i){let s=q(),a=Iu(),l=!1;try{l=!$f(a,s.activeModels).capabilities?.includes("reasoning")}catch(f){k("Could not determine model capabilities, defaulting to include thinking blocks",f)}let c=new of(r,l);try{let f=await this.constructMessages(e),m=this.chainManager.chatModelManager.getChatModel()?.modelName;UC({messages:f,modelName:m,contextEnvelope:e.contextEnvelope}),k(`Final Request to AI:
`,f);let h=await Nc(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:n.signal}));for await(let g of h){if(n.signal.aborted){k("Stream iteration aborted",{reason:n.signal.reason});break}c.processChunk(g)}}catch(f){(f instanceof Error?f.name:"")==="AbortError"||n.signal.aborted?k("Stream aborted by user",{reason:n.signal.reason}):await this.handleError(f,c.processErrorChunk.bind(c))}let u=c.close(),d={wasTruncated:u.wasTruncated,tokenUsage:u.tokenUsage??void 0};return n.signal.aborted&&n.signal.reason==="new-chat"?(r(""),""):(await this.handleResponse(u.content,e,n,o,r,void 0,void 0,d),u.content)}};It();qe();async function AG(t,e){let n=`Given the following conversation and a follow up question,
    summarize the conversation as context and keep the follow up question unchanged, in its original language.
    If the follow up question is unrelated to its preceding messages, return this follow up question directly.
    If it is related, then combine the summary and the follow up question to construct a standalone question.
    Make sure to keep any [[]] wrapped note titles in the question unchanged.
    If there's nothing in the chat history, just return the follow up question.

    Chat History:
    {chat_history}
    Follow Up Input: {question}
    Standalone question:`,r=e.map(({role:o,content:i})=>`${o}: ${i}`).join(`
`);return await Nc(async()=>{let o=await Sl.instance.getCurrentChainManager().chatModelManager.getChatModelWithTemperature(0),i="",s=await o.stream([{role:"user",content:n.replace("{chat_history}",r).replace("{question}",t)}]);for await(let l of s)i+=Kx(l.content);let a=jte(i);return BAe(a)})}ye();ye();ns();yp();Se();ye();qe();iv();lO();var kG=class extends ay{constructor(n,r,o){super();this.lc_namespace=["self_host_retriever"];this.app=n,this.backend=r,this.options={...o,minSimilarityScore:o.minSimilarityScore??.01,salientTerms:o.salientTerms??[],returnAll:o.returnAll??!1}}async getRelevantDocuments(n,r){try{if(!await this.backend.isAvailable())return ee("SelfHostRetriever: Backend is not available"),[];let s=Df(n,this.app.vault).map(f=>f.basename),a=[...new Set([...this.options.salientTerms||[],...s])],l=this.buildFilter(),c=this.options.returnAll?100:this.options.maxK,u=await this.backend.search(n,{limit:c,minScore:this.options.minSimilarityScore,filter:l});k(`SelfHostRetriever: Found ${u.length} results for query "${n.substring(0,50)}..."`);let d=this.convertToDocuments(u);return a.length>0?this.boostBySalientTerms(d,a):d}catch(o){return ee(`SelfHostRetriever: Search failed: ${o}`),[]}}buildFilter(){let n={};return this.options.timeRange&&(n.mtime={gte:this.options.timeRange.startTime,lte:this.options.timeRange.endTime}),this.options.tagTerms&&this.options.tagTerms.length>0&&(n.tags={containsAny:this.options.tagTerms}),Object.keys(n).length>0?n:void 0}convertToDocuments(n){return n.map(r=>new fi({pageContent:r.content,metadata:{...r.metadata,score:r.score,rerank_score:r.score,id:r.id,source:"self_host"}}))}boostBySalientTerms(n,r){return n.map(s=>{let a=s.pageContent.toLowerCase(),l=(s.metadata?.title||"").toLowerCase();if(r.some(u=>a.includes(u.toLowerCase())||l.includes(u.toLowerCase()))){let u=(s.metadata?.score||0)*1.1;return new fi({pageContent:s.pageContent,metadata:{...s.metadata,score:u,rerank_score:u,salientBoost:!0}})}return s}).sort((s,a)=>(a.metadata?.score||0)-(s.metadata?.score||0))}getBackend(){return this.backend}};iv();lO();ye();RN();yp();Se();N0();var WG=class extends ay{constructor(n,r){super();this.app=n;this.options=r;this.lc_namespace=["miyo_semantic_retriever"];this.client=new wp,this.returnAll=!!r.returnAll,this.maxK=Math.max(1,r.maxK),this.minSimilarityScore=r.minSimilarityScore??.1}async getRelevantDocuments(n,r){let o=await this.searchMiyo(n),i=this.deduplicateResults(o);return q().debug&&this.logDebugInfo(n,o,i),i}async searchMiyo(n){try{let r=await this.client.resolveBaseUrl(Jm(q())),o=this.returnAll?ni:this.maxK,i=this.buildSearchFilters();q().debug&&k("MiyoSemanticRetriever: search params:",{baseUrl:r,limit:o,maxK:this.maxK,minSimilarityScore:this.minSimilarityScore,returnAll:this.returnAll,filters:i});let s=q().miyoSearchAll?void 0:Jg(this.app),l=(await this.client.search(r,s,n,o,i)).results||[],c=l.filter(u=>this.isScoreAboveThreshold(u));return q().debug&&k(`MiyoSemanticRetriever: received ${l.length} results, ${c.length} after threshold`),c.map(u=>this.toDocument(u))}catch(r){return ee(`MiyoSemanticRetriever: search failed: ${r}`),[]}}buildSearchFilters(){if(!this.options.timeRange)return;let{startTime:n,endTime:r}=this.options.timeRange;return[{field:"mtime",gte:n,lte:r}]}toDocument(n){let r=i0(this.app,n.path),o=n.metadata??{},i=o.chunkId||(n.chunk_index!==void 0?`${r}#${n.chunk_index}`:void 0),s=typeof n.score=="number"?n.score.toFixed(2):"?";return new fi({pageContent:n.chunk_text??"",metadata:{...o,score:n.score,explanation:`miyo ${s}`,path:r,mtime:n.mtime,ctime:n.ctime,title:n.title??"",id:n.id,embeddingModel:n.embedding_model,tags:n.tags??[],extension:n.extension,created_at:n.created_at,nchars:n.nchars,chunkId:i}})}isScoreAboveThreshold(n){let r=n.score;return typeof r!="number"||Number.isNaN(r)?!0:r>=this.minSimilarityScore}deduplicateResults(n){let r=new Map,o=i=>{let s=this.getDocumentKey(i);r.has(s)||r.set(s,i)};return n.forEach(o),q().debug&&r.size!==n.length&&k(`MiyoSemanticRetriever: deduplicated semantic results from ${n.length} to ${r.size}`),Array.from(r.values())}logDebugInfo(n,r,o){k("*** MIYO SEMANTIC RETRIEVER DEBUG INFO: ***"),k("Query: ",n),k("Semantic Chunks: ",r),k("Deduplicated Chunks: ",o);let i=r.reduce((s,a)=>{let l=a.metadata?.score;return typeof l=="number"&&!Number.isNaN(l)?Math.max(s,l):s},0);k("Max Miyo Score: ",i)}getDocumentKey(n){let r=n.metadata??{};return r.chunkId||r.path||r.id||r.title||`${n.pageContent.slice(0,64)}::${n.pageContent.length}`}};Kve();N0();fz();function F8(t){return{minSimilarityScore:t.minSimilarityScore??.1,maxK:t.maxK,salientTerms:t.salientTerms??[],timeRange:t.timeRange,textWeight:t.textWeight,returnAll:t.returnAll??!1,useRerankerThreshold:t.useRerankerThreshold,tagTerms:t.tagTerms??[]}}var Al=class Al{static registerSelfHostedBackend(e){Al.selfHostedBackend=e,k("RetrieverFactory: Self-hosted backend registered")}static clearSelfHostedBackend(){Al.selfHostedBackend=null,k("RetrieverFactory: Self-hosted backend cleared")}static hasSelfHostedBackend(){return Al.selfHostedBackend!==null}static async createRetriever(e,n,r){let o=r?{...q(),...r}:q(),i=F8(n);if(Al.shouldUseMiyo(o)){let a=Al.createMiyoRetriever(e,n);return k("RetrieverFactory: Using MiyoSemanticRetriever (standalone)"),{retriever:a,type:"semantic",reason:"Miyo search is enabled"}}if(pc()){if(o.selfHostUrl){let l=await Al.getSelfHostedBackend(o);if(l){let c=new kG(e,l,i);return k("RetrieverFactory: Using self-host mode backend"),{retriever:c,type:"self_hosted",reason:"Self-host mode is enabled and backend is available"}}ee("RetrieverFactory: Self-host mode backend unavailable, falling back")}else k("RetrieverFactory: Self-host mode enabled but URL not configured, falling back");if(o.enableSemanticSearchV3){let l=new tP(e,i);return k("RetrieverFactory: Using MergedSemanticRetriever (semantic search fallback for self-host mode)"),{retriever:l,type:"semantic",reason:"Self-host mode fallback to semantic search"}}let a=new ah(e,i);return k("RetrieverFactory: Using TieredLexicalRetriever (lexical search fallback for self-host mode)"),{retriever:a,type:"lexical",reason:"Self-host mode fallback to lexical search (semantic disabled)"}}if(o.enableSemanticSearchV3){let a=new tP(e,i);return k("RetrieverFactory: Using MergedSemanticRetriever (semantic search)"),{retriever:a,type:"semantic",reason:"Semantic search is enabled"}}let s=new ah(e,i);return k("RetrieverFactory: Using TieredLexicalRetriever (lexical search)"),{retriever:s,type:"lexical",reason:"Default lexical search"}}static createLexicalRetriever(e,n){return new ah(e,F8(n))}static createSemanticRetriever(e,n){return Al.shouldUseMiyo(q())?Al.createMiyoRetriever(e,n):new tP(e,F8(n))}static async getSelfHostedBackend(e){if(Al.selfHostedBackend)try{if(await Al.selfHostedBackend.isAvailable())return Al.selfHostedBackend;ee("RetrieverFactory: Registered backend is not available")}catch(n){ee("RetrieverFactory: Error checking backend availability:",n)}return ee("RetrieverFactory: No self-hosted backend available. Register a VectorSearchBackend implementation via RetrieverFactory.registerSelfHostedBackend()"),null}static getRetrieverType(e){let n=e?{...q(),...e}:q();return Al.shouldUseMiyo(n)?"semantic":pc()&&n.selfHostUrl&&Al.selfHostedBackend?"self_hosted":n.enableSemanticSearchV3?"semantic":"lexical"}static shouldUseMiyo(e){return Fa(e)}static isMiyoActive(){return Al.shouldUseMiyo(q())}static createMiyoRetriever(e,n){let r=F8(n),o=r.returnAll?ni:Math.min(r.maxK*2,ni);return new WG(e,{...r,maxK:o})}};Al.selfHostedBackend=null;var lh=Al;U8();B8();kye();Se();qe();var D9e=`CITATION RULES:
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. BE SELECTIVE: ONLY cite when introducing NEW factual claims, specific data, or direct quotes from sources
3. IMPORTANT: Do NOT cite every sentence or bullet point. This creates clutter and poor readability.
4. DO NOT cite for:
   - General knowledge or common facts
   - Your own analysis or synthesis
   - Transitional or concluding statements
   - Every single sentence (AVOID CITATION CLUTTER - aim for 1-3 citations per paragraph maximum)
5. Citations are for SOURCE ATTRIBUTION, not for proving every statement
6. GOOD: One citation per key concept. BAD: Citation after every sentence.
7. Place citations immediately after the specific claim: "The study found X [^1]" not "The study found X. [^1]"
8. Do not reuse any bracketed numbers that appear inside the source content itself
9. If multiple source chunks come from the same document, cite each relevant chunk separately (e.g., [^1] and [^2] can both be from the same document title)
10. End with '#### Sources' section containing: [^n]: [[Title]] (one per line, matching citation order)`,mjt=`WEB CITATION RULES:
1. START with [^1] and increment sequentially ([^1], [^2], [^3], etc.) with NO gaps
2. Cite ONLY when introducing new factual claims, statistics, or direct quotes from the search results
3. After every cited claim, place the corresponding footnote immediately after the sentence ("The study found X [^1]")
4. End with '#### Sources' and provide definitions EXACTLY in this format: [^n]: [Short Title](URL)

IMPORTANT: Each source definition must follow this exact pattern:
- Start with [^n]: (where n is the citation number)
- Follow with [Title](URL) where Title is SHORT (2-5 words) and wrapped in square brackets
- Example: [^1]: [Paul Graham Essay](https://paulgraham.com/wealth.html)
- DO NOT write long descriptions - keep titles concise`;function $9e(t,e=!0){return e?`

<guidance>
${D9e}

IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.

Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`:`

<guidance>
IMAGE INCLUSION:
When the retrieved documents contain relevant images (in formats like ![alt](image.png) or ![[image.png]]), include them in your response at appropriate locations using their exact original markdown format from the source.

Source Catalog (for reference only):
${t.join(`
`)}
</guidance>`}function F9e(t,e=!0){return e?`

${D9e}

Source Catalog (for reference only):
${t}`:""}function U9e(t){return t?"REMINDER: End your response with an '#### Sources' section listing each cited source as [^n]: [[Title]], numbered sequentially from [^1].":null}var hjt=20;function z8(t,e,n=!0){if(!n||!e?.length||!t)return t||"";if(gjt(t))return t;let r=e.slice(0,hjt).map((o,i)=>{let s=(o.title||o.path||"Untitled").replace(/^\[\[|\]\]$/g,"");return`[^${i+1}]: [[${s}]]`}).join(`
`);return`${t}

#### Sources:

${r}`}function rR(t){if(!t)return"";let e=t.replace(/\[\^\d+\]/g,"");return e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,""),e=e.replace(/^\s*\[\^\d+\]:.*$/gm,""),e}function gjt(t){let e=t||"",n=/(^|\n)\s*#{1,6}\s*Sources\b/i.test(e),r=/(^|\n)\s*Sources\s*(?:[:-]\s*)?(\n|$)/i.test(e),o=/<summary[^>]*>\s*Sources\s*<\/summary>/i.test(e),i=/(^|\n)\s*\[\^\d+\]:\s*/.test(e);return n||r||o||i}function B9e(t){let e=t||"";return/\[\^\d+\]/.test(e)}function z9e(t=!0){return t?`

${mjt}`:""}function yjt(t){let e=/([\s\S]*?)\n+(?:####\s*)?Sources\s*:?\s*\n+([\s\S]*)$/i,n=t.match(e);if(n)return{mainContent:n[1],sourcesBlock:(n[2]||"").trim()};let r=t.match(/([\s\S]*?)\n+---+\s*\n+([\s\S]*)$/);if(r){let i=(r[2]||"").trim();if(i.length>0&&i.split(`
`).every(a=>!a.trim()||/^\[\^\d+\]:/.test(a.trim())))return{mainContent:r[1],sourcesBlock:i}}let o=t.match(/([\s\S]*?)\n{2,}(\[\^\d+\]:[\s\S]*)$/);if(o){let i=(o[2]||"").trim();if(i.split(`
`).every(a=>!a.trim()||/^\[\^\d+\]:/.test(a.trim())))return{mainContent:o[1],sourcesBlock:i}}return null}function wjt(t){return t.includes(`
`)||(t=t.replace(/\s*\[(\d+)\]\s*/g,`
[$1] `),t=t.replace(/\s+(\d+)\.\s/g,`
$1. `),t=t.trim()),t}function vjt(t){return t.split(`
`).map(e=>e.trim()).filter(e=>/^\[\^\d+\]:/.test(e))}function xjt(t,e){let n=new Map,r=new Set,o=[],i=/\[\^(\d+)\]/g,s;for(;(s=i.exec(t))!==null;){let a=parseInt(s[1],10);r.has(a)||(r.add(a),o.push(a))}if(o.length>0)o.forEach((a,l)=>n.set(a,l+1));else{let a=1;for(let l of e){let c=l.match(/^\[\^(\d+)\]:/);if(c){let u=parseInt(c[1],10);n.has(u)||n.set(u,a++)}}}return n}function bjt(t,e){let n=t,r;do r=!1,n=n.replace(/\[\^(\d+)\]/g,(o,i)=>{let s=parseInt(i,10),l=`[${e.get(s)??s}]`;return l!==o&&(r=!0),l}),n=n.replace(/\[\^(\d+(?:\s*,\s*\^?\d+)*)\]/g,(o,i)=>{let a=`[${i.split(",").map(l=>{let c=l.trim().replace(/^\^/,""),u=parseInt(c,10);return e.get(u)??u}).sort((l,c)=>l-c).map(l=>l.toString()).join(", ")}]`;return a!==o&&(r=!0),a});while(r);return n=n.replace(/\[(\d+)\]\./g,"[$1]"),n}function Cjt(t,e){let n=[];return t.split(`
`).forEach(r=>{let o=r.match(/^\[\^(\d+)\]:\s*(.*)$/);if(!o)return;let i=parseInt(o[1],10),s=e.get(i)??i,a=o[2].match(/\[([^\]]+)\]\(([^)]+)\)/),l=o[2].match(/\[\[(.*?)\]\]/),c;if(a)c=`<a href="${a[2]}">${a[1]}</a>`;else if(l)c=`[[${l[1]}]]`;else{let u=o[2].match(/^(.*?)\]\s*\(([^)]+)\)\s*$/);if(u){let d=u[1].trim();c=`<a href="${u[2].trim()}">${d}</a>`}else c=o[2].replace(/\s*\([^)]*\)\s*$/,"")}n[s-1]=c}),n}function _jt(t){let e=[],n=new Set,r=new Map;return t.forEach((o,i)=>{if(!o)return;let s=o.match(/\[\[(.*?)\]\]/),a=s?s[1].toLowerCase():o.toLowerCase();if(!n.has(a))n.add(a),e.push(o),r.set(i+1,e.length);else{let l=e.findIndex(c=>{let u=c.match(/\[\[(.*?)\]\]/);return(u?u[1].toLowerCase():c.toLowerCase())===a});l>=0&&r.set(i+1,l+1)}}),{uniqueItems:e,consolidationMap:r}}function Sjt(t,e){return e.size===0?t:t.replace(/\[(\d+(?:\s*,\s*\d+)*)\]/g,(n,r)=>{let o=r.split(/\s*,\s*/),i=new Set,s=[];for(let a of o){let l=e.get(parseInt(a,10))||parseInt(a,10);i.has(l)||(i.add(l),s.push(l))}return`[${s.join(", ")}]`})}function Tjt(t){let e=t,n;do n=e,e=e.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?:\s*(?:and|,)\s*|\s*)\[(\d+(?:\s*,\s*\d+)*)\]/g,(r,o,i)=>{let s=new Set(o.split(/\s*,\s*/).map(l=>l.trim()));return i.split(/\s*,\s*/).map(l=>l.trim()).every(l=>s.has(l))?`[${[...s].join(", ")}]`:r});while(e!==n);return e}function Ijt(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Pjt(t){return t!=null}function Ejt(t){let e=t.split(`
`),n=[];return e.forEach(r=>{let o=r.trim();if(!o)return;let i=o.replace(/^<li>/i,"").replace(/<\/li>$/i,"").replace(/^[-*]\s*/,"").trim();if(!i)return;let s=i.match(/\[([^\]]+)\]\(([^)]+)\)/),a=i.match(/\[\[(.*?)\]\]/),l;s?l=`<a href="${s[2]}">${s[1]}</a>`:a?l=`[[${a[1]}]]`:l=Ijt(i),n.push({index:n.length+1,html:l})}),n}function L9e(t,e){let n=e.filter(o=>o.html.trim().length>0);if(n.length===0)return t;let r=n.map(({index:o,html:i})=>`<li class="copilot-sources__item"><span class="copilot-sources__index">[${o}]</span><span class="copilot-sources__text">${i}</span></li>`).join(`
`);return`${t}

<br/>
<details class="copilot-sources"><summary class="copilot-sources__summary">Sources</summary>
<ul class="copilot-sources__list">
${r}
</ul>
</details>`}function Ajt(t){return t.replace(/\[(\d+(?:\s*,\s*\d+)*)\](?!\()/g,'<span class="copilot-citation-ref">[$1]</span>')}function j9e(t,e=!0){if(!e)return t;let n=yjt(t);if(!n)return t;let{mainContent:r,sourcesBlock:o}=n;o=wjt(o);let i=vjt(o);if(i.length===0){let d=Ejt(o);return L9e(r,d)}let s=xjt(r,i);r=bjt(r,s);let a=Cjt(o,s),{uniqueItems:l,consolidationMap:c}=_jt(a);c.size>0&&(r=Sjt(r,c),r=Tjt(r),a=l),r=Ajt(r);let u=a.map((d,f)=>d?{index:f+1,html:d}:null).filter(Pjt);return L9e(r,u)}function j8(t){return t.map(e=>{let n=e.title||e.path||"Untitled",r=e.path||n;return`- [[${n}]] (${r})`})}Ir();var pz=class extends $C{async run(e,n,r,o,i){let s=q(),a=Iu(),l=!1;try{l=!$f(a,s.activeModels).capabilities?.includes("reasoning")}catch(p){k("Could not determine model capabilities, defaulting to include thinking blocks",p)}let c=new of(r,l);try{let p=e.contextEnvelope;if(!p)throw new Error("[VaultQA] Context envelope is required but not available. Cannot proceed with VaultQA chain.");let h=p.layers.find(K=>K.id==="L5_USER")?.text||e.message,g=this.extractTagTerms(h);k("[VaultQA] Extracted tags before condensing:",g);let y=this.chainManager.memoryManager.getMemory(),w=await y.loadMemoryVariables({}),v=BW(w),x=h;v.length>0&&(k("[VaultQA] Condensing query with chat history for better retrieval"),x=await AG(h,v),k("[VaultQA] Standalone question:",x));let b=q(),_=g.length>0,S=await new XC(app,{salientTerms:_?[...g]:[],maxK:b.maxSourceChunks,returnAll:_}).getRelevantDocuments(x),P=lh.isMiyoActive(),A=await lh.createRetriever(app,{minSimilarityScore:.01,maxK:b.maxSourceChunks,salientTerms:_?[...g]:[],tagTerms:g,returnAll:_},P?{enableMiyo:!1,enableSemanticSearchV3:!1}:{}),O=A.retriever;k(`VaultQA: Using ${A.type} retriever - ${A.reason}`);let D=await O.getRelevantDocuments(x),{filterResults:$,searchResults:B}=nR(S,D),W=[...$,...B],F=W.length>b.maxSourceChunks,Z=W.slice(0,b.maxSourceChunks);this.chainManager.storeRetrieverDocuments(Z);let V=Z.map(K=>{let Y=K.metadata?.title||"Untitled",re=K.metadata?.path||Y;return`<${nee}>
<title>${Y}</title>
<path>${re}</path>
<content>
${rR(K.pageContent??"")}
</content>
</${nee}>`}).join(`

`),H=[],te=this.chainManager.chatModelManager.getChatModel(),fe=Z.slice(0,Math.max(5,Math.min(20,Z.length))).map(K=>({title:K.metadata?.title||K.metadata?.path||"Untitled",path:K.metadata?.path||K.metadata?.title||""})),me=j8(fe).join(`
`),j=F?`

IMPORTANT: The retrieval limit of ${b.maxSourceChunks} documents was reached. ${W.length-b.maxSourceChunks} additional matching documents were omitted. Inform the user: "Note: The retrieval cap was reached \u2014 some matching documents were not included. Upgrade to Copilot Plus for more complete answers."`:"",G=`

Answer the question based only on the following context:
`+V+F9e(me,b.enableInlineCitations)+j;k("[VaultQA] Using envelope-based context construction with LayerToMessagesConverter");let J=sy.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),M=J.find(K=>K.role==="system");M&&H.push({role:e$(te),content:M.content}),await FC(y,H);let E=J.find(K=>K.role==="user");if(E){let K=G+`

`+E.content;if(e.content&&Array.isArray(e.content)){let Y=e.content.map(re=>re.type==="text"?{...re,text:K}:{...re});H.push({role:"user",content:Y})}else H.push({role:"user",content:K})}let R=te?.modelName;UC({messages:H,modelName:R,contextEnvelope:e.contextEnvelope}),k(`Final Request to AI:
`,H);let L=await Nc(()=>this.chainManager.chatModelManager.getChatModel().stream(H,{signal:n.signal}));for await(let K of L){if(n.signal.aborted){k("VaultQA stream iteration aborted",{reason:n.signal.reason});break}c.processChunk(K)}}catch(p){p.name==="AbortError"||n.signal.aborted?k("VaultQA stream aborted by user",{reason:n.signal.reason}):await this.handleError(p,c.processErrorChunk.bind(c))}let u=c.close(),d={wasTruncated:u.wasTruncated,tokenUsage:u.tokenUsage??void 0};if(n.signal.aborted&&n.signal.reason==="new-chat")return r(""),"";let f=this.addSourcestoResponse(u.content);return await this.handleResponse(f,e,n,o,r,void 0,void 0,d),f}addSourcestoResponse(e){let n=q();if(!B9e(e))return e;let r=this.chainManager.getRetrievedDocuments(),o=RAe(r).map(i=>({title:i}));return z8(e,o,n.enableInlineCitations)}extractTagTerms(e){return uO(e)}};var oR=["@vault","@websearch","@composer","@memory"];It();ye();ns();Se();Se();It();ye();Id();Id();Se();var cf=Jh(),QC=Oo([]),qve=Oo(""),V9e=Oo(!1);function V8(){return Wl(QC,{store:cf})}function W9e(){return Hy(qve,{store:cf})}function iR(){return cf.get(QC)}function nP(){return cf.get(qve)}function W8(t){cf.set(QC,t)}function rP(t){let e=cf.get(QC),n=e.findIndex(r=>r.title===t.title);if(n!==-1){let r=[...e];r[n]=t,cf.set(QC,r)}else cf.set(QC,[...e,t])}function sR(t){let e=cf.get(QC);cf.set(QC,e.filter(n=>n.title!==t))}function e_(t){cf.set(qve,t)}function mz(t){cf.set(V9e,t)}function hz(){return cf.get(V9e)}var Gve=new Set;function t_(t){Gve.add(t)}function n_(t){Gve.delete(t)}function vv(t){return Gve.has(t)}function H8(){return q().defaultSystemPromptTitle}function H9e(){let t=iR(),e=nP();if(e){let r=t.find(o=>o.title===e);if(r)return r.content}let n=H8();if(n){let r=t.find(o=>o.title===n);if(r)return r.content}return""}function K9e(){let t=H8();e_(t)}function Yve(){mz(!1),e_("")}function K8(){return H9e()||q()?.userSystemPrompt||""}function r_(){let t=K8();if(hz())return t;let n=pPe;return t?`${n}
<user_custom_instructions>
${t}
</user_custom_instructions>`:n}async function xv(t){let e=r_();if(!t)return k("No UserMemoryManager provided to getSystemPromptWithMemory"),e;let n=await t.getUserMemoryPrompt();return n?`${n}
${e}`:e}var aR=require("obsidian");Kt();ye();Se();ws();function ch(){}ch.prototype={diff:function(e,n){var r,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},i=o.callback;typeof o=="function"&&(i=o,o={});var s=this;function a(x){return x=s.postProcess(x,o),i?(setTimeout(function(){i(x)},0),!0):x}e=this.castInput(e,o),n=this.castInput(n,o),e=this.removeEmpty(this.tokenize(e,o)),n=this.removeEmpty(this.tokenize(n,o));var l=n.length,c=e.length,u=1,d=l+c;o.maxEditLength!=null&&(d=Math.min(d,o.maxEditLength));var f=(r=o.timeout)!==null&&r!==void 0?r:1/0,p=Date.now()+f,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],n,e,0,o);if(m[0].oldPos+1>=c&&h+1>=l)return a(q9e(s,m[0].lastComponent,n,e,s.useLongestToken));var g=-1/0,y=1/0;function w(){for(var x=Math.max(g,-u);x<=Math.min(y,u);x+=2){var b=void 0,_=m[x-1],T=m[x+1];_&&(m[x-1]=void 0);var S=!1;if(T){var P=T.oldPos-x;S=T&&0<=P&&P<l}var A=_&&_.oldPos+1<c;if(!S&&!A){m[x]=void 0;continue}if(!A||S&&_.oldPos<T.oldPos?b=s.addToPath(T,!0,!1,0,o):b=s.addToPath(_,!1,!0,1,o),h=s.extractCommon(b,n,e,x,o),b.oldPos+1>=c&&h+1>=l)return a(q9e(s,b.lastComponent,n,e,s.useLongestToken));m[x]=b,b.oldPos+1>=c&&(y=Math.min(y,x-1)),h+1>=l&&(g=Math.max(g,x+1))}u++}if(i)(function x(){setTimeout(function(){if(u>d||Date.now()>p)return i();w()||x()},0)})();else for(;u<=d&&Date.now()<=p;){var v=w();if(v)return v}},addToPath:function(e,n,r,o,i){var s=e.lastComponent;return s&&!i.oneChangePerToken&&s.added===n&&s.removed===r?{oldPos:e.oldPos+o,lastComponent:{count:s.count+1,added:n,removed:r,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:n,removed:r,previousComponent:s}}},extractCommon:function(e,n,r,o,i){for(var s=n.length,a=r.length,l=e.oldPos,c=l-o,u=0;c+1<s&&l+1<a&&this.equals(r[l+1],n[c+1],i);)c++,l++,u++,i.oneChangePerToken&&(e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1});return u&&!i.oneChangePerToken&&(e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1}),e.oldPos=l,c},equals:function(e,n,r){return r.comparator?r.comparator(e,n):e===n||r.ignoreCase&&e.toLowerCase()===n.toLowerCase()},removeEmpty:function(e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n},castInput:function(e){return e},tokenize:function(e){return Array.from(e)},join:function(e){return e.join("")},postProcess:function(e){return e}};function q9e(t,e,n,r,o){for(var i=[],s;e;)i.push(e),s=e.previousComponent,delete e.previousComponent,e=s;i.reverse();for(var a=0,l=i.length,c=0,u=0;a<l;a++){var d=i[a];if(d.removed)d.value=t.join(r.slice(u,u+d.count)),u+=d.count;else{if(!d.added&&o){var f=n.slice(c,c+d.count);f=f.map(function(p,m){var h=r[u+m];return h.length>p.length?h:p}),d.value=t.join(f)}else d.value=t.join(n.slice(c,c+d.count));c+=d.count,d.added||(u+=d.count)}}return i}var Iur=new ch;function G9e(t,e){var n;for(n=0;n<t.length&&n<e.length;n++)if(t[n]!=e[n])return t.slice(0,n);return t.slice(0,n)}function Y9e(t,e){var n;if(!t||!e||t[t.length-1]!=e[e.length-1])return"";for(n=0;n<t.length&&n<e.length;n++)if(t[t.length-(n+1)]!=e[e.length-(n+1)])return t.slice(-n);return t.slice(-n)}function Zve(t,e,n){if(t.slice(0,e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't start with prefix ").concat(JSON.stringify(e),"; this is a bug"));return n+t.slice(e.length)}function Jve(t,e,n){if(!e)return t+n;if(t.slice(-e.length)!=e)throw Error("string ".concat(JSON.stringify(t)," doesn't end with suffix ").concat(JSON.stringify(e),"; this is a bug"));return t.slice(0,-e.length)+n}function gz(t,e){return Zve(t,e,"")}function q8(t,e){return Jve(t,e,"")}function Z9e(t,e){return e.slice(0,kjt(t,e))}function kjt(t,e){var n=0;t.length>e.length&&(n=t.length-e.length);var r=e.length;t.length<e.length&&(r=t.length);var o=Array(r),i=0;o[0]=0;for(var s=1;s<r;s++){for(e[s]==e[i]?o[s]=o[i]:o[s]=i;i>0&&e[s]!=e[i];)i=o[i];e[s]==e[i]&&i++}i=0;for(var a=n;a<t.length;a++){for(;i>0&&t[a]!=e[i];)i=o[i];t[a]==e[i]&&i++}return i}var G8="a-zA-Z0-9_\\u{C0}-\\u{FF}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}",Mjt=new RegExp("[".concat(G8,"]+|\\s+|[^").concat(G8,"]"),"ug"),Z8=new ch;Z8.equals=function(t,e,n){return n.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t.trim()===e.trim()};Z8.tokenize=function(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n;if(e.intlSegmenter){if(e.intlSegmenter.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');n=Array.from(e.intlSegmenter.segment(t),function(i){return i.segment})}else n=t.match(Mjt)||[];var r=[],o=null;return n.forEach(function(i){/\s/.test(i)?o==null?r.push(i):r.push(r.pop()+i):/\s/.test(o)?r[r.length-1]==o?r.push(r.pop()+i):r.push(o+i):r.push(i),o=i}),r};Z8.join=function(t){return t.map(function(e,n){return n==0?e:e.replace(/^\s+/,"")}).join("")};Z8.postProcess=function(t,e){if(!t||e.oneChangePerToken)return t;var n=null,r=null,o=null;return t.forEach(function(i){i.added?r=i:i.removed?o=i:((r||o)&&J9e(n,o,r,i),n=i,r=null,o=null)}),(r||o)&&J9e(n,o,r,null),t};function J9e(t,e,n,r){if(e&&n){var o=e.value.match(/^\s*/)[0],i=e.value.match(/\s*$/)[0],s=n.value.match(/^\s*/)[0],a=n.value.match(/\s*$/)[0];if(t){var l=G9e(o,s);t.value=Jve(t.value,s,l),e.value=gz(e.value,l),n.value=gz(n.value,l)}if(r){var c=Y9e(i,a);r.value=Zve(r.value,a,c),e.value=q8(e.value,c),n.value=q8(n.value,c)}}else if(n)t&&(n.value=n.value.replace(/^\s*/,"")),r&&(r.value=r.value.replace(/^\s*/,""));else if(t&&r){var u=r.value.match(/^\s*/)[0],d=e.value.match(/^\s*/)[0],f=e.value.match(/\s*$/)[0],p=G9e(u,d);e.value=gz(e.value,p);var m=Y9e(gz(u,p),f);e.value=q8(e.value,m),r.value=Zve(r.value,u,m),t.value=Jve(t.value,u,u.slice(0,u.length-m.length))}else if(r){var h=r.value.match(/^\s*/)[0],g=e.value.match(/\s*$/)[0],y=Z9e(g,h);e.value=q8(e.value,y)}else if(t){var w=t.value.match(/\s*$/)[0],v=e.value.match(/^\s*/)[0],x=Z9e(w,v);e.value=gz(e.value,x)}}var Njt=new ch;Njt.tokenize=function(t){var e=new RegExp("(\\r?\\n)|[".concat(G8,"]+|[^\\S\\n\\r]+|[^").concat(G8,"]"),"ug");return t.match(e)||[]};function Ojt(t,e){if(typeof t=="function")e.callback=t;else if(t)for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}var J8=new ch;J8.tokenize=function(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,`
`));var n=[],r=t.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(var o=0;o<r.length;o++){var i=r[o];o%2&&!e.newlineIsToken?n[n.length-1]+=i:n.push(i)}return n};J8.equals=function(t,e,n){return n.ignoreWhitespace?((!n.newlineIsToken||!t.includes(`
`))&&(t=t.trim()),(!n.newlineIsToken||!e.includes(`
`))&&(e=e.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(t.endsWith(`
`)&&(t=t.slice(0,-1)),e.endsWith(`
`)&&(e=e.slice(0,-1))),ch.prototype.equals.call(this,t,e,n)};function X9e(t,e,n){var r=Ojt(n,{ignoreWhitespace:!0});return J8.diff(t,e,r)}var Rjt=new ch;Rjt.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var Ljt=new ch;Ljt.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function Xve(t){"@babel/helpers - typeof";return Xve=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Xve(t)}var yz=new ch;yz.useLongestToken=!0;yz.tokenize=J8.tokenize;yz.castInput=function(t,e){var n=e.undefinedReplacement,r=e.stringifyReplacer,o=r===void 0?function(i,s){return typeof s>"u"?n:s}:r;return typeof t=="string"?t:JSON.stringify(Qve(t,null,null,o),o,"  ")};yz.equals=function(t,e,n){return ch.prototype.equals.call(yz,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"),n)};function Qve(t,e,n,r,o){e=e||[],n=n||[],r&&(t=r(o,t));var i;for(i=0;i<e.length;i+=1)if(e[i]===t)return n[i];var s;if(Object.prototype.toString.call(t)==="[object Array]"){for(e.push(t),s=new Array(t.length),n.push(s),i=0;i<t.length;i+=1)s[i]=Qve(t[i],e,n,r,o);return e.pop(),n.pop(),s}if(t&&t.toJSON&&(t=t.toJSON()),Xve(t)==="object"&&t!==null){e.push(t),s={},n.push(s);var a=[],l;for(l in t)Object.prototype.hasOwnProperty.call(t,l)&&a.push(l);for(a.sort(),i=0;i<a.length;i+=1)l=a[i],s[l]=Qve(t[l],e,n,r,l);e.pop(),n.pop()}else s=t;return s}var Y8=new ch;Y8.tokenize=function(t){return t.slice()};Y8.join=Y8.removeEmpty=function(t){return t};function Q9e(t,e,n){return Y8.diff(t,e,n)}vt();var bv=require("obsidian"),Xe=N(U());rn();var wz=N(U());Kt();var uh=wz.forwardRef(({checked:t=!1,onCheckedChange:e,disabled:n=!1,className:r,...o},i)=>{let s=()=>{n||e?.(!t)},a=l=>{n||(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),e?.(!t))};return wz.createElement("div",{role:"switch","aria-checked":t,"aria-disabled":n,"data-state":t?"checked":"unchecked","data-disabled":n?"":void 0,ref:i,tabIndex:n?-1:0,className:oe("tw-relative tw-inline-flex tw-h-5.5 tw-w-10 tw-shrink-0 tw-cursor-pointer tw-items-center tw-rounded-full tw-transition-colors","focus-visible:tw-outline-none focus-visible:tw-ring-2 focus-visible:tw-ring-ring focus-visible:tw-ring-offset-2",t?"tw-bg-interactive-accent":"tw-bg-[--background-modifier-border-hover]",n&&"tw-cursor-not-allowed tw-opacity-50",r),onClick:s,onKeyDown:a,...o},wz.createElement("div",{className:oe("tw-pointer-events-none tw-block tw-size-4 tw-rounded-full tw-bg-toggle-thumb tw-shadow-lg tw-ring-0 tw-transition-transform",t?"tw-translate-x-5.5":"tw-translate-x-0.5")}))});uh.displayName="SettingSwitch";function eYe(t){let e=[],n=[];return t.forEach(r=>{r.added||r.removed?n.push(r):(n.length>0&&(e.push(n),n=[]),e.push([r]))}),n.length>0&&e.push(n),e}qe();function Djt(t,e){let n=o=>o.split(/(\s+)/).filter(Boolean);return Q9e(n(t),n(e)).map(o=>({value:o.value.join(""),added:o.added,removed:o.removed}))}function vz(t){let e=t.split(`
`);return e.length>0&&e[e.length-1]===""&&e.pop(),e}function tYe(t){let e=[],n=0;for(;n<t.length;){let r=t[n];if(!r.added&&!r.removed)vz(r.value).forEach(o=>{e.push({original:o,modified:o,isUnchanged:!0})}),n++;else if(r.removed){let o=t[n+1];if(o?.added){let i=vz(r.value),s=vz(o.value),a=Math.max(i.length,s.length);for(let l=0;l<a;l++)e.push({original:i[l]??null,modified:s[l]??null,isUnchanged:!1});n+=2}else vz(r.value).forEach(i=>{e.push({original:i,modified:null,isUnchanged:!1})}),n++}else r.added&&vz(r.value).forEach(o=>{e.push({original:null,modified:o,isUnchanged:!1})}),n++}return e}var nYe=(0,Xe.memo)(({original:t,modified:e,side:n})=>{let r=Djt(t,e);return Xe.default.createElement("span",null,r.map((o,i)=>{if(n==="original"){if(o.removed)return Xe.default.createElement("span",{key:i,className:"tw-bg-error tw-text-error"},o.value);if(o.added)return null}else{if(o.added)return Xe.default.createElement("span",{key:i,className:"tw-bg-success tw-text-success"},o.value);if(o.removed)return null}return Xe.default.createElement("span",{key:i},o.value)}))});nYe.displayName="WordDiffSpan";var xz=(0,Xe.memo)(({row:t,side:e})=>{let n=e==="original"?t.original:t.modified,r=e==="original"?t.modified:t.original;return n===null?Xe.default.createElement("span",{className:"tw-text-muted"},"\xA0"):t.isUnchanged?Xe.default.createElement("span",{className:"tw-text-normal"},n||"\xA0"):r!==null?Xe.default.createElement(nYe,{original:t.original,modified:t.modified,side:e}):Xe.default.createElement("span",{className:e==="original"?"tw-bg-error tw-text-error":"tw-bg-success tw-text-success"},n||"\xA0")});xz.displayName="DiffCell";var bz="obsidian-copilot-apply-view",X8=class extends bv.ItemView{constructor(n){super(n);this.root=null;this.state=null;this.result=null}getViewType(){return bz}getDisplayText(){return"Preview Changes"}async setState(n){this.state=n,this.render()}async onOpen(){this.render()}async onClose(){this.root&&(this.root.unmount(),this.root=null),this.state?.resultCallback?.(this.result?this.result:"aborted")}render(){if(!this.state)return;let n=this.containerEl.children[1];n.empty();let r=n.createDiv();this.root||(this.root=sr(r,this.app)),this.root.render(Xe.default.createElement($jt,{app:this.app,state:this.state,close:o=>{this.result=o,this.leaf.detach()}}))}},rYe=(0,Xe.memo)(({block:t})=>{let e=(0,Xe.useMemo)(()=>tYe(t),[t]);return Xe.default.createElement("div",{className:"tw-grid tw-grid-cols-2 tw-gap-2"},Xe.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((n,r)=>Xe.default.createElement("div",{key:r,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Xe.default.createElement(xz,{row:n,side:"original"})))),Xe.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},e.map((n,r)=>Xe.default.createElement("div",{key:r,className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},Xe.default.createElement(xz,{row:n,side:"modified"})))))});rYe.displayName="SideBySideBlock";var oYe=(0,Xe.memo)(({block:t})=>{let e=t.some(r=>r.added||r.removed),n=(0,Xe.useMemo)(()=>tYe(t),[t]);return e?Xe.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Xe.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Xe.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Original"),Xe.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},n.map((r,o)=>r.original!==null?Xe.default.createElement("div",{key:o},Xe.default.createElement(xz,{row:r,side:"original"})):null))),Xe.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-2"},Xe.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-font-medium tw-text-muted"},"Modified"),Xe.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-font-mono tw-text-sm"},n.map((r,o)=>r.modified!==null?Xe.default.createElement("div",{key:o},Xe.default.createElement(xz,{row:r,side:"modified"})):null)))):Xe.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},t.map((r,o)=>Xe.default.createElement("span",{key:o},r.value)))});oYe.displayName="SplitBlock";var $jt=({app:t,state:e,close:n})=>{let r=e.simple??!1,[o,i]=(0,Xe.useState)(()=>e.changes.map(w=>({...w,accepted:null}))),[s,a]=(0,Xe.useState)(()=>q().diffViewMode??"split"),l=w=>{a(w),pe("diffViewMode",w)},c=eYe(o),u=(0,Xe.useRef)([]);if(!e||!e.changes)return z("Invalid state:",e),Xe.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col tw-items-center tw-justify-center"},Xe.default.createElement("div",{className:"tw-text-error"},"Error: Invalid state - missing changes"),Xe.default.createElement(X,{onClick:()=>n("failed"),className:"tw-mt-4"},"Close"));let d=async()=>{try{let w=o.map(x=>x.accepted===null?{...x,accepted:!0}:x),v=await m(w);n(v?"accepted":"failed")}catch(w){z("Error applying changes:",w),new bv.Notice(`Error applying changes: ${w instanceof Error?w.message:String(w)}`),n("failed")}},f=async()=>{try{let w=o.map(x=>x.accepted===null?{...x,accepted:!1}:x),v=await m(w,!1);n(v?"rejected":"failed")}catch(w){z("Error applying changes:",w),new bv.Notice(`Error applying changes: ${w instanceof Error?w.message:String(w)}`),n("failed")}},p=async w=>{let v=t.vault.getAbstractFileByPath(w);if(v)return v;if(w.includes("/")){let x=w.split("/").slice(0,-1).join("/");await Fr(x)}return await t.vault.create(w,"")},m=async(w,v=!0)=>{let x=w.filter(_=>_.added?_.accepted===!0:_.removed?_.accepted===!1:!0).map(_=>_.value).join(""),b=await p(e.path);return!b||!(b instanceof bv.TFile)?(z("Error in getting file",e.path),new bv.Notice("Failed to create file"),!1):(await t.vault.modify(b,x),v&&new bv.Notice("Changes applied successfully"),!0)},h=w=>{if(!c)return;let v=-1;for(let x=w+1;x<c.length;x++){let b=c[x],_=b.some(S=>S.added||S.removed),T=b.some(S=>(S.added||S.removed)&&S.accepted===null);if(_&&T){v=x;break}}v!==-1&&u.current[v]&&u.current[v]?.scrollIntoView({behavior:"smooth",block:"center"})},g=w=>{i(v=>{let x=[...v],b=c?.[w];return b&&b.forEach(_=>{let T=x.findIndex(S=>S===_);T!==-1&&(x[T]={...x[T],accepted:!0})}),x}),window.setTimeout(()=>h(w),0)},y=w=>{i(v=>{let x=[...v],b=c?.[w];return b&&b.forEach(_=>{let T=x.findIndex(S=>S===_);T!==-1&&(x[T]={...x[T],accepted:!1})}),x}),window.setTimeout(()=>h(w),0)};return Xe.default.createElement("div",{className:"tw-relative tw-flex tw-h-full tw-flex-col"},Xe.default.createElement("div",{className:"tw-fixed tw-bottom-4 tw-left-1/2 tw-z-[9999] tw-flex tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary tw-p-2 tw-shadow-lg"},Xe.default.createElement(X,{variant:"destructive",size:"sm",onClick:f},Xe.default.createElement(Sn,{className:"tw-size-4"}),"Reject"),Xe.default.createElement(X,{variant:"success",size:"sm",onClick:d},Xe.default.createElement(Ro,{className:"tw-size-4"}),"Accept")),Xe.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-border-b tw-border-solid tw-border-border tw-p-2"},Xe.default.createElement("div",{className:"tw-text-sm tw-font-medium"},e.path),Xe.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Xe.default.createElement("span",{className:oe("tw-text-xs",s==="split"?"tw-font-medium tw-text-normal":"tw-text-muted")},"Split"),Xe.default.createElement(uh,{checked:s==="side-by-side",onCheckedChange:w=>l(w?"side-by-side":"split")}),Xe.default.createElement("span",{className:oe("tw-text-xs",s==="side-by-side"?"tw-font-medium tw-text-normal":"tw-text-muted")},"Side-by-side"))),Xe.default.createElement("div",{className:"tw-flex-1 tw-overflow-auto tw-p-2"},c?.map((w,v)=>{let x=w.some(_=>_.added||_.removed),b=x?w.every(_=>!_.added&&!_.removed||_.accepted===!0)?"accepted":w.every(_=>!_.added&&!_.removed||_.accepted===!1)?"rejected":"undecided":"unchanged";return Xe.default.createElement("div",{key:v,ref:_=>u.current[v]=_,className:oe("tw-mb-4 tw-overflow-hidden tw-rounded-md")},b==="accepted"?Xe.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},w.filter(_=>!_.removed).map((_,T)=>Xe.default.createElement("div",{key:T},_.value))):b==="rejected"?Xe.default.createElement("div",{className:"tw-flex-1 tw-whitespace-pre-wrap tw-px-2 tw-py-1 tw-font-mono tw-text-sm tw-text-normal"},w.filter(_=>!_.added).map((_,T)=>Xe.default.createElement("div",{key:T},_.value))):s==="side-by-side"?Xe.default.createElement(rYe,{block:w}):Xe.default.createElement(oYe,{block:w}),!r&&x&&b==="undecided"&&Xe.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-end tw-border-[0px] tw-border-t tw-border-solid tw-border-border tw-p-2"},Xe.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Xe.default.createElement(X,{variant:"destructive",size:"sm",onClick:()=>y(v)},Xe.default.createElement(Sn,{className:"tw-size-4"}),"Reject"),Xe.default.createElement(X,{variant:"success",size:"sm",onClick:()=>g(v)},Xe.default.createElement(Ro,{className:"tw-size-4"}),"Accept"))),!r&&x&&(b==="accepted"||b==="rejected")&&Xe.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-end tw-border-[0px] tw-border-t tw-border-solid tw-border-border tw-p-2"},Xe.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Xe.default.createElement("div",{className:"tw-mr-2 tw-text-sm tw-font-medium"},b==="accepted"?Xe.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-text-success"},Xe.default.createElement(Ro,{className:"tw-size-4"}),Xe.default.createElement("div",null,"Accepted")):Xe.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-text-error"},Xe.default.createElement(Sn,{className:"tw-size-4"}),Xe.default.createElement("div",null,"Rejected"))),Xe.default.createElement(X,{variant:"secondary",size:"sm",onClick:()=>{i(_=>{let T=[..._],S=c?.[v];return S&&S.forEach(P=>{let A=T.findIndex(O=>O===P);A!==-1&&(T[A]={...T[A],accepted:null})}),T})}},"Revert"))))})))};h2();h2();gp();function Rr(t){return Gg(async e=>{let n=await t.func(e);return typeof n=="string"?n:JSON.stringify(n)},{name:t.name,description:t.description,schema:t.schema})}qe();Se();ye();async function sYe(t){let e=app.vault.getAbstractFileByPath(t);if(e&&e instanceof aR.TFile)return e;if(e&&!(e instanceof aR.TFile))throw new Error(`Path "${t}" exists but is not a file`);try{let n=t.includes("/")?t.split("/").slice(0,-1).join("/"):"";if(n&&await Fr(n),e=app.vault.getAbstractFileByPath(t),e&&e instanceof aR.TFile)return e;if(e=await app.vault.create(t,""),!(e instanceof aR.TFile))throw new Error(`Failed to create file: unexpected type returned for "${t}"`);return e}catch(n){let r=n instanceof Error?n.message:String(n);throw new Error(`Failed to get or create file "${t}": ${r}`)}}async function aYe(t,e,n=!1){let r=await sYe(t),o=app.workspace.getActiveFile();r&&(!o||o.path!==t)&&await app.workspace.getLeaf().openFile(r);let i="";r&&(i=await app.vault.read(r));let s=X9e(i,e,{newlineIsToken:!0});return new Promise(a=>{app.workspace.getLeaf(!0).setViewState({type:bz,active:!0,state:{changes:s,path:t,simple:n,resultCallback:c=>{a(c)}}})})}var Fjt=we.object({path:we.string().describe(`(Required) The path to the file to write to. 
          The path must end with explicit file extension, such as .md or .canvas .
          Prefer to create new files in existing folders or root folder unless the user's request specifies otherwise.
          The path must be relative to the root of the vault.`),content:we.union([we.string(),we.object({}).passthrough()]).describe(`(Required) The content to write to the file. Can be either a string or an object.
          ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. 
          You MUST include ALL parts of the file, even if they haven't been modified.

          # For string content
          * Use when writing text files like .md, .txt, etc.
          
          # For object content  
          * Use when writing structured data files like .json, .canvas, etc.
          * The object will be automatically converted to JSON string format
          
          # Canvas JSON Format (JSON Canvas spec 1.0)
          Required node fields: id, type, x, y, width, height
          Node types: "text" (needs text), "file" (needs file), "link" (needs url), "group" (optional label)
          Optional node fields: color (hex #FF0000 or preset "1"-"6"), subpath (file nodes, starts with #)
          Required edge fields: id, fromNode, toNode
          Optional edge fields: fromSide/toSide ("top"/"right"/"bottom"/"left"), fromEnd/toEnd ("none"/"arrow"), color, label
          All IDs must be unique. Edge nodes must reference existing node IDs.
          
          Example:
          {
            "nodes": [
              {"id": "1", "type": "text", "text": "Hello", "x": 0, "y": 0, "width": 200, "height": 50},
              {"id": "2", "type": "file", "file": "note.md", "subpath": "#heading", "x": 250, "y": 0, "width": 200, "height": 100, "color": "2"},
              {"id": "3", "type": "group", "label": "Group", "x": 0, "y": 100, "width": 300, "height": 150}
            ],
            "edges": [
              {"id": "e1-2", "fromNode": "1", "toNode": "2", "fromSide": "right", "toSide": "left", "color": "3", "label": "links to"}
            ]
          }`),confirmation:we.preprocess(t=>{if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t},we.boolean()).optional().default(!0).describe("(Optional) Hint for confirmation preference. Note: preview is always shown unless the user has enabled auto-accept in settings.")}),t9=Rr({name:"writeFile",description:`Request to write content to a file at the specified path and show the changes in a Change Preview UI.

      # Steps to find the the target path
      1. Extract the target file information from user message and find out the file path from the context.
      2. If target file is not specified, use the active note as the target file.
      3. If still failed to find the target file or the file path, ask the user to specify the target file.
      `,schema:Fjt,func:async({path:t,content:e,confirmation:n=!0})=>{let r=Vte(t);r!==t&&(ee(`Filename too long, truncated for filesystem compatibility: "${t}" \u2192 "${r}"`),t=r);let o=typeof e=="string"?e:JSON.stringify(e,null,2);if(q().autoAcceptEdits)try{let l=await sYe(t);return await app.vault.modify(l,o),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."}}catch(l){return{result:"failed",message:`Error writing to file without preview: ${l instanceof Error?l.message:String(l)}`}}let a=await aYe(t,o);return{result:a,message:`File change result: ${a}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}}),Ujt=we.object({path:we.string().describe("(Required) The path of the file to modify (relative to the root of the vault and include the file extension)."),oldText:we.string().describe(`(Required) The exact text to find and replace. Must match the file content exactly, including whitespace and indentation.
Fuzzy matching handles minor differences like trailing spaces or smart quotes, but the overall structure must be correct.
To make the match unique, include enough surrounding context lines (not just the changed line).`),newText:we.string().describe("(Required) The new text to replace the old text with. Can be empty string to delete the old text.")});function exe(t){return t.replace(/\r\n/g,`
`).replace(/\r/g,`
`)}function e9(t){return t.normalize("NFKC").split(`
`).map(e=>e.trimEnd()).join(`
`).replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"').replace(/[\u2010-\u2015\u2212]/g,"-").replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g," ")}function Q8(t,e){if(!e)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=1;return n}function Bjt(t){return t.charCodeAt(0)===65279?{content:t.slice(1),hasBOM:!0}:{content:t,hasBOM:!1}}function zjt(t,e,n){let r=Q8(t,e);if(r>0)return{found:!0,occurrences:r,workingContent:t,workingSearch:e,workingReplace:n,usedFuzzyMatch:!1};let o=e9(t),i=e9(e),s=Q8(o,i);if(s>0)return{found:!0,occurrences:s,workingContent:o,workingSearch:i,workingReplace:n,usedFuzzyMatch:!0};if(e.endsWith(`
`)){let a=e.slice(0,-1),l=n.endsWith(`
`)?n.slice(0,-1):n,c=Q8(t,a);if(c>0)return{found:!0,occurrences:c,workingContent:t,workingSearch:a,workingReplace:l,usedFuzzyMatch:!1};let u=e9(a),d=Q8(o,u);if(d>0)return{found:!0,occurrences:d,workingContent:o,workingSearch:u,workingReplace:l,usedFuzzyMatch:!0}}return{found:!1,occurrences:0,workingContent:o,workingSearch:i,workingReplace:n,usedFuzzyMatch:!0}}function iYe(t,e,n){let r=n,o=0;for(let i=0;i<e.length;i++){let s=e[i].length,a=t[i]??"",l=a.length;if(r<=s){if(r===s)return o+l;let c=0,u=0;for(;u<a.length&&c<r;){let d=a[u].normalize("NFKC").length;if(c+d>r)break;c+=d,u++}return o+u}r-=s+1,o+=l+1}return o}function jjt(t,e,n){let{content:r,hasBOM:o}=Bjt(t),i=(r.match(/\r\n/g)||[]).length,s=(r.match(/(?<!\r)\n/g)||[]).length,a=i>s,l=exe(r),c=exe(e),u=exe(n),d=zjt(l,c,u);if(!d.found)return{ok:!1,reason:"NOT_FOUND"};if(d.occurrences>1)return{ok:!1,reason:"AMBIGUOUS",occurrences:d.occurrences};let f,p;if(d.usedFuzzyMatch){let h=l.split(`
`),g=d.workingContent.split(`
`),y=d.workingContent.indexOf(d.workingSearch);if(f=iYe(h,g,y),p=iYe(h,g,y+d.workingSearch.length),f>=p)return{ok:!1,reason:"NOT_FOUND"};if(e9(l.substring(f,p))!==d.workingSearch)return{ok:!1,reason:"NOT_FOUND"}}else f=l.indexOf(d.workingSearch),p=f+d.workingSearch.length;let m=l.substring(0,f)+d.workingReplace+l.substring(p);return a&&(m=m.replace(/\n/g,`\r
`)),o&&(m="\uFEFF"+m),{ok:!0,content:m}}var lYe=Rr({name:"editFile",description:"Request to make a targeted change to an existing file by specifying the exact text to find and its replacement. Use this tool for precise, surgical edits to specific parts of a file.",schema:Ujt,func:async({path:t,oldText:e,newText:n})=>{let r=Vte(t),o=app.vault.getAbstractFileByPath(r);if(!o||!(o instanceof aR.TFile))return{result:"failed",message:`File not found at path: ${r}. Please check the file path and try again.`};try{let i=await app.vault.read(o),s=jjt(i,e,n);if(!s.ok)return s.reason==="NOT_FOUND"?{result:"failed",message:`Could not find the specified text in ${r}. The oldText must match the file content \u2014 try including more surrounding context lines to locate the right spot.`}:{result:"failed",message:`Found ${s.occurrences} occurrences of the search text in ${r}. The text must be unique \u2014 add more surrounding context to make it unambiguous.`};let a=s.content;if(i===a)return{result:"accepted",message:`No changes made to ${r}. The replacement produced identical content. Use writeFile if the file needs a broader rewrite.`};if(q().autoAcceptEdits)return await app.vault.modify(o,a),{result:"accepted",message:"File changes applied without preview. Do not retry or attempt alternative approaches to modify this file in response to the current user request."};let c=await aYe(r,a,!0);return{result:c,message:`File change result: ${c}. Do not retry or attempt alternative approaches to modify this file in response to the current user request.`}}catch(i){return{result:"failed",message:`Error modifying ${r}: ${i}. Please check the file path and try again.`}}}});ye();var txe=t=>{switch(t){case"@vault":return"Search through your vault for relevant information";case"@websearch":return"Search the web for information";case"@composer":return"Edit existing notes or create new notes.";case"@memory":return"Save information to user memory";default:return""}},Cv=class{static async callTool(e,n){if(!e)throw new Error("Tool is undefined");let r=e,o=await r.call(n);return o??(ee(`[ToolCall] Tool "${r.name}" returned null/undefined`),null)}};function cYe(t){let e=t.trim();if(!e)return"note";let n=e.match(/^\[\[([\s\S]+?)\]\]$/),r=n?n[1]:e,[o="",i=""]=r.split("|"),s=i.trim();if(s.length>0)return s;let a=o.trim(),[l]=a.split("#"),c=(l||a).trim()||e,u=c.split("/").filter(Boolean),d=u.length>0?u[u.length-1]:c;return d.replace(/\.[^/.]+$/,"")||d||"note"}var uYe=180;function Vjt(t){let e=t.trim();return e.length<=uYe?e:`${e.slice(0,uYe)}\u2026`}function Wjt(t){if(!t||typeof t!="object")return null;let e=t,n=typeof e.status=="string"?e.status:null,r=typeof e.message=="string"&&e.message.trim().length>0?Vjt(e.message):null,o=typeof e.notePath=="string"?e.notePath:"",s=(typeof e.noteTitle=="string"&&e.noteTitle.trim().length>0?e.noteTitle.trim():cYe(o))||cYe(o);if(n==="invalid_path")return r??`\u26A0\uFE0F Invalid note path "${s}"`;if(n==="not_found")return r??`\u26A0\uFE0F Note "${s}" not found`;if(n==="not_unique"){let d=Array.isArray(e.candidates)?e.candidates.length:0;return r||(d>0?`\u26A0\uFE0F Multiple matches for "${s}" (${d} candidates)`:`\u26A0\uFE0F Multiple matches for "${s}"`)}if(n==="empty")return r??`\u26A0\uFE0F "${s}" contains no readable content`;if(n==="out_of_range"){if(r)return r;let d=typeof e.totalChunks=="number"&&Number.isFinite(e.totalChunks)?e.totalChunks:null,f=typeof e.chunkIndex=="number"&&Number.isFinite(e.chunkIndex)?e.chunkIndex:null;if(f!==null&&d!==null){let p=Math.max(d-1,0);return`\u26A0\uFE0F Chunk ${f} exceeds available range (max index ${p})`}return"\u26A0\uFE0F Requested chunk is out of range"}let a=typeof e.chunkIndex=="number"&&Number.isFinite(e.chunkIndex)?e.chunkIndex:0,l=typeof e.totalChunks=="number"&&Number.isFinite(e.totalChunks)?e.totalChunks:null,c=!!e.hasMore,u=[`\u2705 Read "${s||"note"}"`];return l&&l>0?u.push(`chunk ${a+1} of ${l}`):u.push(`chunk ${a+1}`),c&&u.push("more available"),u.join(" \xB7 ")}var _v=class{static format(e,n){try{let r=n;if(typeof r=="string"&&r.startsWith("ENC:"))try{r=decodeURIComponent(r.slice(4))}catch{}let o;try{o=JSON.parse(r)}catch{o=r}switch(e){case"localSearch":return this.formatLocalSearch(o);case"webSearch":return this.formatWebSearch(o);case"youtubeTranscription":return this.formatYoutubeTranscription(o);case"writeFile":return this.formatWriteToFile(o);case"editFile":return this.formatReplaceInFile(o);case"readNote":return this.formatReadNote(o);default:return n}}catch{return n}}static formatLocalSearchDocuments(e){if(!Array.isArray(e)||e.length===0)return`\u{1F4DA} Found 0 relevant notes

No matching notes found.`;let n=e.length,r=e.slice(0,10),o=r.some(a=>{let l=a;return typeof l?.rerank_score=="number"||typeof l?.score=="number"||l?.source}),i=r.map((a,l)=>o?this.formatSearchItem(a,l):this.formatBasicSearchItem(a,l)).join(`

`),s=n>10?`

... and ${n-10} more results`:"";return`\u{1F4DA} Found ${n} relevant notes

Top results:

${i}${s}`}static formatLocalSearch(e){if(typeof e=="string"){let r=e.match(/<localSearch[^>]*>([\s\S]*)<\/localSearch>/);if(r){let o=r[1].trim(),i=o.match(/<document>/g);if((i?i.length:0)===0)return`\u{1F4DA} Found 0 relevant notes

No matching notes found.`;let a=[],l=/<document>([\s\S]*?)<\/document>/g,c;for(;(c=l.exec(o))!==null;){let u=c[1],d=u.match(/<title>([\s\S]*?)<\/title>/),f=u.match(/<path>([\s\S]*?)<\/path>/),p=u.match(/<modified>([\s\S]*?)<\/modified>/),m=(d?.[1]||"Untitled").trim(),h=(f?.[1]||"").trim(),g=(p?.[1]||"").trim();a.push({title:m,path:h,mtime:g||null})}return this.formatLocalSearchDocuments(a)}}let n=this.parseSearchResults(e);return Array.isArray(n)?n.length===0?typeof e=="string"&&!e.includes("<localSearch")&&!e.includes('"type":"local_search"')?e:`\u{1F4DA} Found 0 relevant notes

No matching notes found.`:this.formatLocalSearchDocuments(n):typeof e=="string"?e:JSON.stringify(e,null,2)}static parseSearchResults(e){if(typeof e=="object"&&e!==null){let n=e;return n.type==="local_search"&&Array.isArray(n.documents)?n.documents:[]}if(typeof e=="string"){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&n.type==="local_search"&&Array.isArray(n.documents))return n.documents}catch{}return[]}return[]}static formatSearchItem(e,n){let r=e,o=typeof r.path=="string"?r.path:"",i=typeof r.title=="string"?r.title:"",s=o?o.split("/").pop()?.replace(/\.md$/,"")||i||"Untitled":i||"Untitled",a=r.rerank_score||r.score||0,l=typeof a=="number"?a.toFixed(4):a,c=r.source==="time-filtered"?"Recency":"Relevance",u=[`${n+1}. ${s}`];if(r.source==="time-filtered"){if(r.mtime)try{let f=r.mtime,p=new Date(f),m=isNaN(p.getTime())?typeof f=="string"||typeof f=="number"?String(f):"":p.toISOString();u.push(`   \u{1F552} Modified: ${m}${r.includeInContext?" \u2713":""}`)}catch{let f=typeof r.mtime=="string"||typeof r.mtime=="number"?String(r.mtime):"";u.push(`   \u{1F552} Modified: ${f}${r.includeInContext?" \u2713":""}`)}}else r.source==="title-match"?u.push(`   \u{1F516} Title match${r.includeInContext?" \u2713":""}`):u.push(`   \u{1F4CA} ${c}: ${l}${r.includeInContext?" \u2713":""}`);let d=this.extractContentSnippet(r.content);if(d){let f=typeof r.content=="string"?r.content.length:0;u.push(`   \u{1F4AC} "${d}${f>150?"...":""}"`)}return o&&!o.endsWith(`/${s}.md`)&&u.push(`   \u{1F4C1} ${o}`),u.join(`
`)}static formatBasicSearchItem(e,n){let r=e,o=r.title||r.path||`Result ${n+1}`,i=[`${n+1}. ${o}`],s=r.mtime||r.modified||r.modified_at||r.updated_at;if(s){let a=typeof s=="string"||typeof s=="number"?String(s):"";a&&i.push(`   \u{1F552} Modified: ${a}`)}return typeof r.path=="string"&&r.path&&r.path!==o&&i.push(`   \u{1F4C1} ${r.path}`),i.join(`
`)}static extractContentSnippet(e,n=150){return e?(e.match(/NOTE BLOCK CONTENT:\s*([\s\S]*)/)?.[1]||e).substring(0,n).replace(/\s+/g," ").trim():""}static formatWebSearch(e){let n=Array.isArray(e)&&e.length>0?e[0]:null;if(n&&n.type==="web_search"){let r=["\u{1F310} Web Search Results"];n.content&&(r.push(""),r.push(typeof n.content=="string"?n.content:""));let o=Array.isArray(n.citations)?n.citations:[];return o.length>0&&(r.push(""),r.push("Sources:"),o.forEach((i,s)=>{r.push(`[${s+1}] ${String(i)}`)})),n.instruction&&(r.push(""),r.push(`Note: ${typeof n.instruction=="string"?n.instruction:""}`)),r.join(`
`)}if(typeof e=="string"){let r=e.split(`
`),o=["\u{1F310} Web Search Results"],i=!1,s=[],a=[];for(let l of r){if(l.includes("Sources:")){i=!0;continue}i?a.push(l):l.includes("Here are the web search results")||s.push(l)}return s.length>0&&(o.push(""),o.push(...s.filter(l=>l.trim()))),a.length>0&&(o.push(""),o.push("Sources:"),a.forEach(l=>{l.trim()&&o.push(l)})),o.join(`
`)}return typeof e=="string"?e:""}static formatYoutubeTranscription(e){let n;if(typeof e=="string")try{n=JSON.parse(e)}catch{return e}else if(typeof e=="object")n=e;else return typeof e=="number"||typeof e=="boolean"?String(e):"";let r=typeof n=="object"&&n!==null?n:null;if(!r)return typeof e=="object"?JSON.stringify(e,null,2):"";if(r.success===!1)return`\u{1F4FA} YouTube Transcription Failed

${typeof r.message=="string"?r.message:""}`;if(r.results&&Array.isArray(r.results)){let o=typeof r.total_urls=="number"?r.total_urls:r.results.length,i=[`\u{1F4FA} YouTube Transcripts (${o} video${o>1?"s":""})`];i.push("");for(let s of r.results){let a=typeof s=="object"&&s!==null?s:null;if(a){if(a.success){i.push(`\u{1F4F9} Video: ${typeof a.url=="string"?a.url:""}`),i.push("");let c=(typeof a.transcript=="string"?a.transcript:"").split(`
`),u=0;for(let d of c)if(d.trim()&&(d.match(/^\[(\d+:\d+)\]/)?(u>0&&i.push(""),i.push(`\u23F0 ${d}`)):i.push(`   ${d.trim()}`),u++,u>30)){i.push(""),i.push("... (transcript truncated for display)");break}a.elapsed_time_ms&&(i.push(""),i.push(`Processing time: ${(typeof a.elapsed_time_ms=="number"?a.elapsed_time_ms/1e3:0).toFixed(1)}s`))}else i.push(`\u274C Failed to transcribe: ${typeof a.url=="string"?a.url:""}`),i.push(`   ${typeof a.message=="string"?a.message:""}`);i.push(""),i.push("---"),i.push("")}}return i.join(`
`).trimEnd()}if(r.transcript){let o=["\u{1F4FA} YouTube Transcript"];o.push("");let s=(typeof r.transcript=="string"?r.transcript:"").split(`
`),a=0;for(let l of s)if(l.trim()&&(l.match(/^\[(\d+:\d+)\]/)?(a>0&&o.push(""),o.push(`\u23F0 ${l}`)):o.push(`   ${l.trim()}`),a++,a>50)){o.push(""),o.push("... (transcript truncated for display)");break}return r.elapsed_time_ms&&(o.push(""),o.push(`Processing time: ${(typeof r.elapsed_time_ms=="number"?r.elapsed_time_ms/1e3:0).toFixed(1)}s`)),o.join(`
`)}return typeof e=="object"?JSON.stringify(e,null,2):""}static formatWriteToFile(e){let n=typeof e=="object"&&e!==null?e:null,r=n?n.result:e,o=(typeof r=="string"?r:typeof r=="number"||typeof r=="boolean"?String(r):"").toLowerCase();return o.includes("accepted")?"\u2705 File change: accepted":o.includes("rejected")?"\u274C File change: rejected":n&&typeof n.message=="string"?n.message:typeof r=="string"?r:""}static formatReplaceInFile(e){let n=typeof e=="object"&&e!==null?e:null,r=n?n.result:void 0,o=n?typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):"":typeof e=="string"?e:"",i=n?n.diff:void 0,s=typeof i=="string"?i:typeof i=="number"?String(i):"";return o.toLowerCase().includes("accepted")&&s?`\u2705 Edit accepted
\`\`\`diff
${s}
\`\`\``:o.toLowerCase().includes("accepted")?"\u2705 Edit accepted":o.toLowerCase().includes("rejected")?"\u274C Edit rejected":n&&typeof n.message=="string"?n.message:o}static formatReadNote(e){let n=e;if(typeof e=="string")try{n=JSON.parse(e)}catch{n=null}let r=Wjt(n);return r||(typeof e=="string"?e:JSON.stringify(e,null,2))}};Se();var dYe=require("obsidian"),Hjt="obsidian",Kjt=["/Applications/Obsidian.app/Contents/MacOS/obsidian","/Applications/Obsidian.app/Contents/MacOS/Obsidian"],qjt=15e3,Gjt=1048576;function nxe(){let t=dYe.Platform;return!!(t.isDesktopApp??t.isDesktop)}function Yjt(){let t=window;if(typeof t.require!="function")throw new Error("Node require is unavailable in this runtime. Obsidian CLI commands require the desktop app.");return t.require}function Zjt(){let e=Yjt()("child_process");if(typeof e.execFile!="function")throw new Error("Failed to resolve child_process.execFile");return e.execFile}function Jjt(t){return t.replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function Xjt(){let e=window.process?.env;return e?[e.OBSIDIAN_CLI_BINARY,e.OBSIDIAN_CLI_PATH].map(r=>r?.trim()||"").filter(Boolean):[]}function Qjt(t){let e=t?.trim();if(e)return[e];let n=[...Xjt(),Hjt,...Kjt];return Array.from(new Set(n.map(r=>r.trim()).filter(Boolean)))}function e4t(t){let e=[],n=t.vault?.trim();n&&e.push(`vault=${n}`),e.push(t.command);let r=Object.entries(t.params||{});r.sort(([o],[i])=>o.localeCompare(i));for(let[o,i]of r)if(i!=null){if(typeof i=="boolean"){i&&e.push(o);continue}e.push(`${o}=${Jjt(String(i))}`)}return e}function t4t(t){return typeof t=="number"?t:null}async function n4t(t,e,n,r,o,i,s){let a=Date.now();return await new Promise(l=>{t(n,r,{timeout:o,maxBuffer:i,windowsHide:!0},(c,u,d)=>{let f=Date.now()-a;if(c){l({command:e,args:r,binary:n,attemptedBinaries:[...s],ok:!1,stdout:u||"",stderr:d||"",exitCode:t4t(c.code),errorCode:c.code??null,signal:c.signal??null,durationMs:f});return}l({command:e,args:r,binary:n,attemptedBinaries:[...s],ok:!0,stdout:u||"",stderr:d||"",exitCode:0,errorCode:null,signal:null,durationMs:f})})})}async function Sv(t){let e=t.command?.trim();if(!e)throw new Error("Obsidian CLI command is required");if(!nxe())throw new Error("Obsidian CLI commands are only supported in desktop Obsidian.");let n=e4t({...t,command:e}),r=t.timeoutMs??qjt,o=t.maxBufferBytes??Gjt,i=Zjt(),s=Qjt(t.binary),a=[],l=null;for(let c of s){a.push(c);let u=await n4t(i,e,c,n,r,o,a);if(l=u,u.ok||u.errorCode!=="ENOENT")return u}if(l)return l;throw new Error("Obsidian CLI execution failed before process spawn.")}async function fYe(t){return await Sv({command:"daily:read",vault:t})}async function pYe(t){return await Sv({command:"random:read",vault:t})}fc();function r4t(t){return typeof t=="object"&&t!==null&&"children"in t&&"path"in t}function o4t(t){return typeof t=="object"&&t!==null&&"path"in t&&!("children"in t)}function i4t(t){let e=t.split(".");return e.length>1&&e.pop()?.toLowerCase()||""}function rxe(t,e=!0){let n=[],r={},o={},{inclusions:i,exclusions:s}=Bo();for(let l of t.children)if(o4t(l)){if(Qr(l,i,s)){e&&n.push(l.name);let c=i4t(l.name)||"unknown";c&&(r[c]=(r[c]||0)+1)}}else if(r4t(l)){let c=rxe(l,e);if(Object.keys(c).length>0&&(o[l.name]=c[l.name],c[l.name].extensionCounts))for(let[u,d]of Object.entries(c[l.name].extensionCounts))r[u]=(r[u]||0)+d}let a={};return Object.keys(r).length>0&&(a.extensionCounts=r),e&&n.length>0&&(a.files=n),Object.keys(o).length>0&&(a.subFolders=o),Object.keys(a).length===0?{}:t.name?{[t.name]:a}:{vault:a}}var mYe=t=>Rr({name:"getFileTree",description:"Get the file tree as a nested structure of folders and files",schema:we.object({}),func:async()=>{let e=rxe(t,!0),n=`A JSON represents the file tree as a nested structure:
* The root object has a key "vault" which contains a FileTreeNode object.
* Each FileTreeNode has these properties:
  * files: An array of filenames in the current directory (if any files exist)
  * subFolders: An object mapping folder names to their FileTreeNode objects (if any subfolders exist)
  * extensionCounts: An object with counts of file extensions in this folder and all subfolders

`,r=JSON.stringify(e);if(r.length>5e5){let o=rxe(t,!1);return n+JSON.stringify(o)}return n+r}});var lR=require("obsidian");ye();Se();qe();Kr();var o_=class{constructor(e){this.recentConversationsContent="";this.savedMemoriesContent="";this.isUpdatingMemory=!1;this.app=e}async loadMemory(){try{let e=this.app.vault.getAbstractFileByPath(this.getRecentConversationFilePath());e instanceof lR.TFile?this.recentConversationsContent=await this.app.vault.read(e):(this.recentConversationsContent="",k("[UserMemoryManager] Recent Conversations file not found, skipping memory load"));let n=this.app.vault.getAbstractFileByPath(this.getSavedMemoriesFilePath());n instanceof lR.TFile?this.savedMemoriesContent=await this.app.vault.read(n):(this.savedMemoriesContent="",k("[UserMemoryManager] Saved Memories file not found, skipping saved memory load"))}catch(e){z("[UserMemoryManager] Error reading memory files:",e),this.recentConversationsContent="",this.savedMemoriesContent=""}}addRecentConversation(e,n){if(!q().enableRecentConversations){ee("[UserMemoryManager] Recent history referencing is disabled, skipping analysis");return}if(e.length===0){ee("[UserMemoryManager] No messages to analyze for user memory");return}this.updateMemory(e,n).catch(o=>{z("[UserMemoryManager] Background user memory operation failed:",o)})}async updateSavedMemory(e,n){if(!q().enableSavedMemory)return{error:"Saved memory is disabled, skipping save"};if(!e||e.trim()==="")return{error:"No content provided for saved memory"};if(!n)return{error:"No chat model available, skipping save"};try{return await this.ensureMemoryFolderExists(),await this.updateSavedMemoryFile(this.getSavedMemoriesFilePath(),e,n)}catch(o){return{error:"Error saving memory: "+(o instanceof Error?o.message:String(o))}}}async getUserMemoryPrompt(){await this.loadMemory();try{let e=q(),n="";return e.enableRecentConversations&&this.recentConversationsContent&&(n+=`<recent_conversations>
        ${this.recentConversationsContent}
        </recent_conversations>

        The current time is ${this.getTimestamp()}.
        <recent_conversations> are the recent conversations between you and the user. 
        You can use it to provide more context for your responses. 
        Only use the recent conversations if they are relevant to the current conversation.`),e.enableSavedMemory&&this.savedMemoriesContent&&(n+=`<saved_memories>
        ${this.savedMemoriesContent}
        </saved_memories>

        <saved_memories> are important memories that the user explicitly asked you to remember. 
        Use these memories to provide more personalized and contextually relevant responses.`),n.length>0?n:null}catch(e){return z("[UserMemoryManager] Error reading user memory content:",e),null}}getTimestamp(){let e=new Date,n=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0"),i=String(e.getHours()).padStart(2,"0"),s=String(e.getMinutes()).padStart(2,"0");return`${n}-${r}-${o} ${i}:${s}`}async createConversationSection(e,n){let{title:r,summary:o}=await this.extractTitleAndSummary(e,n),i=this.getTimestamp(),s=`## ${r}
`;return s+=`**Time:** ${i}
`,s+=`**Summary:** ${o}
`,s}async updateMemory(e,n){if(this.isUpdatingMemory){k("[UserMemoryManager] Memory update already in progress, skipping.");return}this.isUpdatingMemory=!0;try{if(await this.ensureMemoryFolderExists(),!n){z("[UserMemoryManager] No chat model available, skipping memory update");return}if(e.length===0){k("[UserMemoryManager] No messages available, skipping memory update");return}let r=await this.createConversationSection(e,n);await this.addToRecentConversationsFile(this.getRecentConversationFilePath(),r)}catch(r){z("[UserMemoryManager] Error analyzing chat messages for user memory:",r)}finally{this.isUpdatingMemory=!1}}async ensureMemoryFolderExists(){let n=q().memoryFolderName;await Fr(n)}getRecentConversationFilePath(){return`${q().memoryFolderName}/Recent Conversations.md`}getSavedMemoriesFilePath(){return`${q().memoryFolderName}/Saved Memories.md`}async updateSavedMemoryFile(e,n,r){let o=this.app.vault.getAbstractFileByPath(e),i=o instanceof lR.TFile?await this.app.vault.read(o):"";if(!r)return{error:"No chat model available, skipping memory update"};let s=`You maintain a user's long-term personal memory list as concise bullet points.

    You task is to update the user's memory list with the new statement.
Rules:
- Keep only stable, evergreen facts or preferences that will help future conversations.
- Remove duplicates and near-duplicates by merging them into one concise statement.
- If the new statement conflicts with older ones, keep the most recent truth and remove obsolete/conflicting entries.
- Prefer short, specific, and unambiguous phrasing.
- Preserve the language used in the input memories.
- Output only the memory content with each as a bullet point.


# OUTPUT FORMAT
Return the updated memory list with each as a bullet point.
- memory item 1
- memory item 2
- memory item 3
...
`,a=`<current_memories>
${i.trim()}
</current_memories>

<new_statement>
${n.trim()}
</new_statement>
`,l=[new Vu(s),new Zo(a)],c=null;try{c=(await r.invoke(l)).text??""}catch(u){return{error:"LLM call failed while updating saved memories: "+(u instanceof Error?u.message:String(u))}}return c==null||c.trim()===""?{error:"Empty content returned from LLM"}:(o instanceof lR.TFile?await this.app.vault.modify(o,c):await this.app.vault.create(e,c),{content:c})}async addToRecentConversationsFile(e,n){let r=this.app.vault.getAbstractFileByPath(e);if(r instanceof lR.TFile){let o=await this.app.vault.read(r),i;if(o.trim()==="")i=`${n.trim()}
`;else{let s=this.parseExistingConversations(o);s.push(n);let l=q().maxRecentConversations;s.length>l&&s.splice(0,s.length-l),i=`${s.map(u=>u.trim()).join(`

`)}
`}await this.app.vault.modify(r,i)}else{let o=`${n.trim()}
`;await this.app.vault.create(e,o)}}parseExistingConversations(e){let n=e.split(`
`),r=[],o=[];for(let i of n)i.trim().startsWith("## ")?(o.length>0&&r.push(o.join(`
`).trim()),o=[i]):o.length>0&&o.push(i);return o.length>0&&r.push(o.join(`
`).trim()),r}extractJsonFromResponse(e){let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);if(n)return n[1].trim();let r=e.match(/\{[\s\S]*\}/);return r?r[0]:e}async extractTitleAndSummary(e,n){let r=e.map(a=>`${a.sender}: ${a.message}`).join(`

`),o=`Your task is to analyze a conversation and generate both a title and a summary.

# OUTPUT FORMAT
You must return your response in the following JSON format:
{
  "title": "Brief 2-8 word title capturing the main user intent",
  "summary": "2-3 sentence summary at most including key details (e.g. user facts mentioned entities), and key conclusions if there are any."
}

# RULES
* Use the same language as the conversation`,i=`<conversation_text>
${r}
</conversation_text>

Generate a title and summary for this conversation:`,s=[new Vu(o),new Zo(i)];try{let l=(await n.invoke(s)).text,c=this.extractJsonFromResponse(l);try{let u=JSON.parse(c);return{title:u.title||"Untitled Conversation",summary:u.summary||"No summary available"}}catch(u){return z("[UserMemoryManager] Failed to parse LLM response as JSON:",u),{title:"Untitled Conversation",summary:"Summary generation failed"}}}catch(a){return z("[UserMemoryManager] Failed to extract title and summary:",a),{title:"Untitled Conversation",summary:"Summary generation failed"}}}};ye();eP();var s4t=we.object({statement:we.string().min(1).describe("The user statement for explicitly updating saved memories")}),n9=Rr({name:"updateMemory",description:"Update the user memory when the user explicitly asks to update the memory",schema:s4t,func:async({statement:t})=>{try{let e=new o_(app),n=Np.getInstance().getChatModel(),r=await e.updateSavedMemory(t,n);return r.error?{success:!1,message:r.error}:{success:!0,message:`Memory updated successfully into ${e.getSavedMemoriesFilePath()}: ${r.content}`}}catch(e){return z("[updateMemoryTool] Error updating memory:",e),{success:!1,message:`Failed to save memory: ${e instanceof Error?e.message:String(e)}`}}}});var Cz=require("obsidian");ye();var oxe=200;function r9(t){return t.replace(/\\/g,"/").toLowerCase()}function a4t(t){return t.replace(/\.[^/.]+$/,"")}function l4t(t,e){if(e.length===0)return!1;let r=r9(t).split("/").filter(Boolean);if(r.length<e.length)return!1;let o=r.slice(-e.length);for(let i=0;i<e.length;i+=1){let s=e[i];if(!s)return!1;let a=o[i];if(i===o.length-1){let l=a4t(a);if(!a.includes(s)&&!l.includes(s))return!1}else if(!a.includes(s))return!1}return!0}function ixe(t){return/\.[^/]+$/.test(t)}async function c4t(t){let e=w=>{let v=app.vault.getAbstractFileByPath(w);return v instanceof Cz.TFile?v:null},n=t.trim(),r=n.match(/^\s*\[\[([\s\S]+?)\]\]\s*$/),i=(r?r[1]:n).trim(),[s]=i.split("|"),[a]=s.split("#"),l=a.trim(),c=Array.from(new Set([n,i,l].map(w=>w.trim()).filter(Boolean)));for(let w of c){let v=e(w);if(v)return{type:"resolved",file:v};if(!ixe(w))for(let x of[".md",".canvas"]){let b=e(`${w}${x}`);if(b)return{type:"resolved",file:b}}}let u=app.metadataCache,d=l.trim();if(u&&d){let w=new Set([d]);if(!ixe(d))for(let v of[".md",".canvas"])w.add(`${d}${v}`);for(let v of w){let x=u.getFirstLinkpathDest?.(v,"");if(x instanceof Cz.TFile)return{type:"resolved",file:x}}}if(!d)return{type:"not_found"};let f=app.vault.getMarkdownFiles?.()??[];if(f.length===0)return{type:"not_found"};let p=r9(d),m=new Set([p]);if(!ixe(d))for(let w of[".md",".canvas"])m.add(r9(`${d}${w}`));for(let w of f){let v=r9(w.path);if(m.has(v))return{type:"resolved",file:w}}let h=d.split("/").pop();if(h){let w=h.toLowerCase(),v=f.filter(x=>x.basename.toLowerCase()===w);if(v.length===1)return{type:"resolved",file:v[0]};if(v.length>1)return{type:"not_unique",matches:v}}let g=p.split("/").filter(Boolean);if(g.length===0)return{type:"not_found"};let y=f.filter(w=>l4t(w.path,g));return y.length===1?{type:"resolved",file:y[0]}:y.length>1?{type:"not_unique",matches:y}:{type:"not_found"}}async function u4t(t){try{return await app.vault.read(t)}catch(e){return ee(`readNote: failed to read ${t.path}`,e),""}}function d4t(){let t=new Map,e=app.vault.getMarkdownFiles?.()??[];for(let n of e)if(n instanceof Cz.TFile){let r=t.get(n.basename)??[];r.push(n),t.set(n.basename,r)}return t}function f4t(t,e,n){let r=t.trim();if(!r)return[];let o=new Map,i=app.metadataCache.getFirstLinkpathDest?.(r,e);if(i instanceof Cz.TFile&&o.set(i.path,i),!/\.[^./]+$/.test(r)){let s=r.split("/").pop()??r,a=n.get(s)??[];for(let l of a)o.set(l.path,l)}return Array.from(o.values())}function p4t(t,e){if(!t)return[];let n=/\[\[([^\]]+)\]\]/g,r=new Map,o=null,i;for(;(i=n.exec(t))!==null;){if(i.index>0&&t[i.index-1]==="!")continue;let s=i[1]?.trim();if(!s)continue;let[a,l]=s.split("|"),[c,u]=a.split("#"),d=c?.trim();if(!d)continue;let f=`${d}|${l??""}|${u??""}`;if(r.has(f))continue;o||(o=d4t());let p=f4t(d,e.path,o);r.set(f,{linkText:d,displayText:l?.trim()||d,section:u?.trim()||void 0,candidates:p.map(m=>({path:m.path,title:m.basename})),unresolved:p.length===0?!0:void 0})}return Array.from(r.values())}function m4t(t,e){let n=e.split(/\r?\n/),r=n.length===1&&n[0]===""?0:n.length;if(r===0)return[{id:`${t.path}#L1-1`,notePath:t.path,chunkIndex:0,content:"",heading:""}];let o=Math.ceil(r/oxe),i=[];for(let s=0;s<o;s++){let a=s*oxe,l=Math.min((s+1)*oxe,r),c=n.slice(a,l),u=c.find(f=>/^#+\s+/.test(f.trim())),d=u?u.trim().replace(/^#+\s+/,""):"";i.push({id:`${t.path}#L${a+1}-${l}`,notePath:t.path,chunkIndex:s,content:c.join(`
`).trimEnd(),heading:d})}return i}var h4t=we.object({notePath:we.string().min(1).describe("Full path to the note (relative to the vault root) that needs to be read, such as 'Projects/plan.md'."),chunkIndex:we.preprocess(t=>{if(typeof t=="string"){let e=t.trim();if(e.length===0)return;let n=Number(e);return Number.isFinite(n)?n:t}return t},we.number().int().min(0)).optional().describe("0-based chunk index to read. Omit to read the first chunk.")}),hYe=Rr({name:"readNote",description:"Read a single note in search v3 sized chunks. Use only when you already know the exact note path and need its contents.",schema:h4t,func:async({notePath:t,chunkIndex:e=0})=>{let n=t.trim();if(n.startsWith("/"))return{notePath:n,status:"invalid_path",message:"Provide the note path relative to the vault root without a leading slash."};let r=await c4t(n);if(r.type==="not_found")return ee(`readNote: note not found or not a file (${n})`),{notePath:n,status:"not_found",message:`Note "${n}" was not found or is not a readable file.`};if(r.type==="not_unique")return ee(`readNote: ambiguous note path "${n}" matched multiple files`,r.matches.map(f=>f.path)),{notePath:n,status:"not_unique",message:`Multiple notes match "${n}". Provide a more specific path.`,candidates:r.matches.map(f=>({path:f.path,title:f.basename}))};let o=r.file,i=o.path,s=await u4t(o),a=m4t(o,s),l=a.length;if(l===0)return{notePath:i,status:"empty",message:`No readable content was found in "${i}".`};if(e>=l)return{notePath:i,status:"out_of_range",message:`Chunk index ${e} exceeds available chunks (last index ${l-1}).`,totalChunks:l};let c=a[e];k(`readNote: returning chunk ${c.chunkIndex} of ${l} for ${i}`);let u=c.chunkIndex<l-1,d=p4t(c.content,o);return{notePath:i,noteTitle:o.basename,heading:c.heading,chunkId:c.id,chunkIndex:c.chunkIndex,totalChunks:l,hasMore:u,nextChunkIndex:u?c.chunkIndex+1:null,content:c.content,mtime:o.stat.mtime,linkedNotes:d.length>0?d:void 0}}});function o9(t,e,n,r){let o=t.trim();return o.length>0?o:n==="ENOENT"?`CLI binary not found. Tried: ${r.length>0?r.join(", "):"unknown"}. Ensure Obsidian CLI is installed or set OBSIDIAN_CLI_BINARY/OBSIDIAN_CLI_PATH.`:n!==null?`Obsidian CLI failed with error code ${String(n)}`:e!==null?`Obsidian CLI failed with exit code ${e}`:"Obsidian CLI command failed for an unknown reason"}function oP(t){throw new Error(o9(t.stderr,t.exitCode,t.errorCode,t.attemptedBinaries))}var Ndr=Rr({name:"obsidianDailyRead",description:"Read the current daily note via Obsidian CLI and return the note content as plain text.",schema:we.object({vault:we.string().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await fYe(t);if(!e.ok)throw new Error(`Failed to read daily note via Obsidian CLI: ${o9(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_daily_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}}),gYe=Rr({name:"obsidianRandomRead",description:"Read a random note via Obsidian CLI and return the note content as plain text.",schema:we.object({vault:we.string().optional().describe("Optional vault name to target. Omit to use the active/default vault resolution from Obsidian CLI.")}),func:async({vault:t})=>{let e=await pYe(t);if(!e.ok)throw new Error(`Failed to read random note via Obsidian CLI: ${o9(e.stderr,e.exitCode,e.errorCode,e.attemptedBinaries)}`);return{type:"obsidian_cli_random_read",command:e.command,vault:t||null,content:e.stdout,durationMs:e.durationMs}}});function cR(t){return Object.fromEntries(Object.entries(t).filter(([e,n])=>e!=="command"&&e!=="vault"&&n!==void 0))}var g4t=we.object({command:we.enum(["daily","daily:read","daily:path"]).describe("daily \u2014 create today's daily note (applies configured template). daily:read \u2014 read today's daily note content. daily:path \u2014 get the vault-relative file path."),vault:we.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),yYe=Rr({name:"obsidianDailyNote",description:"Create or read today's daily note, or get its vault path, via the official Obsidian CLI. Use readNote for reading specific notes by path. Use obsidianRandomRead for picking a random note.",schema:g4t,func:async t=>{let{command:e,vault:n}=t,r=cR(t),o=await Sv({command:e,vault:n,params:r});o.ok||oP(o);let i=e==="daily:read"?o.stdout:o.stdout.trim();return{type:"obsidian_cli_daily_note",command:o.command,vault:n??null,content:i,durationMs:o.durationMs}}}),y4t=we.object({command:we.enum(["properties","property:read"]).describe("properties \u2014 list property names vault-wide or key-value pairs for a specific note. property:read \u2014 read a single property value from a note."),name:we.string().optional().describe("For property:read: the property name to read (required). For properties vault-wide: filter to this property name."),file:we.string().optional().describe("Target file by name (without extension)."),path:we.string().optional().describe("Target file by vault-relative path."),counts:we.boolean().optional().describe("Include occurrence counts alongside property names (vault-wide mode)."),sort:we.string().optional().describe("Sort order for vault-wide listing. Use 'count' to sort by occurrence count."),total:we.boolean().optional().describe("Return only the total property count."),vault:we.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),wYe=Rr({name:"obsidianProperties",description:"Read frontmatter properties from your vault via the official Obsidian CLI: list all property names used vault-wide, or read specific property values from a note.",schema:y4t,func:async t=>{let{command:e,vault:n}=t;if(e==="property:read"&&!t.name)throw new Error("name is required for property:read");let r=cR(t),o=await Sv({command:e,vault:n,params:r});return o.ok||oP(o),{type:"obsidian_cli_properties",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}}),w4t=we.object({command:we.literal("tasks").describe('Must be exactly "tasks". Lists tasks across the vault with optional filters.'),file:we.string().optional().describe("Filter tasks by file name."),path:we.string().optional().describe("Filter tasks by vault-relative file path."),todo:we.boolean().optional().describe("Show only incomplete (todo) tasks."),done:we.boolean().optional().describe("Show only completed tasks."),status:we.string().optional().describe("Filter by a specific status character (e.g. '/' for in-progress)."),daily:we.boolean().optional().describe("Show tasks from today's daily note only."),verbose:we.boolean().optional().describe("Group tasks by file with line numbers."),total:we.boolean().optional().describe("Return only the total task count."),vault:we.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),vYe=Rr({name:"obsidianTasks",description:"List tasks across your vault via the official Obsidian CLI with filters for completion status, file, daily note, and more.",schema:w4t,func:async t=>{let{command:e,vault:n}=t,r=cR(t),o=await Sv({command:e,vault:n,params:r});return o.ok||oP(o),{type:"obsidian_cli_tasks",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}}),v4t=we.object({command:we.enum(["backlinks","links","orphans","unresolved"]).describe("backlinks \u2014 list notes that link TO a given file. links \u2014 list outgoing links FROM a file. orphans \u2014 list files with no incoming links. unresolved \u2014 list wikilinks that don't resolve to any file."),file:we.string().optional().describe("Target file by name (for backlinks and links commands)."),path:we.string().optional().describe("Target file by vault-relative path (for backlinks and links commands)."),counts:we.boolean().optional().describe("Include link counts per source file (for backlinks and unresolved)."),verbose:we.boolean().optional().describe("Include source file for each entry (for unresolved)."),total:we.boolean().optional().describe("Return only the count."),all:we.boolean().optional().describe("Include non-markdown files such as images and PDFs (for orphans)."),vault:we.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),xYe=Rr({name:"obsidianLinks",description:"Query the vault link graph via the official Obsidian CLI: list backlinks to a file, outgoing links from a file, orphaned notes with no incoming links, or unresolved wikilinks.",schema:v4t,func:async t=>{let{command:e,vault:n}=t,r=cR(t),o=await Sv({command:e,vault:n,params:r});return o.ok||oP(o),{type:"obsidian_cli_links",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}}),x4t=we.object({command:we.enum(["templates","template:read"]).describe("templates \u2014 list all available template names. template:read \u2014 read a template's content with variable resolution."),name:we.string().optional().describe("Template name to read. Required for template:read."),vault:we.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),bYe=Rr({name:"obsidianTemplates",description:"List available templates or read template content via the official Obsidian CLI. Use before creating notes to find the right template.",schema:x4t,func:async t=>{let{command:e,vault:n}=t;if(e==="template:read"&&!t.name)throw new Error("name is required for template:read");let r=cR(t),o=await Sv({command:e,vault:n,params:r});return o.ok||oP(o),{type:"obsidian_cli_templates",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}}),b4t=we.object({command:we.enum(["bases","base:views","base:query","base:create"]).describe("bases \u2014 list all Base files in the vault. base:views \u2014 list views defined in a Base file. base:query \u2014 query data from a Base view. base:create \u2014 create a new item (row) in a Base."),file:we.string().optional().describe("Target Base file by name (without extension). Used for base:views, base:query, and base:create."),path:we.string().optional().describe("Target Base file by vault-relative path. Alternative to file= for base:views, base:query, and base:create."),view:we.string().optional().describe("View name. For base:query: view to query. For base:create: view to add item to."),name:we.string().optional().describe("New file name for the created item. For base:create only."),content:we.string().optional().describe("Initial content for the created item. For base:create only."),format:we.string().optional().describe("Output format for base:query (e.g., 'csv'). Omit for default text output."),total:we.boolean().optional().describe("Return only the count."),vault:we.string().optional().describe("Optional vault name to target. Omit to use the active vault.")}),C4t=["base:views","base:query","base:create"],CYe=Rr({name:"obsidianBases",description:"Interact with Obsidian Base (database) files via the official Obsidian CLI: list all bases, list views in a base, query data from a base view, or create a new item in a base.",schema:b4t,func:async t=>{let{command:e,vault:n}=t;if(C4t.includes(e)&&!t.file&&!t.path)throw new Error(`file or path is required for ${e}`);let r=cR(t),o=await Sv({command:e,vault:n,params:r});return o.ok||oP(o),{type:"obsidian_cli_bases",command:o.command,vault:n??null,content:o.stdout.trim(),durationMs:o.durationMs}}});It();Zg();ye();yp();ns();Se();ye();ns();Se();qe();async function _Ye(t,e,n){try{if(!t||!t.name)return{toolName:t?.name||"unknown",result:"Error: Invalid tool call - missing tool name",success:!1};let o=e.find(u=>u.name===t.name);if(!o){let u=e.map(d=>d.name).join(", ");return{toolName:t.name,result:`Error: Tool '${t.name}' not found. Available tools: ${u}. Make sure you have the tool enabled in the Agent settings.`,success:!1}}let s=Vi.getInstance().getToolMetadata(t.name);if(s?.isPlusOnly&&!await _p()&&!pc())return{toolName:t.name,result:`Error: ${sxe(t.name)} requires a Copilot Plus subscription`,success:!1};let a={...t.args};s?.requiresUserMessageContent&&n&&(a._userMessageContent=n);let l=12e4;typeof s?.timeoutMs=="number"&&(l=s.timeoutMs);let c;return!l||l===1/0?c=await Cv.callTool(o,a):c=await Promise.race([Cv.callTool(o,a),new Promise((u,d)=>window.setTimeout(()=>d(new Error(`Tool execution timed out after ${l}ms`)),l))]),c==null?(ee(`Tool ${t.name} returned null/undefined result`),{toolName:t.name,result:JSON.stringify({message:"Tool executed but returned no result",status:"empty"}),success:!0}):{toolName:t.name,result:typeof c=="string"?c:JSON.stringify(c),success:!0}}catch(o){let i=Xt(o);return i.includes("schema")?z(`[ToolCall] Schema validation failed for "${t.name}". Args: ${JSON.stringify(t.args,null,2)}`):z(`[ToolCall] Error executing "${t.name}": ${i}`),{toolName:t.name,result:`Error: ${i}`,success:!1}}}function sxe(t){return t==="localSearch"?q().enableSemanticSearchV3?"vault search (semantic)":"vault search (index-free)":{webSearch:"web search",getFileTree:"file tree",getCurrentTime:"current time",getTimeRangeMs:"time range",getTimeInfoByEpoch:"time info",convertTimeBetweenTimezones:"timezone converter",startPomodoro:"pomodoro timer",pomodoroTool:"pomodoro timer",youtubeTranscription:"YouTube transcription",indexVault:"vault indexing",indexTool:"index",writeFile:"file editor",editFile:"file editor",obsidianDailyNote:"daily note (CLI)",obsidianRandomRead:"random note (CLI)",obsidianProperties:"properties (CLI)",obsidianTasks:"tasks (CLI)",obsidianLinks:"links (CLI)",obsidianTemplates:"templates (CLI)",obsidianBases:"bases (CLI)"}[t]||t}function SYe(t){return{localSearch:"\u{1F50D}",webSearch:"\u{1F310}",getFileTree:"\u{1F4C1}",getCurrentTime:"\u{1F552}",getTimeRangeMs:"\u{1F4C5}",getTimeInfoByEpoch:"\u{1F570}\uFE0F",convertTimeBetweenTimezones:"\u{1F30D}",youtubeTranscription:"\u{1F4FA}",indexVault:"\u{1F4DA}",indexTool:"\u{1F4DA}",writeFile:"\u270F\uFE0F",editFile:"\u{1F504}",readNote:"\u{1F50D}",obsidianDailyNote:"\u{1F4C5}",obsidianRandomRead:"\u{1F3B2}",obsidianProperties:"\u{1F3F7}\uFE0F",obsidianTasks:"\u2705",obsidianLinks:"\u{1F517}",obsidianTemplates:"\u{1F4C4}",obsidianBases:"\u{1F5C4}\uFE0F"}[t]||"\u{1F527}"}function TYe(t,e){let n=sxe(t.name),r=SYe(t.name),o=Object.keys(t.args).length>0?JSON.stringify(t.args,null,2):"(no parameters)";k(`${r} [Iteration ${e}] ${n.toUpperCase()}`),k("Parameters:",o),k("---")}function IYe(t,e){if(t==="localSearch")return;let n=sxe(t),r=SYe(t),o=e.success?"\u2705 SUCCESS":"\u274C FAILED";k(`${r} ${n.toUpperCase()} RESULT: ${o}`);let i=300,s=String(e.result??"");s.length>i?k(`Result: ${s.substring(0,i)}... (truncated, ${s.length} chars total)`):s.length>0&&k("Result:",s)}function iP(t){let e=new Map;for(let n of t){let r=n.path||n.title,o=e.get(r);(!o||n.score>o.score)&&e.set(r,n)}return Array.from(e.values()).sort((n,r)=>r.score-n.score)}fz();U8();N0();B8();function _4t(t){let e=new Set,n=[],r=o=>{if(typeof o!="string")return;let i=o.toLowerCase().trim();i&&!e.has(i)&&(e.add(i),n.push(o.trim()))};return t.originalQuery&&typeof t.originalQuery=="string"&&r(t.originalQuery),(t.salientTerms||[]).forEach(r),(t.expandedQueries||[]).forEach(r),n}var lxe=we.object({query:we.string().min(1).describe("The search query to find relevant notes"),salientTerms:we.array(we.string()).describe("Keywords extracted from the user's query for BM25 full-text search. Must be from original query."),timeRange:we.object({startTime:we.number().optional().describe("Start time as epoch milliseconds"),endTime:we.number().optional().describe("End time as epoch milliseconds")}).optional().describe("Optional time range filter. Use epoch milliseconds from getTimeRangeMs result."),_preExpandedQuery:we.object({originalQuery:we.string(),salientTerms:we.array(we.string()),expandedQueries:we.array(we.string()),recallTerms:we.array(we.string())}).optional().describe("Internal: pre-expanded query data injected by the system to avoid double expansion")});async function axe({timeRange:t,query:e,salientTerms:n,forceLexical:r=!1,preExpandedQuery:o}){let i=q(),s=n.filter(A=>A.startsWith("#")),a=s.length>0?s:(()=>{try{return[...e.matchAll(/#[\p{L}\p{N}_/-]+/gu)].map(A=>A[0])}catch{return[...e.matchAll(/#[a-z0-9_/-]+/gi)].map(A=>A[0])}})(),l=a.length>0,c=t!==void 0||l,u=c?ni:i.maxSourceChunks;k(`lexicalSearch effectiveMaxK: ${u} (expanded: ${c}), forceLexical: ${r}`);let d=o?{...o,queries:[o.originalQuery,...o.expandedQueries||[]].filter(Boolean)}:void 0,f=new XC(app,{salientTerms:n,timeRange:t,maxK:u,returnAll:c}),p=await f.getRelevantDocuments(e);k(`lexicalSearch filterRetriever returned ${p.length} filter docs`);let m=[],h;if(!f.hasTimeRange()){let A={minSimilarityScore:c?0:.1,maxK:u,salientTerms:n,textWeight:XV,returnAll:c,useRerankerThreshold:.5,tagTerms:a,preExpandedQuery:d},O,D;if(r)O=lh.createLexicalRetriever(app,A),D="lexical (forced)";else{let $=await lh.createRetriever(app,A);O=$.retriever,D=$.type}if(k(`lexicalSearch using ${D} retriever`),m=await O.getRelevantDocuments(e),O instanceof ah){let $=O.getLastQueryExpansion();$&&(h={originalQuery:$.originalQuery,salientTerms:$.salientTerms,expandedQueries:$.expandedQueries,recallTerms:_4t($)})}}let{filterResults:g,searchResults:y}=nR(p,m),w=(A,O)=>({title:A.metadata.title||"Untitled",content:A.pageContent,path:A.metadata.path||"",score:A.metadata.rerank_score??A.metadata.score??0,rerank_score:A.metadata.rerank_score??A.metadata.score??0,includeInContext:A.metadata.includeInContext??!0,source:A.metadata.source,mtime:A.metadata.mtime??null,ctime:A.metadata.ctime??null,chunkId:A.metadata.chunkId??null,isChunk:A.metadata.isChunk??!1,explanation:A.metadata.explanation??null,isFilterResult:O,matchType:O?A.metadata.source||"filter":void 0}),v=g.map(A=>w(A,!0)),x=y.map(A=>w(A,!1));k(`lexicalSearch found ${v.length} filter + ${x.length} search documents for query: "${e}"`),t&&k(`Time range search from ${new Date(t.startTime).toISOString()} to ${new Date(t.endTime).toISOString()}`);let b=x.map(A=>({title:A.title||A.path||"Untitled",path:A.path||A.title||"",score:A.rerank_score||A.score||0})),_=iP(b),T=new Map;for(let A of x){let O=(A.path||A.title).toLowerCase(),D=T.get(O);(!D||(A.rerank_score||0)>(D.rerank_score||0))&&T.set(O,A)}let S=_.map(A=>T.get((A.path||A.title).toLowerCase())).filter(Boolean);return{type:"local_search",documents:[...v,...S].slice(0,u),queryExpansion:h}}var cfr=Rr({name:"lexicalSearch",description:"Search for notes using lexical/keyword-based search",schema:lxe,func:async({timeRange:t,query:e,salientTerms:n})=>{let r=cxe(t);return await axe({timeRange:r,query:e,salientTerms:n})}}),ufr=Rr({name:"semanticSearch",description:"Search for notes using semantic/meaning-based search with embeddings",schema:lxe,func:async({timeRange:t,query:e,salientTerms:n})=>{let r=cxe(t),o=q(),i=n.filter(h=>h.startsWith("#")),s=r!==void 0||i.length>0,a=s?ni:o.maxSourceChunks;k(`semanticSearch effectiveMaxK: ${a} (expanded: ${s})`);let c=await new(await Promise.resolve().then(()=>(Nye(),$qe))).HybridRetriever({minSimilarityScore:s?0:.1,maxK:a,salientTerms:n,timeRange:r,textWeight:XV,returnAll:s,useRerankerThreshold:.5}).getRelevantDocuments(e);k(`semanticSearch found ${c.length} documents for query: "${e}"`),r&&k(`Time range search from ${new Date(r.startTime).toISOString()} to ${new Date(r.endTime).toISOString()}`);let u=c.map(h=>{let g=h.metadata.rerank_score??h.metadata.score??0;return{title:h.metadata.title||"Untitled",content:h.pageContent,path:h.metadata.path||"",score:g,rerank_score:g,includeInContext:h.metadata.includeInContext??!0,source:h.metadata.source,mtime:h.metadata.mtime??null,ctime:h.metadata.ctime??null,chunkId:h.metadata.chunkId??null,isChunk:h.metadata.isChunk??!1,explanation:h.metadata.explanation??null}}),d=u.map(h=>({title:h.title||h.path||"Untitled",path:h.path||h.title||"",score:h.rerank_score||h.score||0})),f=iP(d),p=new Map;for(let h of u){let g=(h.path||h.title).toLowerCase(),y=p.get(g);(!y||(h.rerank_score||0)>(y.rerank_score||0))&&p.set(g,h)}return{type:"local_search",documents:f.map(h=>p.get((h.path||h.title).toLowerCase())).filter(Boolean)}}});function cxe(t){if(!t)return;let{startTime:e,endTime:n}=t;if(!e||!n||e<=0||n<=0){k("localSearch: Ignoring invalid time range (missing, zero, or negative values)");return}if(e>n){k("localSearch: Ignoring inverted time range (start > end)");return}return{startTime:e,endTime:n}}async function S4t({query:t,salientTerms:e,timeRange:n}){let r=e.filter(p=>p.startsWith("#")),o=n!==void 0||r.length>0,i=o?ni:q().maxSourceChunks,s=new XC(app,{salientTerms:e,timeRange:n,maxK:i,returnAll:o}),a=await s.getRelevantDocuments(t),l=[];s.hasTimeRange()||(l=await lh.createMiyoRetriever(app,{minSimilarityScore:o?0:.1,maxK:i,salientTerms:e,textWeight:XV,returnAll:o,useRerankerThreshold:.5,tagTerms:r}).getRelevantDocuments(t)),k(`miyoSearch: ${a.length} filter + ${l.length} miyo docs for query: "${t}"`);let{filterResults:c,searchResults:u}=nR(a,l),d=(p,m)=>({title:p.metadata.title||"Untitled",content:p.pageContent,path:p.metadata.path||"",score:p.metadata.rerank_score??p.metadata.score??0,rerank_score:p.metadata.rerank_score??p.metadata.score??0,includeInContext:p.metadata.includeInContext??!0,source:p.metadata.source,mtime:p.metadata.mtime??null,ctime:p.metadata.ctime??null,chunkId:p.metadata.chunkId??null,isChunk:p.metadata.isChunk??!1,explanation:p.metadata.explanation??null,isFilterResult:m,matchType:m?p.metadata.source||"filter":void 0});return{type:"local_search",documents:[...c.map(p=>d(p,!0)),...u.map(p=>d(p,!1))].slice(0,i)}}var i9=Rr({name:"localSearch",description:"Search for notes in the vault based on query, salient terms, and optional time range",schema:lxe,func:async({timeRange:t,query:e,salientTerms:n,_preExpandedQuery:r})=>{let o=cxe(t);if(lh.isMiyoActive())return k("localSearch: Using Miyo search path"),await S4t({query:e,salientTerms:n,timeRange:o});let i=n.filter(l=>l.startsWith("#"));if(o!==void 0||i.length>0)return k("localSearch: Forcing lexical search (time range or tags present)"),await axe({timeRange:o,query:e,salientTerms:n,forceLexical:!0,preExpandedQuery:r});let a=lh.getRetrieverType();return k(`localSearch: Using ${a} retriever via factory`),await axe({timeRange:o,query:e,salientTerms:n,preExpandedQuery:r})}}),dfr=Rr({name:"indexVault",description:"Index the vault to the Copilot index",schema:we.object({}),func:async()=>{let t=q();if(t.enableSemanticSearchV3)try{let n=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(),r=Fa(t),o=r?`Requested a Miyo folder scan for this vault.
`:`Semantic search index refreshed with ${n} documents.
`;return{success:!0,message:r?o+"Miyo will handle chunking and indexing for the registered folder.":o+`Semantic search index has been refreshed with ${n} documents.`,documentCount:n}}catch(e){return{success:!1,message:`Failed to index with semantic search: ${e instanceof Error?e.message:String(e)}`}}else return{success:!0,message:"Tiered lexical retriever uses on-demand indexing. No manual indexing required."}}}),T4t=we.object({query:we.string().min(1).describe("The search query to search the internet"),chatHistory:we.array(we.object({role:we.enum(["user","assistant"]),content:we.string()})).describe("Previous conversation turns for context (usually empty array)")}),s9=Rr({name:"webSearch",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",schema:T4t,func:async({query:t,chatHistory:e})=>{try{let n=await AG(t,e),r,o;if(pc()&&B5e()){let s=await z5e(n);r=s.content,o=s.citations}else{let s=await di.getInstance().webSearch(n);r=s.response.choices[0].message.content,o=s.response.citations||[]}return[{type:"web_search",content:r,citations:o,instruction:z9e()}]}catch(n){return console.error(`Error processing web search query ${t}:`,n),{error:`Web search failed: ${n}`}}}});var uxe=5e5,I4t=500,PYe=50,P4t=we.object({includeInline:we.boolean().optional().describe("Include inline tags in addition to frontmatter tags. Defaults to true."),maxEntries:we.number().int().min(1).max(5e3).optional().describe("Maximum number of tag entries to return, sorted by occurrences. Responses are capped at ~500KB.")}).describe("Parameters for retrieving the tag list.");function E4t(){return typeof app>"u"||!app?.metadataCache?null:app.metadataCache}function EYe(t){let e={};if(!t)return e;for(let[n,r]of Object.entries(t)){let o=n?.trim();if(!o)continue;let i=o.replace(/^#+/,"").trim().toLowerCase();if(!i)continue;let s=`#${i}`;if(s==="#")continue;let a=Number.isFinite(r)?Math.max(0,Math.floor(r)):0;e[s]=(e[s]||0)+a}return e}function A4t(t,e,n){let r=t,o=EYe(r.getFrontmatterTags?.()),i=e?EYe(r.getTags?.()):{},s=new Set([...Object.keys(o),...e?Object.keys(i):[]]),a=[],l=0;for(let u of s){let d=o[u]??0,f=e?Math.max(0,i[u]??0):0,p=0,m=d;e&&(f>=d?(p=f-d,m=f):f>0&&(p=f,m=d+p)),m!==0&&(l+=m,a.push({tag:u,occurrences:m,frontmatterOccurrences:d,inlineOccurrences:p}))}a.sort((u,d)=>d.occurrences===u.occurrences?u.tag.localeCompare(d.tag):d.occurrences-u.occurrences);let c=a.slice(0,n);return{totalUniqueTags:a.length,returnedTagCount:c.length,totalOccurrences:l,includedSources:e?["frontmatter","inline"]:["frontmatter"],truncated:c.length<a.length,tags:c}}function k4t(t){let e=t,n=JSON.stringify(e);if(n.length<=uxe)return e;let r=e.tags.length;for(;n.length>uxe&&r>PYe;)r=Math.max(PYe,Math.floor(r/2)),e={...e,tags:t.tags.slice(0,r),returnedTagCount:r,truncated:!0},n=JSON.stringify(e);return n.length>uxe?{totalUniqueTags:t.totalUniqueTags,returnedTagCount:0,totalOccurrences:t.totalOccurrences,includedSources:t.includedSources,truncated:!0,tags:[],note:"Tag list exceeded the size limit. Request a narrower scope or specify a smaller maxEntries value."}:e}function AYe(t){return`A JSON object lists the vault tags and their occurrence counts:
* totalUniqueTags: number of unique tags indexed across the vault
* returnedTagCount: number of tag entries included in this response
* totalOccurrences: total tag occurrences across included sources
* includedSources: sources represented in the counts (frontmatter, inline)
* truncated: whether the list was shortened due to limits
* tags: array of tag objects { tag, occurrences, frontmatterOccurrences, inlineOccurrences }
${JSON.stringify(t)}`}var kYe=()=>Rr({name:"getTagList",description:"Get the list of tags in the vault with occurrence statistics.",schema:P4t,func:async t=>{let e=E4t(),n=t?.includeInline??!0,r=t?.maxEntries??I4t;if(!e)return AYe({totalUniqueTags:0,returnedTagCount:0,totalOccurrences:0,includedSources:n?["frontmatter","inline"]:["frontmatter"],truncated:!1,tags:[],note:"Metadata cache is unavailable. Try again after the vault finishes indexing."});let o=A4t(e,n,r),i=k4t(o);return AYe(i)}});var RYe=N(MYe(),1),_z=N(i_(),1);var Lr;(function(t){t[t.AM=0]="AM",t[t.PM=1]="PM"})(Lr||(Lr={}));var Is;(function(t){t[t.SUNDAY=0]="SUNDAY",t[t.MONDAY=1]="MONDAY",t[t.TUESDAY=2]="TUESDAY",t[t.WEDNESDAY=3]="WEDNESDAY",t[t.THURSDAY=4]="THURSDAY",t[t.FRIDAY=5]="FRIDAY",t[t.SATURDAY=6]="SATURDAY"})(Is||(Is={}));var uf;(function(t){t[t.JANUARY=1]="JANUARY",t[t.FEBRUARY=2]="FEBRUARY",t[t.MARCH=3]="MARCH",t[t.APRIL=4]="APRIL",t[t.MAY=5]="MAY",t[t.JUNE=6]="JUNE",t[t.JULY=7]="JULY",t[t.AUGUST=8]="AUGUST",t[t.SEPTEMBER=9]="SEPTEMBER",t[t.OCTOBER=10]="OCTOBER",t[t.NOVEMBER=11]="NOVEMBER",t[t.DECEMBER=12]="DECEMBER"})(uf||(uf={}));function NYe(t,e){e=e.add(1,"day"),sP(t,e),uR(t,e)}function dh(t,e){t.assign("day",e.date()),t.assign("month",e.month()+1),t.assign("year",e.year())}function a9(t,e){t.assign("hour",e.hour()),t.assign("minute",e.minute()),t.assign("second",e.second()),t.assign("millisecond",e.millisecond()),t.get("hour")<12?t.assign("meridiem",Lr.AM):t.assign("meridiem",Lr.PM)}function sP(t,e){t.imply("day",e.date()),t.imply("month",e.month()+1),t.imply("year",e.year())}function uR(t,e){t.imply("hour",e.hour()),t.imply("minute",e.minute()),t.imply("second",e.second()),t.imply("millisecond",e.millisecond())}var hxe=N(i_(),1);var M4t={ACDT:630,ACST:570,ADT:-180,AEDT:660,AEST:600,AFT:270,AKDT:-480,AKST:-540,ALMT:360,AMST:-180,AMT:-240,ANAST:720,ANAT:720,AQTT:300,ART:-180,AST:-240,AWDT:540,AWST:480,AZOST:0,AZOT:-60,AZST:300,AZT:240,BNT:480,BOT:-240,BRST:-120,BRT:-180,BST:60,BTT:360,CAST:480,CAT:120,CCT:390,CDT:-300,CEST:120,CET:{timezoneOffsetDuringDst:2*60,timezoneOffsetNonDst:60,dstStart:t=>OYe(t,uf.MARCH,Is.SUNDAY,2),dstEnd:t=>OYe(t,uf.OCTOBER,Is.SUNDAY,3)},CHADT:825,CHAST:765,CKT:-600,CLST:-180,CLT:-240,COT:-300,CST:-360,CT:{timezoneOffsetDuringDst:-5*60,timezoneOffsetNonDst:-6*60,dstStart:t=>s_(t,uf.MARCH,Is.SUNDAY,2,2),dstEnd:t=>s_(t,uf.NOVEMBER,Is.SUNDAY,1,2)},CVT:-60,CXT:420,ChST:600,DAVT:420,EASST:-300,EAST:-360,EAT:180,ECT:-300,EDT:-240,EEST:180,EET:120,EGST:0,EGT:-60,EST:-300,ET:{timezoneOffsetDuringDst:-4*60,timezoneOffsetNonDst:-5*60,dstStart:t=>s_(t,uf.MARCH,Is.SUNDAY,2,2),dstEnd:t=>s_(t,uf.NOVEMBER,Is.SUNDAY,1,2)},FJST:780,FJT:720,FKST:-180,FKT:-240,FNT:-120,GALT:-360,GAMT:-540,GET:240,GFT:-180,GILT:720,GMT:0,GST:240,GYT:-240,HAA:-180,HAC:-300,HADT:-540,HAE:-240,HAP:-420,HAR:-360,HAST:-600,HAT:-90,HAY:-480,HKT:480,HLV:-210,HNA:-240,HNC:-360,HNE:-300,HNP:-480,HNR:-420,HNT:-150,HNY:-540,HOVT:420,ICT:420,IDT:180,IOT:360,IRDT:270,IRKST:540,IRKT:540,IRST:210,IST:330,JST:540,KGT:360,KRAST:480,KRAT:480,KST:540,KUYT:240,LHDT:660,LHST:630,LINT:840,MAGST:720,MAGT:720,MART:-510,MAWT:300,MDT:-360,MESZ:120,MEZ:60,MHT:720,MMT:390,MSD:240,MSK:180,MST:-420,MT:{timezoneOffsetDuringDst:-6*60,timezoneOffsetNonDst:-7*60,dstStart:t=>s_(t,uf.MARCH,Is.SUNDAY,2,2),dstEnd:t=>s_(t,uf.NOVEMBER,Is.SUNDAY,1,2)},MUT:240,MVT:300,MYT:480,NCT:660,NDT:-90,NFT:690,NOVST:420,NOVT:360,NPT:345,NST:-150,NUT:-660,NZDT:780,NZST:720,OMSST:420,OMST:420,PDT:-420,PET:-300,PETST:720,PETT:720,PGT:600,PHOT:780,PHT:480,PKT:300,PMDT:-120,PMST:-180,PONT:660,PST:-480,PT:{timezoneOffsetDuringDst:-7*60,timezoneOffsetNonDst:-8*60,dstStart:t=>s_(t,uf.MARCH,Is.SUNDAY,2,2),dstEnd:t=>s_(t,uf.NOVEMBER,Is.SUNDAY,1,2)},PWT:540,PYST:-180,PYT:-240,RET:240,SAMT:240,SAST:120,SBT:660,SCT:240,SGT:480,SRT:-180,SST:-660,TAHT:-600,TFT:300,TJT:300,TKT:780,TLT:540,TMT:300,TVT:720,ULAT:480,UTC:0,UYST:-120,UYT:-180,UZT:300,VET:-210,VLAST:660,VLAT:660,VUT:660,WAST:120,WAT:60,WEST:60,WESZ:60,WET:0,WEZ:0,WFT:720,WGST:-120,WGT:-180,WIB:420,WIT:540,WITA:480,WST:780,WT:0,YAKST:600,YAKT:600,YAPT:600,YEKST:360,YEKT:360};function s_(t,e,n,r,o=0){let i=0,s=0;for(;s<r;)i++,new Date(t,e-1,i).getDay()===n&&s++;return new Date(t,e-1,i,o)}function OYe(t,e,n,r=0){let o=n===0?7:n,i=new Date(t,e-1+1,1,12),s=i.getDay()===0?7:i.getDay(),a;return s===o?a=7:s<o?a=7+s-o:a=s-o,i.setDate(i.getDate()-a),new Date(t,e-1,i.getDate(),r)}function l9(t,e,n={}){if(t==null)return null;if(typeof t=="number")return t;let r=n[t]??M4t[t];return r==null?null:typeof r=="number"?r:e==null?null:(0,hxe.default)(e).isAfter(r.dstStart(e.getFullYear()))&&!(0,hxe.default)(e).isAfter(r.dstEnd(e.getFullYear()))?r.timezoneOffsetDuringDst:r.timezoneOffsetNonDst}_z.default.extend(RYe.default);var a_=class{constructor(e){e=e??new Date,e instanceof Date?this.instant=e:(this.instant=e.instant??new Date,this.timezoneOffset=l9(e.timezone,this.instant))}getDateWithAdjustedTimezone(){return new Date(this.instant.getTime()+this.getSystemTimezoneAdjustmentMinute(this.instant)*6e4)}getSystemTimezoneAdjustmentMinute(e,n){(!e||e.getTime()<0)&&(e=new Date);let r=-e.getTimezoneOffset(),o=n??this.timezoneOffset??r;return r-o}},Dr=class t{constructor(e,n){if(this._tags=new Set,this.reference=e,this.knownValues={},this.impliedValues={},n)for(let o in n)this.knownValues[o]=n[o];let r=(0,_z.default)(e.instant);this.imply("day",r.date()),this.imply("month",r.month()+1),this.imply("year",r.year()),this.imply("hour",12),this.imply("minute",0),this.imply("second",0),this.imply("millisecond",0)}get(e){return e in this.knownValues?this.knownValues[e]:e in this.impliedValues?this.impliedValues[e]:null}isCertain(e){return e in this.knownValues}getCertainComponents(){return Object.keys(this.knownValues)}imply(e,n){return e in this.knownValues?this:(this.impliedValues[e]=n,this)}assign(e,n){return this.knownValues[e]=n,delete this.impliedValues[e],this}delete(e){delete this.knownValues[e],delete this.impliedValues[e]}clone(){let e=new t(this.reference);e.knownValues={},e.impliedValues={};for(let n in this.knownValues)e.knownValues[n]=this.knownValues[n];for(let n in this.impliedValues)e.impliedValues[n]=this.impliedValues[n];return e}isOnlyDate(){return!this.isCertain("hour")&&!this.isCertain("minute")&&!this.isCertain("second")}isOnlyTime(){return!this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")&&!this.isCertain("year")}isOnlyWeekdayComponent(){return this.isCertain("weekday")&&!this.isCertain("day")&&!this.isCertain("month")}isDateWithUnknownYear(){return this.isCertain("month")&&!this.isCertain("year")}isValidDate(){let e=this.dateWithoutTimezoneAdjustment();return!(e.getFullYear()!==this.get("year")||e.getMonth()!==this.get("month")-1||e.getDate()!==this.get("day")||this.get("hour")!=null&&e.getHours()!=this.get("hour")||this.get("minute")!=null&&e.getMinutes()!=this.get("minute"))}toString(){return`[ParsingComponents {
            tags: ${JSON.stringify(Array.from(this._tags).sort())}, 
            knownValues: ${JSON.stringify(this.knownValues)}, 
            impliedValues: ${JSON.stringify(this.impliedValues)}}, 
            reference: ${JSON.stringify(this.reference)}]`}dayjs(){return(0,_z.default)(this.date())}date(){let e=this.dateWithoutTimezoneAdjustment(),n=this.reference.getSystemTimezoneAdjustmentMinute(e,this.get("timezoneOffset"));return new Date(e.getTime()+n*6e4)}addTag(e){return this._tags.add(e),this}addTags(e){for(let n of e)this._tags.add(n);return this}tags(){return new Set(this._tags)}dateWithoutTimezoneAdjustment(){let e=new Date(this.get("year"),this.get("month")-1,this.get("day"),this.get("hour"),this.get("minute"),this.get("second"),this.get("millisecond"));return e.setFullYear(this.get("year")),e}static createRelativeFromReference(e,n){let r=(0,_z.default)(e.instant);for(let i in n)r=r.add(n[i],i);let o=new t(e);return n.hour||n.minute||n.second?(a9(o,r),dh(o,r),e.timezoneOffset!==null&&o.assign("timezoneOffset",-e.instant.getTimezoneOffset())):(uR(o,r),e.timezoneOffset!==null&&o.imply("timezoneOffset",-e.instant.getTimezoneOffset()),n.d?(o.assign("day",r.date()),o.assign("month",r.month()+1),o.assign("year",r.year())):n.week?(o.assign("day",r.date()),o.assign("month",r.month()+1),o.assign("year",r.year()),o.imply("weekday",r.day())):(o.imply("day",r.date()),n.month?(o.assign("month",r.month()+1),o.assign("year",r.year())):(o.imply("month",r.month()+1),n.year?o.assign("year",r.year()):o.imply("year",r.year())))),o}},Tv=class t{constructor(e,n,r,o,i){this.reference=e,this.refDate=e.instant,this.index=n,this.text=r,this.start=o||new Dr(e),this.end=i}clone(){let e=new t(this.reference,this.index,this.text);return e.start=this.start?this.start.clone():null,e.end=this.end?this.end.clone():null,e}date(){return this.start.date()}tags(){let e=new Set(this.start.tags());if(this.end)for(let n of this.end.tags())e.add(n);return e}toString(){let e=Array.from(this.tags()).sort();return`[ParsingResult {index: ${this.index}, text: '${this.text}', tags: ${JSON.stringify(e)} ...}]`}};function gxe(t,e,n="\\s{0,5},?\\s{0,5}"){let r=e.replace(/\((?!\?)/g,"(?:");return`${t}${r}(?:${n}${r}){0,10}`}function N4t(t){let e;return t instanceof Array?e=[...t]:t instanceof Map?e=Array.from(t.keys()):e=Object.keys(t),e}function kl(t){return`(?:${N4t(t).sort((n,r)=>r.length-n.length).join("|").replace(/\./g,"\\.")})`}var LYe=N(i_(),1);function c9(t){return t<100&&(t>50?t=t+1900:t=t+2e3),t}function l_(t,e,n){let r=(0,LYe.default)(t),o=r;o=o.month(n-1),o=o.date(e),o=o.year(r.year());let i=o.add(1,"y"),s=o.add(-1,"y");return Math.abs(i.diff(r))<Math.abs(o.diff(r))?o=i:Math.abs(s.diff(r))<Math.abs(o.diff(r))&&(o=s),o.year()}var vxe={sunday:0,sun:0,"sun.":0,monday:1,mon:1,"mon.":1,tuesday:2,tue:2,"tue.":2,wednesday:3,wed:3,"wed.":3,thursday:4,thurs:4,"thurs.":4,thur:4,"thur.":4,thu:4,"thu.":4,friday:5,fri:5,"fri.":5,saturday:6,sat:6,"sat.":6},xxe={january:1,february:2,march:3,april:4,may:5,june:6,july:7,august:8,september:9,october:10,november:11,december:12},Op={...xxe,jan:1,"jan.":1,feb:2,"feb.":2,mar:3,"mar.":3,apr:4,"apr.":4,jun:6,"jun.":6,jul:7,"jul.":7,aug:8,"aug.":8,sep:9,"sep.":9,sept:9,"sept.":9,oct:10,"oct.":10,nov:11,"nov.":11,dec:12,"dec.":12},yxe={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12},wxe={first:1,second:2,third:3,fourth:4,fifth:5,sixth:6,seventh:7,eighth:8,ninth:9,tenth:10,eleventh:11,twelfth:12,thirteenth:13,fourteenth:14,fifteenth:15,sixteenth:16,seventeenth:17,eighteenth:18,nineteenth:19,twentieth:20,"twenty first":21,"twenty-first":21,"twenty second":22,"twenty-second":22,"twenty third":23,"twenty-third":23,"twenty fourth":24,"twenty-fourth":24,"twenty fifth":25,"twenty-fifth":25,"twenty sixth":26,"twenty-sixth":26,"twenty seventh":27,"twenty-seventh":27,"twenty eighth":28,"twenty-eighth":28,"twenty ninth":29,"twenty-ninth":29,thirtieth:30,"thirty first":31,"thirty-first":31},$Ye={second:"second",seconds:"second",minute:"minute",minutes:"minute",hour:"hour",hours:"hour",day:"d",days:"d",week:"week",weeks:"week",month:"month",months:"month",quarter:"quarter",quarters:"quarter",year:"year",years:"year"},Sz={s:"second",sec:"second",second:"second",seconds:"second",m:"minute",min:"minute",mins:"minute",minute:"minute",minutes:"minute",h:"hour",hr:"hour",hrs:"hour",hour:"hour",hours:"hour",d:"d",day:"d",days:"d",w:"w",week:"week",weeks:"week",mo:"month",mon:"month",mos:"month",month:"month",months:"month",qtr:"quarter",quarter:"quarter",quarters:"quarter",y:"year",yr:"year",year:"year",years:"year",...$Ye},FYe=`(?:${kl(yxe)}|[0-9]+|[0-9]+\\.[0-9]+|half(?:\\s{0,2}an?)?|an?\\b(?:\\s{0,2}few)?|few|several|the|a?\\s{0,2}couple\\s{0,2}(?:of)?)`;function O4t(t){let e=t.toLowerCase();return yxe[e]!==void 0?yxe[e]:e==="a"||e==="an"||e=="the"?1:e.match(/few/)?3:e.match(/half/)?.5:e.match(/couple/)?2:e.match(/several/)?7:parseFloat(e)}var dR=`(?:${kl(wxe)}|[0-9]{1,2}(?:st|nd|rd|th)?)`;function fR(t){let e=t.toLowerCase();return wxe[e]!==void 0?wxe[e]:(e=e.replace(/(?:st|nd|rd|th)$/i,""),parseInt(e))}var c_="(?:[1-9][0-9]{0,3}\\s{0,2}(?:BE|AD|BC|BCE|CE)|[1-2][0-9]{3}|[5-9][0-9]|2[0-5])";function u_(t){if(/BE/i.test(t))return t=t.replace(/BE/i,""),parseInt(t)-543;if(/BCE?/i.test(t))return t=t.replace(/BCE?/i,""),-parseInt(t);if(/(AD|CE)/i.test(t))return t=t.replace(/(AD|CE)/i,""),parseInt(t);let e=parseInt(t);return c9(e)}var UYe=`(${FYe})\\s{0,3}(${kl(Sz)})`,DYe=new RegExp(UYe,"i"),R4t=`(${FYe})\\s{0,3}(${kl($Ye)})`,BYe="\\s{0,5},?(?:\\s*and)?\\s{0,5}",Iv=gxe("(?:(?:about|around)\\s{0,3})?",UYe,BYe),d_=gxe("(?:(?:about|around)\\s{0,3})?",R4t,BYe);function Rp(t){let e={},n=t,r=DYe.exec(n);for(;r;)L4t(e,r),n=n.substring(r[0].length).trim(),r=DYe.exec(n);return Object.keys(e).length==0?null:e}function L4t(t,e){if(e[0].match(/^[a-zA-Z]+$/))return;let n=O4t(e[1]),r=Sz[e[2].toLowerCase()];t[r]=n}var so=class{constructor(){this.cachedInnerPattern=null,this.cachedPattern=null}innerPatternHasChange(e,n){return this.innerPattern(e)!==n}patternLeftBoundary(){return"(\\W|^)"}pattern(e){return this.cachedInnerPattern&&!this.innerPatternHasChange(e,this.cachedInnerPattern)?this.cachedPattern:(this.cachedInnerPattern=this.innerPattern(e),this.cachedPattern=new RegExp(`${this.patternLeftBoundary()}${this.cachedInnerPattern.source}`,this.cachedInnerPattern.flags),this.cachedPattern)}extract(e,n){let r=n[1]??"";n.index=n.index+r.length,n[0]=n[0].substring(r.length);for(let o=2;o<n.length;o++)n[o-1]=n[o];return this.innerExtract(e,n)}};var D4t=new RegExp(`(?:(?:within|in|for)\\s*)?(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Iv})(?=\\W|$)`,"i"),$4t=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${Iv})(?=\\W|$)`,"i"),F4t=new RegExp(`(?:within|in|for)\\s*(?:(?:about|around|roughly|approximately|just)\\s*(?:~\\s*)?)?(${d_})(?=\\W|$)`,"i"),Tz=class extends so{constructor(e){super(),this.strictMode=e}innerPattern(e){return this.strictMode?F4t:e.option.forwardDate?D4t:$4t}innerExtract(e,n){if(n[0].match(/^for\s*the\s*\w+/))return null;let r=Rp(n[1]);return r?Dr.createRelativeFromReference(e.reference,r):null}};var U4t=new RegExp(`(?:on\\s{0,3})?(${dR})(?:\\s{0,3}(?:to|\\-|\\\u2013|until|through|till)?\\s{0,3}(${dR}))?(?:-|/|\\s{0,3}(?:of)?\\s{0,3})(${kl(Op)})(?:(?:-|/|,?\\s{0,3})(${c_}(?!\\w)))?(?=\\W|$)`,"i"),zYe=1,jYe=2,B4t=3,VYe=4,Iz=class extends so{innerPattern(){return U4t}innerExtract(e,n){let r=e.createParsingResult(n.index,n[0]),o=Op[n[B4t].toLowerCase()],i=fR(n[zYe]);if(i>31)return n.index=n.index+n[zYe].length,null;if(r.start.assign("month",o),r.start.assign("day",i),n[VYe]){let s=u_(n[VYe]);r.start.assign("year",s)}else{let s=l_(e.refDate,i,o);r.start.imply("year",s)}if(n[jYe]){let s=fR(n[jYe]);r.end=r.start.clone(),r.end.assign("day",s)}return r}};var z4t=new RegExp(`(${kl(Op)})(?:-|/|\\s*,?\\s*)(${dR})(?!\\s*(?:am|pm))\\s*(?:(?:to|\\-)\\s*(${dR})\\s*)?(?:(?:-|/|\\s*,\\s*|\\s+)(${c_}))?(?=\\W|$)(?!\\:\\d)`,"i"),j4t=1,WYe=2,bxe=3,Cxe=4,Pz=class extends so{constructor(e){super(),this.shouldSkipYearLikeDate=e}innerPattern(){return z4t}innerExtract(e,n){let r=Op[n[j4t].toLowerCase()],o=fR(n[WYe]);if(o>31||this.shouldSkipYearLikeDate&&!n[bxe]&&!n[Cxe]&&n[WYe].match(/^2[0-5]$/))return null;let i=e.createParsingComponents({day:o,month:r}).addTag("parser/ENMonthNameMiddleEndianParser");if(n[Cxe]){let l=u_(n[Cxe]);i.assign("year",l)}else{let l=l_(e.refDate,o,r);i.imply("year",l)}if(!n[bxe])return i;let s=fR(n[bxe]),a=e.createParsingResult(n.index,n[0]);return a.start=i,a.end=i.clone(),a.end.assign("day",s),a}};var V4t=new RegExp(`((?:in)\\s*)?(${kl(Op)})\\s*(?:[,-]?\\s*(${c_})?)?(?=[^\\s\\w]|\\s+[^0-9]|\\s+$|$)`,"i"),W4t=1,H4t=2,HYe=3,Ez=class extends so{innerPattern(){return V4t}innerExtract(e,n){let r=n[H4t].toLowerCase();if(n[0].length<=3&&!xxe[r])return null;let o=e.createParsingResult(n.index+(n[W4t]||"").length,n.index+n[0].length);o.start.imply("day",1),o.start.addTag("parser/ENMonthNameParser");let i=Op[r];if(o.start.assign("month",i),n[HYe]){let s=u_(n[HYe]);o.start.assign("year",s)}else{let s=l_(e.refDate,1,i);o.start.imply("year",s)}return o}};var K4t=new RegExp(`([0-9]{4})[-\\.\\/\\s](?:(${kl(Op)})|([0-9]{1,2}))[-\\.\\/\\s]([0-9]{1,2})(?=\\W|$)`,"i"),q4t=1,G4t=2,KYe=3,Y4t=4,Az=class extends so{constructor(e){super(),this.strictMonthDateOrder=e}innerPattern(){return K4t}innerExtract(e,n){let r=parseInt(n[q4t]),o=parseInt(n[Y4t]),i=n[KYe]?parseInt(n[KYe]):Op[n[G4t].toLowerCase()];if(i<1||i>12){if(this.strictMonthDateOrder)return null;o>=1&&o<=12&&([i,o]=[o,i])}return o<1||o>31?null:{day:o,month:i,year:r}}};var Z4t=new RegExp("([0-9]|0[1-9]|1[012])/([0-9]{4})","i"),J4t=1,X4t=2,kz=class extends so{innerPattern(){return Z4t}innerExtract(e,n){let r=parseInt(n[X4t]),o=parseInt(n[J4t]);return e.createParsingComponents().imply("day",1).assign("month",o).assign("year",r)}};function Q4t(t,e,n,r){return new RegExp(`${t}${e}(\\d{1,4})(?:(?:\\.|:|\uFF1A)(\\d{1,2})(?:(?::|\uFF1A)(\\d{2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${n}`,r)}function eVt(t,e){return new RegExp(`^(${t})(\\d{1,4})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:(?:\\.|\\:|\\\uFF1A)(\\d{1,2})(?:\\.(\\d{1,6}))?)?)?(?:\\s*(a\\.m\\.|p\\.m\\.|am?|pm?))?${e}`,"i")}var qYe=2,pR=3,u9=4,d9=5,Mz=6,f9=class{constructor(e=!1){this.cachedPrimaryPrefix=null,this.cachedPrimarySuffix=null,this.cachedPrimaryTimePattern=null,this.cachedFollowingPhase=null,this.cachedFollowingSuffix=null,this.cachedFollowingTimePatten=null,this.strictMode=e}patternFlags(){return"i"}primaryPatternLeftBoundary(){return"(^|\\s|T|\\b)"}primarySuffix(){return"(?!/)(?=\\W|$)"}followingSuffix(){return"(?!/)(?=\\W|$)"}pattern(e){return this.getPrimaryTimePatternThroughCache()}extract(e,n){let r=this.extractPrimaryTimeComponents(e,n);if(!r)return n[0].match(/^\d{4}/)?(n.index+=4,null):(n.index+=n[0].length,null);let o=n.index+n[1].length,i=n[0].substring(n[1].length),s=e.createParsingResult(o,i,r);n.index+=n[0].length;let a=e.text.substring(n.index),c=this.getFollowingTimePatternThroughCache().exec(a);return i.match(/^\d{3,4}/)&&c&&(c[0].match(/^\s*([+-])\s*\d{2,4}$/)||c[0].match(/^\s*([+-])\s*\d{2}\W\d{2}/))?null:!c||c[0].match(/^\s*([+-])\s*\d{3,4}$/)?this.checkAndReturnWithoutFollowingPattern(s):(s.end=this.extractFollowingTimeComponents(e,c,s),s.end&&(s.text+=c[0]),this.checkAndReturnWithFollowingPattern(s))}extractPrimaryTimeComponents(e,n,r=!1){let o=e.createParsingComponents(),i=0,s=null,a=parseInt(n[qYe]);if(a>100){if(this.strictMode||n[pR]!=null)return null;i=a%100,a=Math.floor(a/100)}if(a>24)return null;if(n[pR]!=null){if(n[pR].length==1&&!n[Mz])return null;i=parseInt(n[pR])}if(i>=60)return null;if(a>12&&(s=Lr.PM),n[Mz]!=null){if(a>12)return null;let l=n[Mz][0].toLowerCase();l=="a"&&(s=Lr.AM,a==12&&(a=0)),l=="p"&&(s=Lr.PM,a!=12&&(a+=12))}if(o.assign("hour",a),o.assign("minute",i),s!==null?o.assign("meridiem",s):a<12?o.imply("meridiem",Lr.AM):o.imply("meridiem",Lr.PM),n[d9]!=null){let l=parseInt(n[d9].substring(0,3));if(l>=1e3)return null;o.assign("millisecond",l)}if(n[u9]!=null){let l=parseInt(n[u9]);if(l>=60)return null;o.assign("second",l)}return o}extractFollowingTimeComponents(e,n,r){let o=e.createParsingComponents();if(n[d9]!=null){let l=parseInt(n[d9].substring(0,3));if(l>=1e3)return null;o.assign("millisecond",l)}if(n[u9]!=null){let l=parseInt(n[u9]);if(l>=60)return null;o.assign("second",l)}let i=parseInt(n[qYe]),s=0,a=-1;if(n[pR]!=null?s=parseInt(n[pR]):i>100&&(s=i%100,i=Math.floor(i/100)),s>=60||i>24)return null;if(i>=12&&(a=Lr.PM),n[Mz]!=null){if(i>12)return null;let l=n[Mz][0].toLowerCase();l=="a"&&(a=Lr.AM,i==12&&(i=0,o.isCertain("day")||o.imply("day",o.get("day")+1))),l=="p"&&(a=Lr.PM,i!=12&&(i+=12)),r.start.isCertain("meridiem")||(a==Lr.AM?(r.start.imply("meridiem",Lr.AM),r.start.get("hour")==12&&r.start.assign("hour",0)):(r.start.imply("meridiem",Lr.PM),r.start.get("hour")!=12&&r.start.assign("hour",r.start.get("hour")+12)))}return o.assign("hour",i),o.assign("minute",s),a>=0?o.assign("meridiem",a):r.start.isCertain("meridiem")&&r.start.get("hour")>12?r.start.get("hour")-12>i?o.imply("meridiem",Lr.AM):i<=12&&(o.assign("hour",i+12),o.assign("meridiem",Lr.PM)):i>12?o.imply("meridiem",Lr.PM):i<=12&&o.imply("meridiem",Lr.AM),o.date().getTime()<r.start.date().getTime()&&o.imply("day",o.get("day")+1),o}checkAndReturnWithoutFollowingPattern(e){if(e.text.match(/^\d$/)||e.text.match(/^\d\d\d+$/)||e.text.match(/\d[apAP]$/))return null;let n=e.text.match(/[^\d:.](\d[\d.]+)$/);if(n){let r=n[1];if(this.strictMode||r.includes(".")&&!r.match(/\d(\.\d{2})+$/)||parseInt(r)>24)return null}return e}checkAndReturnWithFollowingPattern(e){if(e.text.match(/^\d+-\d+$/))return null;let n=e.text.match(/[^\d:.](\d[\d.]+)\s*-\s*(\d[\d.]+)$/);if(n){if(this.strictMode)return null;let r=n[1],o=n[2];if(o.includes(".")&&!o.match(/\d(\.\d{2})+$/))return null;let i=parseInt(o),s=parseInt(r);if(i>24||s>24)return null}return e}getPrimaryTimePatternThroughCache(){let e=this.primaryPrefix(),n=this.primarySuffix();return this.cachedPrimaryPrefix===e&&this.cachedPrimarySuffix===n?this.cachedPrimaryTimePattern:(this.cachedPrimaryTimePattern=Q4t(this.primaryPatternLeftBoundary(),e,n,this.patternFlags()),this.cachedPrimaryPrefix=e,this.cachedPrimarySuffix=n,this.cachedPrimaryTimePattern)}getFollowingTimePatternThroughCache(){let e=this.followingPhase(),n=this.followingSuffix();return this.cachedFollowingPhase===e&&this.cachedFollowingSuffix===n?this.cachedFollowingTimePatten:(this.cachedFollowingTimePatten=eVt(e,n),this.cachedFollowingPhase=e,this.cachedFollowingSuffix=n,this.cachedFollowingTimePatten)}};var Nz=class extends f9{constructor(e){super(e)}followingPhase(){return"\\s*(?:\\-|\\\u2013|\\~|\\\u301C|to|until|through|till|\\?)\\s*"}primaryPrefix(){return"(?:(?:at|from)\\s*)??"}primarySuffix(){return"(?:\\s*(?:o\\W*clock|at\\s*night|in\\s*the\\s*(?:morning|afternoon)))?(?!/)(?=\\W|$)"}extractPrimaryTimeComponents(e,n){let r=super.extractPrimaryTimeComponents(e,n);if(!r)return r;if(n[0].endsWith("night")){let o=r.get("hour");o>=6&&o<12?(r.assign("hour",r.get("hour")+12),r.assign("meridiem",Lr.PM)):o<6&&r.assign("meridiem",Lr.AM)}if(n[0].endsWith("afternoon")){r.assign("meridiem",Lr.PM);let o=r.get("hour");o>=0&&o<=6&&r.assign("hour",r.get("hour")+12)}return n[0].endsWith("morning")&&(r.assign("meridiem",Lr.AM),r.get("hour")<12&&r.assign("hour",r.get("hour"))),r.addTag("parser/ENTimeExpressionParser")}};function f_(t){let e={};for(let n in t)e[n]=-t[n];return e}function GYe(t,e){let n=t.clone(),r=t.dayjs();for(let o in e)r=r.add(e[o],o);return("day"in e||"d"in e||"week"in e||"month"in e||"year"in e)&&(n.imply("day",r.date()),n.imply("month",r.month()+1),n.imply("year",r.year())),("second"in e||"minute"in e||"hour"in e)&&(n.imply("second",r.second()),n.imply("minute",r.minute()),n.imply("hour",r.hour())),n}var tVt=new RegExp(`(${Iv})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),nVt=new RegExp(`(${d_})\\s{0,5}(?:ago|before|earlier)(?=\\W|$)`,"i"),Oz=class extends so{constructor(e){super(),this.strictMode=e}innerPattern(){return this.strictMode?nVt:tVt}innerExtract(e,n){let r=Rp(n[1]);if(!r)return null;let o=f_(r);return Dr.createRelativeFromReference(e.reference,o)}};var rVt=new RegExp(`(${Iv})\\s{0,5}(?:later|after|from now|henceforth|forward|out)(?=(?:\\W|$))`,"i"),oVt=new RegExp(`(${d_})\\s{0,5}(later|after|from now)(?=\\W|$)`,"i"),iVt=1,Rz=class extends so{constructor(e){super(),this.strictMode=e}innerPattern(){return this.strictMode?oVt:rVt}innerExtract(e,n){let r=Rp(n[iVt]);return r?Dr.createRelativeFromReference(e.reference,r):null}};var p9=class{refine(e,n){return n.filter(r=>this.isValid(e,r))}},Lp=class{refine(e,n){if(n.length<2)return n;let r=[],o=n[0],i=null;for(let s=1;s<n.length;s++){i=n[s];let a=e.text.substring(o.index+o.text.length,i.index);if(!this.shouldMergeResults(a,o,i,e))r.push(o),o=i;else{let l=o,c=i,u=this.mergeResults(a,l,c,e);e.debug(()=>{console.log(`${this.constructor.name} merged ${l} and ${c} into ${u}`)}),o=u}}return o!=null&&r.push(o),r}};var Lz=class extends Lp{shouldMergeResults(e,n,r){return!n.end&&!r.end&&e.match(this.patternBetween())!=null}mergeResults(e,n,r){if(!n.start.isOnlyWeekdayComponent()&&!r.start.isOnlyWeekdayComponent()&&(r.start.getCertainComponents().forEach(i=>{n.start.isCertain(i)||n.start.imply(i,r.start.get(i))}),n.start.getCertainComponents().forEach(i=>{r.start.isCertain(i)||r.start.imply(i,n.start.get(i))})),n.start.date().getTime()>r.start.date().getTime()){let i=n.start.dayjs(),s=r.start.dayjs();r.start.isOnlyWeekdayComponent()&&s.add(7,"days").isAfter(i)?(s=s.add(7,"days"),r.start.imply("day",s.date()),r.start.imply("month",s.month()+1),r.start.imply("year",s.year())):n.start.isOnlyWeekdayComponent()&&i.add(-7,"days").isBefore(s)?(i=i.add(-7,"days"),n.start.imply("day",i.date()),n.start.imply("month",i.month()+1),n.start.imply("year",i.year())):r.start.isDateWithUnknownYear()&&s.add(1,"years").isAfter(i)?(s=s.add(1,"years"),r.start.imply("year",s.year())):n.start.isDateWithUnknownYear()&&i.add(-1,"years").isBefore(s)?(i=i.add(-1,"years"),n.start.imply("year",i.year())):[r,n]=[n,r]}let o=n.clone();return o.start=n.start,o.end=r.start,o.index=Math.min(n.index,r.index),n.index<r.index?o.text=n.text+e+r.text:o.text=r.text+e+n.text,o}};var Dz=class extends Lz{patternBetween(){return/^\s*(to|-|–|until|through|till)\s*$/i}};function _xe(t,e){let n=t.clone(),r=t.start,o=e.start;if(n.start=YYe(r,o),t.end!=null||e.end!=null){let i=t.end==null?t.start:t.end,s=e.end==null?e.start:e.end,a=YYe(i,s);if(t.end==null&&a.date().getTime()<n.start.date().getTime()){let l=a.dayjs().add(1,"day");a.isCertain("day")?dh(a,l):sP(a,l)}n.end=a}return n}function YYe(t,e){let n=t.clone();return e.isCertain("hour")?(n.assign("hour",e.get("hour")),n.assign("minute",e.get("minute")),e.isCertain("second")?(n.assign("second",e.get("second")),e.isCertain("millisecond")?n.assign("millisecond",e.get("millisecond")):n.imply("millisecond",e.get("millisecond"))):(n.imply("second",e.get("second")),n.imply("millisecond",e.get("millisecond")))):(n.imply("hour",e.get("hour")),n.imply("minute",e.get("minute")),n.imply("second",e.get("second")),n.imply("millisecond",e.get("millisecond"))),e.isCertain("timezoneOffset")&&n.assign("timezoneOffset",e.get("timezoneOffset")),e.isCertain("meridiem")?n.assign("meridiem",e.get("meridiem")):e.get("meridiem")!=null&&n.get("meridiem")==null&&n.imply("meridiem",e.get("meridiem")),n.get("meridiem")==Lr.PM&&n.get("hour")<12&&(e.isCertain("hour")?n.assign("hour",n.get("hour")+12):n.imply("hour",n.get("hour")+12)),n.addTags(t.tags()),n.addTags(e.tags()),n}var $z=class extends Lp{shouldMergeResults(e,n,r){return(n.start.isOnlyDate()&&r.start.isOnlyTime()||r.start.isOnlyDate()&&n.start.isOnlyTime())&&e.match(this.patternBetween())!=null}mergeResults(e,n,r){let o=n.start.isOnlyDate()?_xe(n,r):_xe(r,n);return o.index=n.index,o.text=n.text+e+r.text,o}};var mR=class extends $z{patternBetween(){return new RegExp("^\\s*(T|at|after|before|on|of|,|-|\\.|\u2219|:)?\\s*$")}};var sVt=new RegExp("^\\s*,?\\s*\\(?([A-Z]{2,4})\\)?(?=\\W|$)","i"),Fz=class{constructor(e){this.timezoneOverrides=e}refine(e,n){let r=e.option.timezones??{};return n.forEach(o=>{let i=e.text.substring(o.index+o.text.length),s=sVt.exec(i);if(!s)return;let a=s[1].toUpperCase(),l=o.start.date()??o.refDate??new Date,c={...this.timezoneOverrides,...r},u=l9(a,l,c);if(u==null)return;e.debug(()=>{console.log(`Extracting timezone: '${a}' into: ${u} for: ${o.start}`)});let d=o.start.get("timezoneOffset");d!==null&&u!=d&&(o.start.isCertain("timezoneOffset")||a!=s[1])||o.start.isOnlyDate()&&a!=s[1]||(o.text+=s[0],o.start.isCertain("timezoneOffset")||o.start.assign("timezoneOffset",u),o.end!=null&&!o.end.isCertain("timezoneOffset")&&o.end.assign("timezoneOffset",u))}),n}};var aVt=new RegExp("^\\s*(?:\\(?(?:GMT|UTC)\\s?)?([+-])(\\d{1,2})(?::?(\\d{2}))?\\)?","i"),lVt=1,cVt=2,uVt=3,Uz=class{refine(e,n){return n.forEach(function(r){if(r.start.isCertain("timezoneOffset"))return;let o=e.text.substring(r.index+r.text.length),i=aVt.exec(o);if(!i)return;e.debug(()=>{console.log(`Extracting timezone: '${i[0]}' into : ${r}`)});let s=parseInt(i[cVt]),a=parseInt(i[uVt]||"0"),l=s*60+a;l>14*60||(i[lVt]==="-"&&(l=-l),r.end!=null&&r.end.assign("timezoneOffset",l),r.start.assign("timezoneOffset",l),r.text+=i[0])}),n}};var p_=class{refine(e,n){if(n.length<2)return n;let r=[],o=n[0];for(let i=1;i<n.length;i++){let s=n[i];if(s.index>=o.index+o.text.length){r.push(o),o=s;continue}let a=null,l=null;s.text.length>o.text.length?(a=s,l=o):(a=o,l=s),e.debug(()=>{console.log(`${this.constructor.name} remove ${l} by ${a}`)}),o=a}return o!=null&&r.push(o),r}};var ZYe=N(i_(),1);var Bz=class{refine(e,n){return e.option.forwardDate&&n.forEach(r=>{let o=(0,ZYe.default)(e.refDate);if(r.start.isOnlyTime()&&o.isAfter(r.start.dayjs())&&(o=o.add(1,"day"),sP(r.start,o),r.end&&r.end.isOnlyTime()&&(sP(r.end,o),r.start.dayjs().isAfter(r.end.dayjs())&&(o=o.add(1,"day"),sP(r.end,o))),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} time result (${r.start})`)})),r.start.isOnlyWeekdayComponent()&&o.isAfter(r.start.dayjs())&&(o.day()>=r.start.get("weekday")?o=o.day(r.start.get("weekday")+7):o=o.day(r.start.get("weekday")),r.start.imply("day",o.date()),r.start.imply("month",o.month()+1),r.start.imply("year",o.year()),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} weekday (${r.start})`)}),r.end&&r.end.isOnlyWeekdayComponent()&&(o.day()>r.end.get("weekday")?o=o.day(r.end.get("weekday")+7):o=o.day(r.end.get("weekday")),r.end.imply("day",o.date()),r.end.imply("month",o.month()+1),r.end.imply("year",o.year()),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} weekday (${r.end})`)}))),r.start.isDateWithUnknownYear()&&o.isAfter(r.start.dayjs()))for(let i=0;i<3&&o.isAfter(r.start.dayjs());i++)r.start.imply("year",r.start.get("year")+1),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} year (${r.start})`)}),r.end&&!r.end.isCertain("year")&&(r.end.imply("year",r.end.get("year")+1),e.debug(()=>{console.log(`${this.constructor.name} adjusted ${r} month (${r.start})`)}))}),n}};var zz=class extends p9{constructor(e){super(),this.strictMode=e}isValid(e,n){return n.text.replace(" ","").match(/^\d*(\.\d*)?$/)?(e.debug(()=>{console.log(`Removing unlikely result '${n.text}'`)}),!1):n.start.isValidDate()?n.end&&!n.end.isValidDate()?(e.debug(()=>{console.log(`Removing invalid result: ${n} (${n.end})`)}),!1):this.strictMode?this.isStrictModeValid(e,n):!0:(e.debug(()=>{console.log(`Removing invalid result: ${n} (${n.start})`)}),!1)}isStrictModeValid(e,n){return n.start.isOnlyWeekdayComponent()?(e.debug(()=>{console.log(`(Strict) Removing weekday only component: ${n} (${n.end})`)}),!1):n.start.isOnlyTime()&&(!n.start.isCertain("hour")||!n.start.isCertain("minute"))?(e.debug(()=>{console.log(`(Strict) Removing uncertain time component: ${n} (${n.end})`)}),!1):!0}};var dVt=new RegExp("([0-9]{4})\\-([0-9]{1,2})\\-([0-9]{1,2})(?:T([0-9]{1,2}):([0-9]{1,2})(?::([0-9]{1,2})(?:\\.(\\d{1,4}))?)?(Z|([+-]\\d{2}):?(\\d{2})?)?)?(?=\\W|$)","i"),fVt=1,pVt=2,mVt=3,JYe=4,hVt=5,XYe=6,QYe=7,gVt=8,eZe=9,tZe=10,jz=class extends so{innerPattern(){return dVt}innerExtract(e,n){let r=e.createParsingComponents({year:parseInt(n[fVt]),month:parseInt(n[pVt]),day:parseInt(n[mVt])});if(n[JYe]!=null&&(r.assign("hour",parseInt(n[JYe])),r.assign("minute",parseInt(n[hVt])),n[XYe]!=null&&r.assign("second",parseInt(n[XYe])),n[QYe]!=null&&r.assign("millisecond",parseInt(n[QYe])),n[gVt]!=null)){let o=0;if(n[eZe]){let i=parseInt(n[eZe]),s=0;n[tZe]!=null&&(s=parseInt(n[tZe])),o=i*60,o<0?o-=s:o+=s}r.assign("timezoneOffset",o)}return r.addTag("parser/ISOFormatParser")}};var Vz=class extends Lp{mergeResults(e,n,r){let o=r.clone();return o.index=n.index,o.text=n.text+e+o.text,o.start.assign("weekday",n.start.get("weekday")),o.end&&o.end.assign("weekday",n.start.get("weekday")),o}shouldMergeResults(e,n,r){return n.start.isOnlyWeekdayComponent()&&!n.start.isCertain("hour")&&r.start.isCertain("day")&&e.match(/^,?\s*$/)!=null}};function nZe(t,e=!1){return t.parsers.unshift(new jz),t.refiners.unshift(new Vz),t.refiners.unshift(new Uz),t.refiners.unshift(new p_),t.refiners.push(new Fz),t.refiners.push(new p_),t.refiners.push(new Bz),t.refiners.push(new zz(e)),t}var hZe=N(i_(),1);var hR=N(i_(),1);function rZe(t){let e=(0,hR.default)(t.instant),n=new Dr(t,{});return dh(n,e),a9(n,e),t.timezoneOffset!==null&&n.assign("timezoneOffset",e.utcOffset()),n.addTag("casualReference/now"),n}function oZe(t){let e=(0,hR.default)(t.instant),n=new Dr(t,{});return dh(n,e),uR(n,e),n.addTag("casualReference/today"),n}function iZe(t){return yVt(t,1).addTag("casualReference/yesterday")}function yVt(t,e){return aZe(t,-e)}function sZe(t){return aZe(t,1).addTag("casualReference/tomorrow")}function aZe(t,e){let n=(0,hR.default)(t.instant),r=new Dr(t,{});return n=n.add(e,"day"),dh(r,n),uR(r,n),r}function lZe(t,e=22){let n=(0,hR.default)(t.instant),r=new Dr(t,{});return dh(r,n),r.imply("hour",e),r.imply("meridiem",Lr.PM),r.addTag("casualReference/tonight"),r}function cZe(t,e=20){let n=new Dr(t,{});return n.imply("meridiem",Lr.PM),n.imply("hour",e),n.addTag("casualReference/evening"),n}function uZe(t){let e=new Dr(t,{}),n=(0,hR.default)(t.instant);return n.hour()>2&&NYe(e,n),e.assign("hour",0),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/midnight"),e}function dZe(t,e=6){let n=new Dr(t,{});return n.imply("meridiem",Lr.AM),n.imply("hour",e),n.imply("minute",0),n.imply("second",0),n.imply("millisecond",0),n.addTag("casualReference/morning"),n}function fZe(t,e=15){let n=new Dr(t,{});return n.imply("meridiem",Lr.PM),n.imply("hour",e),n.imply("minute",0),n.imply("second",0),n.imply("millisecond",0),n.addTag("casualReference/afternoon"),n}function pZe(t){let e=new Dr(t,{});return e.imply("meridiem",Lr.AM),e.imply("hour",12),e.imply("minute",0),e.imply("second",0),e.imply("millisecond",0),e.addTag("casualReference/noon"),e}var wVt=/(now|today|tonight|tomorrow|tmr|tmrw|yesterday|last\s*night)(?=\W|$)/i,Wz=class extends so{innerPattern(e){return wVt}innerExtract(e,n){let r=(0,hZe.default)(e.refDate),o=n[0].toLowerCase(),i=e.createParsingComponents();switch(o){case"now":i=rZe(e.reference);break;case"today":i=oZe(e.reference);break;case"yesterday":i=iZe(e.reference);break;case"tomorrow":case"tmr":case"tmrw":i=sZe(e.reference);break;case"tonight":i=lZe(e.reference);break;default:o.match(/last\s*night/)&&(r.hour()>6&&(r=r.add(-1,"day")),dh(i,r),i.imply("hour",0));break}return i.addTag("parser/ENCasualDateParser"),i}};var vVt=/(?:this)?\s{0,3}(morning|afternoon|evening|night|midnight|midday|noon)(?=\W|$)/i,Hz=class extends so{innerPattern(){return vVt}innerExtract(e,n){let r=null;switch(n[1].toLowerCase()){case"afternoon":r=fZe(e.reference);break;case"evening":case"night":r=cZe(e.reference);break;case"midnight":r=uZe(e.reference);break;case"morning":r=dZe(e.reference);break;case"noon":case"midday":r=pZe(e.reference);break}return r&&r.addTag("parser/ENCasualTimeParser"),r}};function gZe(t,e,n){let r=t.getDateWithAdjustedTimezone(),o=xVt(r,e,n),i=new Dr(t);return i=GYe(i,{day:o}),i.assign("weekday",e),i}function xVt(t,e,n){let r=t.getDay();switch(n){case"this":return m9(t,e);case"last":return yZe(t,e);case"next":return r==Is.SUNDAY?e==Is.SUNDAY?7:e:r==Is.SATURDAY?e==Is.SATURDAY?7:e==Is.SUNDAY?8:1+e:e<r&&e!=Is.SUNDAY?m9(t,e):m9(t,e)+7}return bVt(t,e)}function bVt(t,e){let n=yZe(t,e),r=m9(t,e);return r<-n?r:n}function m9(t,e){let n=t.getDay(),r=e-n;return r<0&&(r+=7),r}function yZe(t,e){let n=t.getDay(),r=e-n;return r>=0&&(r-=7),r}var CVt=new RegExp(`(?:(?:\\,|\\(|\\\uFF08)\\s*)?(?:on\\s*?)?(?:(this|last|past|next)\\s*)?(${kl(vxe)})(?:\\s*(?:\\,|\\)|\\\uFF09))?(?:\\s*(this|last|past|next)\\s*week)?(?=\\W|$)`,"i"),_Vt=1,SVt=2,TVt=3,Kz=class extends so{innerPattern(){return CVt}innerExtract(e,n){let r=n[SVt].toLowerCase(),o=vxe[r],i=n[_Vt],s=n[TVt],a=i||s;a=a||"",a=a.toLowerCase();let l=null;return a=="last"||a=="past"?l="last":a=="next"?l="next":a=="this"&&(l="this"),gZe(e.reference,o,l)}};var wZe=N(i_(),1);var IVt=new RegExp(`(this|last|past|next|after\\s*this)\\s*(${kl(Sz)})(?=\\s*)(?=\\W|$)`,"i"),PVt=1,EVt=2,qz=class extends so{innerPattern(){return IVt}innerExtract(e,n){let r=n[PVt].toLowerCase(),o=n[EVt].toLowerCase(),i=Sz[o];if(r=="next"||r.startsWith("after")){let l={};return l[i]=1,Dr.createRelativeFromReference(e.reference,l)}if(r=="last"||r=="past"){let l={};return l[i]=-1,Dr.createRelativeFromReference(e.reference,l)}let s=e.createParsingComponents(),a=(0,wZe.default)(e.reference.instant);return o.match(/week/i)?(a=a.add(-a.get("d"),"d"),s.imply("day",a.date()),s.imply("month",a.month()+1),s.imply("year",a.year())):o.match(/month/i)?(a=a.add(-a.date()+1,"d"),s.imply("day",a.date()),s.assign("year",a.year()),s.assign("month",a.month()+1)):o.match(/year/i)&&(a=a.add(-a.date()+1,"d"),a=a.add(-a.month(),"month"),s.imply("day",a.date()),s.imply("month",a.month()+1),s.assign("year",a.year())),s}};var AVt=new RegExp("([^\\d]|^)([0-3]{0,1}[0-9]{1})[\\/\\.\\-]([0-3]{0,1}[0-9]{1})(?:[\\/\\.\\-]([0-9]{4}|[0-9]{2}))?(\\W|$)","i"),kVt=1,MVt=5,vZe=2,xZe=3,Sxe=4,Gz=class{constructor(e){this.groupNumberMonth=e?xZe:vZe,this.groupNumberDay=e?vZe:xZe}pattern(){return AVt}extract(e,n){let r=n.index+n[kVt].length,o=n.index+n[0].length-n[MVt].length;if(r>0&&e.text.substring(0,r).match("\\d/?$")||o<e.text.length&&e.text.substring(o).match("^/?\\d"))return;let i=e.text.substring(r,o);if(i.match(/^\d\.\d$/)||i.match(/^\d\.\d{1,2}\.\d{1,2}\s*$/)||!n[Sxe]&&i.indexOf("/")<0)return;let s=e.createParsingResult(r,i),a=parseInt(n[this.groupNumberMonth]),l=parseInt(n[this.groupNumberDay]);if((a<1||a>12)&&a>12)if(l>=1&&l<=12&&a<=31)[l,a]=[a,l];else return null;if(l<1||l>31)return null;if(s.start.assign("day",l),s.start.assign("month",a),n[Sxe]){let c=parseInt(n[Sxe]),u=c9(c);s.start.assign("year",u)}else{let c=l_(e.refDate,l,a);s.start.imply("year",c)}return s}};var NVt=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${Iv})(?=\\W|$)`,"i"),OVt=new RegExp(`(this|last|past|next|after|\\+|-)\\s*(${d_})(?=\\W|$)`,"i"),Yz=class extends so{constructor(e=!0){super(),this.allowAbbreviations=e}innerPattern(){return this.allowAbbreviations?NVt:OVt}innerExtract(e,n){let r=n[1].toLowerCase(),o=Rp(n[2]);if(!o)return null;switch(r){case"last":case"past":case"-":o=f_(o);break}return Dr.createRelativeFromReference(e.reference,o)}};function RVt(t){return t.text.match(/^[+-]/i)!=null}function bZe(t){return t.text.match(/^-/i)!=null}var Zz=class extends Lp{shouldMergeResults(e,n,r){return e.match(/^\s*$/i)?RVt(r)||bZe(r):!1}mergeResults(e,n,r,o){let i=Rp(r.text);bZe(r)&&(i=f_(i));let s=Dr.createRelativeFromReference(new a_(n.start.date()),i);return new Tv(n.reference,n.index,`${n.text}${e}${r.text}`,s)}};function CZe(t){return t.text.match(/\s+(before|from)$/i)!=null}function LVt(t){return t.text.match(/\s+(after|since)$/i)!=null}var Jz=class extends Lp{patternBetween(){return/^\s*$/i}shouldMergeResults(e,n,r){return!e.match(this.patternBetween())||!CZe(n)&&!LVt(n)?!1:!!r.start.get("day")&&!!r.start.get("month")&&!!r.start.get("year")}mergeResults(e,n,r){let o=Rp(n.text);CZe(n)&&(o=f_(o));let i=Dr.createRelativeFromReference(new a_(r.start.date()),o);return new Tv(r.reference,n.index,`${n.text}${e}${r.text}`,i)}};var DVt=new RegExp(`^\\s*(${c_})`,"i"),$Vt=1,Xz=class{refine(e,n){return n.forEach(function(r){if(!r.start.isDateWithUnknownYear())return;let o=e.text.substring(r.index+r.text.length),i=DVt.exec(o);if(!i)return;e.debug(()=>{console.log(`Extracting year: '${i[0]}' into : ${r}`)});let s=u_(i[$Vt]);r.end!=null&&r.end.assign("year",s),r.start.assign("year",s),r.text+=i[0]}),n}};var aP=class{createCasualConfiguration(e=!1){let n=this.createConfiguration(!1,e);return n.parsers.push(new Wz),n.parsers.push(new Hz),n.parsers.push(new Ez),n.parsers.push(new qz),n.parsers.push(new Yz),n}createConfiguration(e=!0,n=!1){let r=nZe({parsers:[new Gz(n),new Tz(e),new Iz,new Pz(n),new Kz,new kz,new Nz(e),new Oz(e),new Rz(e)],refiners:[new mR]},e);return r.parsers.unshift(new Az(e)),r.refiners.unshift(new Jz),r.refiners.unshift(new Zz),r.refiners.unshift(new p_),r.refiners.push(new mR),r.refiners.push(new Xz),r.refiners.push(new Dz),r}};var gR=class t{constructor(e){this.defaultConfig=new aP,e=e||this.defaultConfig.createCasualConfiguration(),this.parsers=[...e.parsers],this.refiners=[...e.refiners]}clone(){return new t({parsers:[...this.parsers],refiners:[...this.refiners]})}parseDate(e,n,r){let o=this.parse(e,n,r);return o.length>0?o[0].start.date():null}parse(e,n,r){let o=new Txe(e,n,r),i=[];return this.parsers.forEach(s=>{let a=t.executeParser(o,s);i=i.concat(a)}),i.sort((s,a)=>s.index-a.index),this.refiners.forEach(function(s){i=s.refine(o,i)}),i}static executeParser(e,n){let r=[],o=n.pattern(e),i=e.text,s=e.text,a=o.exec(s);for(;a;){let l=a.index+i.length-s.length;a.index=l;let c=n.extract(e,a);if(!c){s=i.substring(a.index+1),a=o.exec(s);continue}let u=null;c instanceof Tv?u=c:c instanceof Dr?(u=e.createParsingResult(a.index,a[0]),u.start=c):u=e.createParsingResult(a.index,a[0],c);let d=u.index,f=u.text;e.debug(()=>console.log(`${n.constructor.name} extracted (at index=${d}) '${f}'`)),r.push(u),s=i.substring(d+f.length),a=o.exec(s)}return r}},Txe=class{constructor(e,n,r){this.text=e,this.reference=new a_(n),this.option=r??{},this.refDate=this.reference.instant}createParsingComponents(e){return e instanceof Dr?e:new Dr(this.reference,e)}createParsingResult(e,n,r,o){let i=typeof n=="string"?n:this.text.substring(e,n),s=r?this.createParsingComponents(r):null,a=o?this.createParsingComponents(o):null;return new Tv(this.reference,e,i,s,a)}debug(e){this.option.debug&&(this.option.debug instanceof Function?this.option.debug(e):this.option.debug.debug(e))}};var Ixe=new aP,_Ze=new gR(Ixe.createCasualConfiguration(!1)),FVt=new gR(Ixe.createConfiguration(!0,!1)),hhr=new gR(Ixe.createCasualConfiguration(!0));var SZe=_Ze;function Pxe(t,e,n){return SZe.parse(t,e,n)}function TZe(t,e,n){return SZe.parseDate(t,e,n)}Lte();function Exe(t){let e=t.match(/^(?:UTC|GMT)?([-+]?\d{1,2})(?::(\d{2}))?$/i);if(!e)throw new Error(`Invalid timezone offset format: ${t}. Use formats like '+8', '-5', '+5:30', 'UTC+8', 'GMT-5'`);let n=parseInt(e[1]),r=parseInt(e[2]||"0");if(Math.abs(n)>14||r>=60)throw new Error(`Invalid timezone offset: ${t}. Hours must be between -14 and +14, minutes must be less than 60`);let o=n>=0?"+":"",i=r>0?`:${r.toString().padStart(2,"0")}`:"";return`UTC${o}${n}${i}`}async function zVt(t){let e=hn.now();if(t)try{let i=Exe(t),s=e.setZone(i);if(!s.isValid)throw new Error(`Failed to apply timezone offset: ${t}`);e=s}catch(i){throw new Error(`${i.message}`)}let n=e.toJSDate(),r=e.offset,o=e.offsetNameShort||"Unknown";return{epoch:Math.floor(n.getTime()),isoString:n.toISOString(),userLocaleString:e.toLocaleString(hn.DATETIME_FULL),localDateString:e.toISODate()||"",timezoneOffset:r,timezone:o}}var IZe=Rr({name:"getCurrentTime",description:"Get the current time in local timezone or at a specified UTC offset. Returns epoch time, ISO string, and formatted strings.",schema:we.object({timezoneOffset:we.string().optional().describe(`Optional UTC offset. IMPORTANT: Must be a numeric offset, NOT a timezone name.

EXAMPLES OF CORRECT USAGE:
- "what time is it" \u2192 No parameter (uses local time)
- "what time is it in Tokyo" \u2192 timezoneOffset: "+9"
- "what time is it in Beijing" \u2192 timezoneOffset: "+8"
- "what time is it in New York" \u2192 timezoneOffset: "-5" (or "-4" during DST)
- "what time is it in Mumbai" \u2192 timezoneOffset: "+5:30"

SUPPORTED FORMATS:
- Simple: "+8", "-5", "+5:30"
- With prefix: "UTC+8", "GMT-5", "UTC+5:30"

COMMON TIMEZONE OFFSETS:
- Tokyo: UTC+9
- Beijing/Singapore: UTC+8
- Mumbai: UTC+5:30
- Dubai: UTC+4
- London: UTC+0 (UTC+1 during BST)
- New York: UTC-5 (UTC-4 during DST)
- Los Angeles: UTC-8 (UTC-7 during DST)`)}),func:async({timezoneOffset:t})=>zVt(t)}),PZe={jan:1,january:1,feb:2,february:2,mar:3,march:3,apr:4,april:4,may:5,jun:6,june:6,jul:7,july:7,aug:8,august:8,sep:9,sept:9,september:9,oct:10,october:10,nov:11,november:11,dec:12,december:12};function jVt(t,e){let n=t.match(/^(last|past|previous|prior)\s+(\d+)\s+(days?|weeks?|months?|years?)$/i);if(!n)return;let[,,r,o]=n,i=parseInt(r);if(i<=0)return;let s=o.replace(/s$/,""),a=e.startOf("day");return{start:a.minus({[s+"s"]:i}),end:a}}function VVt(t,e){switch(t){case"yesterday":return{start:e.minus({days:1}).startOf("day"),end:e.minus({days:1}).endOf("day")};case"last week":return{start:e.minus({weeks:1}).startOf("week"),end:e.minus({weeks:1}).endOf("week")};case"this week":return{start:e.startOf("week"),end:e.endOf("week")};case"next week":return{start:e.plus({weeks:1}).startOf("week"),end:e.plus({weeks:1}).endOf("week")};case"last month":return{start:e.minus({months:1}).startOf("month"),end:e.minus({months:1}).endOf("month")};case"this month":return{start:e.startOf("month"),end:e.endOf("month")};case"next month":return{start:e.plus({months:1}).startOf("month"),end:e.plus({months:1}).endOf("month")};case"last year":return{start:e.minus({years:1}).startOf("year"),end:e.minus({years:1}).endOf("year")};case"this year":return{start:e.startOf("year"),end:e.endOf("year")};case"next year":return{start:e.plus({years:1}).startOf("year"),end:e.plus({years:1}).endOf("year")};case"last quarter":return{start:e.minus({quarters:1}).startOf("quarter"),end:e.minus({quarters:1}).endOf("quarter")};case"this quarter":return{start:e.startOf("quarter"),end:e.endOf("quarter")};case"next quarter":return{start:e.plus({quarters:1}).startOf("quarter"),end:e.plus({quarters:1}).endOf("quarter")}}}function WVt(t,e){let n=t.match(/(?:the\s+)?week\s+of\s+(.+)/i);if(!n)return;let r=n[1],o=Pxe(r,e.toJSDate(),{forwardDate:!1});if(o.length===0)return;let i=hn.fromJSDate(o[0].start.date()).startOf("week"),s=i.endOf("week");return i>e&&(i=i.minus({years:1}),s=s.minus({years:1})),{start:i,end:s}}function HVt(t,e){let n=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)$/i);if(!n)return;let r=PZe[n[1]],o=e.year;r>e.month&&o--;let i=hn.fromObject({year:o,month:r,day:1}),s=i.endOf("month");return i>e&&(i=i.minus({years:1}),s=s.minus({years:1})),{start:i,end:s}}function KVt(t,e){let n=t.match(/^(?:(?:the\s+)?(?:year|yr)(?:\s+(?:of|in))?\s+)?(\d{4})$/i);if(!n)return;let r=parseInt(n[1]),o=hn.fromObject({year:r,month:1,day:1}),i=hn.fromObject({year:r,month:12,day:31});return o>e&&(o=o.minus({years:1}),i=i.minus({years:1})),{start:o,end:i}}function qVt(t,e){let n=t.match(/^(?:(?:q|Q)(\d{1})\s+(\d{4})|(\d{4})\s+(?:q|Q)(\d{1}))$/),r=t.match(/^(?:q|Q)(\d{1})$/),o,i;if(n)o=parseInt(n[1]||n[4]),i=parseInt(n[2]||n[3]);else if(r){o=parseInt(r[1]),i=e.year;let c=Math.floor((e.month-1)/3)+1;o>c&&i--}else return;if(o<1||o>4)return;let s=(o-1)*3+1,a=hn.fromObject({year:i,month:s,day:1}).startOf("day"),l=a.plus({months:3}).minus({days:1}).endOf("day");return a>e&&(a=a.minus({years:1}),l=l.minus({years:1})),{start:a,end:l}}function GVt(t,e){let n=t.match(/^(jan|january|feb|february|mar|march|apr|april|may|jun|june|jul|july|aug|august|sep|sept|september|oct|october|nov|november|dec|december)\s+(\d{4})$/i);if(!n)return;let r=PZe[n[1].toLowerCase()],o=parseInt(n[2]),i=hn.fromObject({year:o,month:r,day:1}).startOf("day"),s=i.endOf("month");return i>e&&(i=i.minus({years:1}),s=s.minus({years:1})),{start:i,end:s}}function YVt(t){let e=hn.now(),n=t.toLowerCase().replace("@vault","").trim(),r=jVt(n,e)||VVt(n,e)||WVt(n,e)||HVt(n,e)||GVt(n,e)||qVt(n,e)||KVt(n,e);if(r)return{startTime:r.start.toMillis(),endTime:r.end.toMillis()};let o=Pxe(t,e.toJSDate(),{forwardDate:!1});if(o.length>0){let i=hn.fromJSDate(o[0].start.date()).startOf("day"),s=o[0].end?hn.fromJSDate(o[0].end.date()).endOf("day"):i.endOf("day");return i>e&&(i.minus({years:1}),s.minus({years:1})),{startTime:i.toMillis(),endTime:s.toMillis()}}console.warn(`Unable to parse time expression: ${t}`)}function ZVt(t){let e=t.toJSDate(),n=t.offset,r=t.offsetNameShort||"Unknown";return{epoch:Math.floor(e.getTime()),isoString:e.toISOString(),userLocaleString:t.toLocaleString(hn.DATETIME_FULL),localDateString:t.toISODate()||"",timezoneOffset:n,timezone:r}}var EZe=Rr({name:"getTimeRangeMs",description:"Convert natural language time expressions to date ranges for use with localSearch",schema:we.object({timeExpression:we.string().describe(`Natural language time expression to convert to a date range.

COMMON EXPRESSIONS:
- Relative past: "yesterday", "last week", "last month", "last year"
- Relative ranges: "this week", "this month", "this year"
- Specific dates: "July 1", "July 1 2023", "2023-07-01"
- Date ranges: "from July 1 to July 15", "between May and June"
- Time periods: "last 7 days", "past 30 days", "previous 3 months"

IMPORTANT: This tool is typically used as the first step before localSearch when searching notes by time.

EXAMPLE WORKFLOW:
1. User: "what did I do last week"
2. First call getTimeRangeMs with timeExpression: "last week"
3. Then use the returned time range with localSearch`)}),func:async({timeExpression:t})=>{let e=YVt(t);return e||{error:`Unable to parse time expression: ${t}`}}});function JVt(t){let e=t.toString().length===10?t*1e3:t,n=hn.fromMillis(e);return ZVt(n)}var AZe=Rr({name:"getTimeInfoByEpoch",description:"Convert a Unix timestamp (in seconds or milliseconds) to detailed time information",schema:we.object({epoch:we.number().describe("Unix timestamp in seconds or milliseconds")}),func:async({epoch:t})=>JVt(t)});async function XVt(t,e,n){let r=Exe(e),o=Exe(n);try{let i=hn.now().setZone(r),s=TZe(t,i.toJSDate());if(!s)throw new Error(`Could not parse time: ${t}`);let a=hn.fromJSDate(s,{zone:r}),l=a.setZone(o);if(!l.isValid)throw new Error("Invalid timezone conversion");let c=l.toJSDate(),u=l.offset;return{epoch:Math.floor(c.getTime()),isoString:c.toISOString(),userLocaleString:l.toLocaleString(hn.DATETIME_FULL),localDateString:l.toISODate()||"",timezoneOffset:u,timezone:l.offsetNameShort||o,originalTime:a.toLocaleString(hn.TIME_SIMPLE)+" "+a.offsetNameShort,convertedTime:l.toLocaleString(hn.TIME_SIMPLE)+" "+l.offsetNameShort}}catch(i){throw new Error(`Failed to convert time: ${i.message}`)}}var kZe=Rr({name:"convertTimeBetweenTimezones",description:"Convert a specific time from one timezone to another using UTC offsets",schema:we.object({time:we.string().describe(`Time to convert. Supports various formats:
- 12-hour: "6pm", "3:30 PM", "11:45 am"
- 24-hour: "18:00", "15:30", "23:45"
- Relative: "noon", "midnight"`),fromOffset:we.string().describe(`Source UTC offset. Must be numeric, not timezone name.
Examples: "-8" for PT, "+0" for London, "+8" for Beijing`),toOffset:we.string().describe(`Target UTC offset. Must be numeric, not timezone name.
Examples: "+9" for Tokyo, "-5" for NY, "+5:30" for Mumbai

EXAMPLE USAGE:
- "what time is 6pm PT in Tokyo" \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"
- "convert 3:30 PM EST to London time" \u2192 time: "3:30 PM", fromOffset: "-5", toOffset: "+0"
- "what is 9am Beijing time in New York" \u2192 time: "9am", fromOffset: "+8", toOffset: "-5"`)}),func:async({time:t,fromOffset:e,toOffset:n})=>XVt(t,e,n)});Zg();ns();Se();qe();var MZe=5e4,NZe=Rr({name:"youtubeTranscription",description:"Get transcripts of YouTube videos when the user provides YouTube URLs",schema:we.object({_userMessageContent:we.string().optional().describe("Internal: user message content injected by the system")}),func:async t=>{let{_userMessageContent:e}=t;if(typeof e!="string")return{success:!1,message:"Invalid input: User message must be a string"};if(e.length>MZe)return{success:!1,message:`Input too long: Maximum allowed length is ${MZe} characters`};let n=FAe(e);if(n.length===0)return{success:!1,message:"No YouTube URLs found in the user prompt. URLs must be in the user prompt instead of the context notes."};let r=await Promise.all(n.map(async i=>{try{let s=pc()&&q().supadataApiKey?await gG(i):await di.getInstance().youtube4llm(i);return s.response.transcript?{url:i,success:!0,transcript:s.response.transcript,elapsed_time_ms:s.elapsed_time_ms}:{url:i,success:!1,message:"Transcript not available. Only English videos with auto transcript enabled are supported"}}catch(s){return console.error(`Error transcribing YouTube video ${i}:`,s),{url:i,success:!1,message:"An error occurred while transcribing the YouTube video"}}}));return{success:r.some(i=>i.success),results:r,total_urls:n.length}}});var QVt=[{tool:i9,metadata:{id:"localSearch",displayName:"Vault Search",description:"Search through your vault notes",category:"search",copilotCommands:["@vault"],customPromptInstructions:`For localSearch (searching notes based on their contents in the vault):
- You MUST always provide both "query" (string) and "salientTerms" (array of strings)
- salientTerms MUST be extracted from the user's original query - never invent new terms
- They are keywords used for BM25 full-text search to find notes containing those exact words
- Treat every token that begins with "#" as a high-priority salient term. Keep the leading "#" and the full tag hierarchy (e.g., "#project/phase1").
- Include tagged terms alongside other meaningful words; never strip hashes or rewrite tags into plain words.
- Extract meaningful content words from the query (nouns, verbs, names, etc.)
- Exclude common words like "what", "I", "do", "the", "a", etc.
- Exclude time expressions like "last month", "yesterday", "last week"
- Preserve the original language - do NOT translate terms to English

Evaluating search results and re-searching:
- Results include a relevance quality summary: high (score \u22650.7), medium (0.3-0.7), low (<0.3)
- If most results are low relevance or miss key concepts from the user's question:
  1. Try searching again with synonyms or related terms
  2. Use more specific phrasing if query was too broad
  3. Use more general phrasing if query was too narrow
- Example: "machine learning algorithms" returned low results \u2192 try "ML models", "neural networks", or "AI techniques"

Examples:
- Query "piano learning practice" \u2192 query: "piano learning practice", salientTerms: ["piano", "learning", "practice"]
- Query "#projectx status update" \u2192 query: "#projectx status update", salientTerms: ["#projectx", "status", "update"]
- Query "\u94A2\u7434\u5B66\u4E60" (Chinese) \u2192 query: "\u94A2\u7434\u5B66\u4E60", salientTerms: ["\u94A2\u7434", "\u5B66\u4E60"] (preserve original language)

For time-based searches (e.g., "what did I do last week"):
1. First call getTimeRangeMs with timeExpression: "last week"
2. Then use localSearch with the returned timeRange, query matching the user's question, and salientTerms: [] (empty for generic time queries)

For time-based searches with meaningful terms (e.g., "python debugging notes from yesterday"):
1. First call getTimeRangeMs with timeExpression: "yesterday"
2. Then use localSearch with the returned timeRange, query: "python debugging notes", salientTerms: ["python", "debugging", "notes"]

For broad searches:
- If the user wants a comprehensive list, use getFileTree to get all note titles as reference. This helps verify search completeness and identify notes the search may have missed.`}},{tool:s9,metadata:{id:"webSearch",displayName:"Web Search",description:"Search the INTERNET (NOT vault notes) when user explicitly asks for web/online information",category:"search",copilotCommands:["@websearch","@web"],customPromptInstructions:`For webSearch:
- ONLY use when the user's query contains explicit web-search intent like:
  * "web search", "internet search", "online search"
  * "Google", "search online", "look up online", "search the web"
- Always provide an empty chatHistory array

Example: "search the web for python tutorials" \u2192 query: "python tutorials", chatHistory: []`}},{tool:IZe,metadata:{id:"getCurrentTime",displayName:"Get Current Time",description:"Get the current time in any timezone",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time queries (IMPORTANT: Always use UTC offsets, not timezone names):

- If the user mentions a specific city, country, or timezone name (e.g., "Tokyo", "Japan", "JST"), you MUST convert it to the correct UTC offset and pass it via the timezoneOffset parameter (e.g., "+9").
- Only omit timezoneOffset when the user asks for the current local time without naming any location or timezone.
- If you cannot confidently determine the offset from the user request, ask the user to clarify before calling the tool.

Examples:
- "what time is it" (local time) \u2192 call with no parameters
- "what time is it in Tokyo" (UTC+9) \u2192 timezoneOffset: "+9"
- "what time is it in New York" (UTC-5 or UTC-4 depending on DST) \u2192 timezoneOffset: "-5"`}},{tool:AZe,metadata:{id:"getTimeInfoByEpoch",displayName:"Get Time Info",description:"Convert epoch timestamp to human-readable format",category:"time",isAlwaysEnabled:!0}},{tool:EZe,metadata:{id:"getTimeRangeMs",displayName:"Get Time Range",description:"Convert time expressions to date ranges",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For time-based queries:
- Use this tool to convert time expressions like "last week", "yesterday", "last month" to proper time ranges
- This is typically the first step before using localSearch with a time range

Example: For "last week" \u2192 timeExpression: "last week"`}},{tool:kZe,metadata:{id:"convertTimeBetweenTimezones",displayName:"Convert Timezones",description:"Convert time between different timezones",category:"time",isAlwaysEnabled:!0,customPromptInstructions:`For timezone conversions:

Example: "what time is 6pm PT in Tokyo" (PT is UTC-8 or UTC-7, Tokyo is UTC+9) \u2192 time: "6pm", fromOffset: "-8", toOffset: "+9"`}},{tool:hYe,metadata:{id:"readNote",displayName:"Read Note",description:"Read a specific note in sequential chunks using its own line-chunking logic.",category:"file",requiresVault:!0,isAlwaysEnabled:!0,customPromptInstructions:`For readNote:
- Decide based on the user's request: only call this tool when the question requires reading note content.
- If the user asks about a note title that is already mentioned in the current or previous turns of the conversation, or linked in <active_note> or <note_context> blocks, call readNote directly\u2014do not use localSearch to look it up. Even if the note title mention is partial but similar to what you have seen in the context, try to infer the correct note path from context. Skip the tool when a note is irrelevant to the user query.
- If the user asks about notes linked from that note, read the original note first, then follow the "linkedNotes" paths returned in the tool result to inspect those linked notes.
- Always start with chunk 0 (omit chunkIndex or set it to 0). Only request the next chunk if the previous chunk did not answer the question.
- Pass vault-relative paths without a leading slash. If a call fails, adjust the path (for example, add ".md" or use an alternative candidate) and retry only if necessary.
- Every tool result may include a "linkedNotes" array. If the user needs information from those linked notes, call readNote again with one of the provided candidate paths, starting again at chunk 0. Do not expand links you don't need.
- Stop calling readNote as soon as you have the required information.
- Always call getFileTree to get the exact note path if it is not provided in the context before calling readNote.

Examples:
- First chunk: notePath: "Projects/launch-plan.md" (chunkIndex omitted or 0)
- Next chunk: notePath: "Projects/launch-plan.md", chunkIndex: 1`}},{tool:t9,metadata:{id:"writeFile",displayName:"Write to File",description:"Create or rewrite files in your vault",category:"file",requiresVault:!0,timeoutMs:0,copilotCommands:["@composer"],customPromptInstructions:`For writeFile:
- NEVER display the file content directly in your response
- Always pass the complete file content to the tool
- Include the full path to the file
- You MUST explicitly call writeFile for any intent of updating or creating files
- Do not call writeFile tool again if the result is not accepted
- Do not call writeFile tool if no change needs to be made
- Always create new notes in root folder or folders the user explicitly specifies
- When creating a new note in a folder, you MUST use getFileTree to get the exact folder path first
Examples:
- Basic: path: "path/to/note.md", content: "FULL CONTENT OF THE NOTE"
- Skip confirmation: path: "path/to/note.md", content: "FULL CONTENT", confirmation: false`}},{tool:lYe,metadata:{id:"editFile",displayName:"Edit File",description:"Make a targeted, single-match edit to an existing file",category:"file",requiresVault:!0,timeoutMs:0,customPromptInstructions:`For editFile:
- Use for targeted edits; use writeFile for major rewrites or new files
- oldText must uniquely identify the location \u2014 include surrounding context lines if needed
- The tool automatically handles minor whitespace/quote differences (fuzzy matching)
- Call once per edit; for multiple edits call the tool multiple times

Example: Add "Bob Johnson" to attendees in notes/meeting.md:
path: "notes/meeting.md"
oldText: "## Attendees\\n- John Smith\\n- Jane Doe"
newText: "## Attendees\\n- John Smith\\n- Jane Doe\\n- Bob Johnson"`}},{tool:NZe,metadata:{id:"youtubeTranscription",displayName:"YouTube Transcription",description:"Get transcripts from YouTube videos",category:"media",isPlusOnly:!0,requiresUserMessageContent:!0,customPromptInstructions:`For youtubeTranscription:
- Use when user provides YouTube URLs
- No parameters needed - the tool will process URLs from the conversation`}}];function eWt(t){Vi.getInstance().register({tool:mYe(t.getRoot()),metadata:{id:"getFileTree",displayName:"File Tree",description:"Browse vault file structure",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getFileTree:
- Use to browse the vault's file structure including paths of notes and folders
- Always call this tool to explore the exact path of notes or folders when you are not given the exact path.
- DO NOT use this tool to look up note contents or metadata - use localSearch or readNote instead.
- No parameters needed

Example queries that should use getFileTree:
- "Create a new note in the projects folder" \u2192 call getFileTree to get the exact folder path
- "Create a new note using the quick note template" \u2192 call getFileTree to look up the template path
- "How many files are in the projects folder" \u2192 call getFileTree to list all files`}})}function tWt(){Vi.getInstance().register({tool:kYe(),metadata:{id:"getTagList",displayName:"Tag List",description:"List vault tags with occurrence statistics",category:"file",isAlwaysEnabled:!0,requiresVault:!0,isBackground:!0,customPromptInstructions:`For getTagList:
- Use to inspect existing tags before suggesting new ones or reorganizing notes.
- Omit parameters to include both frontmatter and inline tags.
- Set includeInline to false when you only need frontmatter-defined tags.
- Use maxEntries to limit output for very large vaults.

Examples:
- Default (all tags): call with no parameters
- Frontmatter only: includeInline: false`}})}function nWt(){Vi.getInstance().register({tool:n9,metadata:{id:"updateMemory",displayName:"Update Memory",description:"Save information to user memory when the user explicitly asks to remember something or update the memory",category:"memory",copilotCommands:["@memory"],isAlwaysEnabled:!0,customPromptInstructions:`For updateMemory:
- Use this tool to update the memory when the user explicitly asks to update the memory
- DO NOT use for general information - only for personal facts, preferences, or specific things the user wants stored

Example: statement: "I'm studying Japanese and I'm preparing for JLPT N3"`}})}function rWt(){let t=Vi.getInstance();t.register({tool:yYe,metadata:{id:"obsidianDailyNote",displayName:"Daily Note",description:"Create or read today's daily note, or get its path",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianDailyNote:
- Use for daily note operations: creating, reading content, or getting the file path.
- Use readNote for reading specific notes by path. Use obsidianDailyNote only for today's daily note.
- daily \u2014 create today's daily note. Applies the user's configured daily note template automatically. Use this when the user asks to create or set up today's daily note.
- daily:read \u2014 read today's daily note content.
- daily:path \u2014 get the vault-relative file path (useful for follow-up readNote calls).
- For past or future daily notes (e.g. "yesterday's daily note"): NEVER ask the user for the date \u2014 use the time tools. Workflow: (1) call getCurrentTime to resolve the date, (2) call daily:path to discover the date format and folder, (3) call obsidianTemplates with command=templates to list available template names, then call template:read with the name that matches (e.g. "Daily Note Template"), (4) use writeFile to create the note at the resolved path with the template content, replacing variables like {{date}} with the target date. If templates returns an error or no daily template is found, ask the user for their template path and use readNote to read it.
- To add content to a daily note, use writeFile or editFile.
- Use \\n for newlines and \\t for tabs in content strings.
- For arbitrary file writes beyond daily notes, use writeFile or editFile instead.
- If the user names a specific vault, pass it using the vault parameter.`}}),t.register({tool:gYe,metadata:{id:"obsidianRandomRead",displayName:"Random Note",description:"Read a random note using the official Obsidian CLI",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianRandomRead:
- Use when the user explicitly asks for a random note or random note content.
- If the user names a specific vault, pass it using the vault parameter.
- Do not use when the user asks for a specific note; use readNote/getFileTree for specific targets.`}}),t.register({tool:wYe,metadata:{id:"obsidianProperties",displayName:"Properties",description:"Read frontmatter properties from notes or list all property names in the vault",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianProperties:
- Use to inspect frontmatter properties across the vault or within a specific note.
- properties (no file/path): list all property names used vault-wide. Add counts=true for occurrence counts. Add sort=count to sort by frequency.
- properties with file= or path=: list that note's key-value property pairs.
- property:read: read a single property value from a specific note. Requires name parameter.
- file= resolves like a wikilink (name only, no path or extension). path= uses exact vault-relative path.
- Do not use for full note content \u2014 use readNote for that.
- To modify properties, use writeFile or editFile to update the frontmatter YAML.`}}),t.register({tool:vYe,metadata:{id:"obsidianTasks",displayName:"Tasks",description:"List tasks across the vault with filters for status, file, and daily note",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTasks:
- ALWAYS use this tool when the user asks about tasks, todos, or checkboxes. Do NOT use localSearch for task queries.
- Use to list and filter tasks across the vault.
- todo=true: show only incomplete tasks. done=true: show only completed tasks.
- status="x": filter by specific status character (e.g., "/" for in-progress, "x" for done, " " for open).
- daily=true: show tasks from today's daily note only.
- verbose=true: group tasks by file with line numbers.
- total=true: return only the task count.
- file= resolves like a wikilink (name only). path= uses exact vault-relative path.
- For time-based task queries (e.g. "tasks from last month"): use verbose=true to get tasks grouped by file, then filter results by file dates or daily note filenames to match the time range.`}}),t.register({tool:xYe,metadata:{id:"obsidianLinks",displayName:"Links",description:"Query the vault link graph: backlinks, outgoing links, orphans, unresolved",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianLinks:
- Use to explore the vault's link graph.
- backlinks: list notes that link TO a given file. Use file= or path= to target a note. Add counts=true for link counts.
- links: list outgoing links FROM a given file. Use file= or path= to target a note.
- orphans: list all notes with no incoming links. Use total=true for just the count. Add all=true to include non-markdown files.
- unresolved: list wikilinks that don't resolve to any existing file. Use counts=true for occurrence counts, verbose=true to see source files.
- file= resolves like a wikilink (name only). path= uses exact vault-relative path. Without either, targets the active file.`}}),t.register({tool:bYe,metadata:{id:"obsidianTemplates",displayName:"Templates",description:"List available templates or read template content",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianTemplates:
- Use 'templates' to list all available templates when you need to find the right template for a task.
- Use 'template:read' with a template name to get its content with variables resolved. Requires name parameter.
- This is useful for creating daily notes from templates \u2014 read the template first, then use writeFile to populate the note.`}}),t.register({tool:CYe,metadata:{id:"obsidianBases",displayName:"Bases",description:"List Base files, views, query data, or create new items in Obsidian Bases",category:"cli",requiresVault:!0,customPromptInstructions:`For obsidianBases:
- Use to explore and manage structured data in Obsidian Base (.base) database files.
- bases: list all Base files in the vault. Use total=true for just the count.
- base:views: list the views defined in a Base file. Requires file= or path=.
- base:query: query data from a specific Base view. Requires file= or path=, optionally view= and format= (e.g., format=csv).
- base:create: create a new item (row) in a Base. Requires file= or path=. Optional: view= (target view), name= (file name for the item), content= (initial note content).
  - The created item appears as a new note that matches the Base's filter criteria.
  - Use base:query first to understand the Base's structure and existing data before creating items.
  - If the Base filters by a specific tag or folder, ensure the new item will match those filters.

Base file YAML reference (for creating new .base files with writeFile):
- filters: MUST be either a single string OR an object with and/or/not keys. NEVER use a bare YAML list.
  - Single filter: filters: 'file.hasTag("book")'
  - Multiple filters: filters: { and: ['file.hasTag("book")', 'status == "reading"'] }
  - Negation: filters: { not: ['file.hasTag("archived")'] }
  - Bare lists like "filters: - 'expr'" are INVALID and will cause parse errors.
- formulas: computed properties. Functions: date(), now(), today(), if(cond, true, false), duration(). Duration fields: .days, .hours, .minutes. Example: days_left: 'if(due, (date(due) - today()).days, "")'
- properties: display config per property (displayName, width, hidden).
- views: table (default), cards, list, or map. Each view can have its own filters, order (property display list), groupBy, summaries.
- Property types: note properties (from frontmatter), file properties (file.name, file.mtime, file.ctime, file.tags, file.links, file.backlinks), formula properties (formula.my_formula).
- YAML quoting: single-quote formulas containing double quotes: 'if(done, "Yes", "No")'. Quote strings with special chars (:, {, }, [, ]).
- Embed in notes with ![[MyBase.base]] or ![[MyBase.base#View Name]].
- VALIDATION: After creating or editing a .base file, ALWAYS call obsidianBases with base:views to verify it parses correctly. If it returns an error, fix the YAML with writeFile and re-validate. Do not stop until validation passes.`}})}function yR(t){let e=Vi.getInstance(),n=q(),r=e.getToolMetadata("getFileTree")!==void 0,o=t!==void 0,i=e.getToolMetadata("updateMemory")!==void 0,s=n.enableSavedMemory;(e.getAllTools().length===0||r!==o||i!==s)&&(e.clear(),e.registerAll(QVt),t&&(eWt(t),tWt()),n.enableSavedMemory&&nWt(),nxe()&&rWt())}qe();qe();var h9=class{constructor(e,n){this.toolManager=e;this.writeFileTool=n;this.buffer=""}findCompleteBlock(e){let n=/<writeFile>[\s\S]*?<\/writeFile>/,r=e.match(n);return!r||r.index===void 0?null:{block:r[0],endIdx:r.index+r[0].length}}async*processChunk(e){let n="";if(Array.isArray(e.content))for(let o of e.content)o.type==="text"&&o.text!=null&&(n+=typeof o.text=="string"?o.text:"");else e.content!=null&&(n=typeof e.content=="string"?e.content:"");n&&(this.buffer+=n),yield e;let r=this.findCompleteBlock(this.buffer);for(;r;){let{block:o,endIdx:i}=r,s=o.match(/<path>([\s\S]*?)<\/path>/),a=o.match(/<content>([\s\S]*?)<\/content>/),l=s?s[1].trim():void 0,c=a?a[1].trim():void 0;try{let u=await this.toolManager.callTool(this.writeFileTool,{path:l,content:c}),d=_v.format("writeFile",u);yield{...e,content:`
${d}
`}}catch(u){yield{...e,content:`
Error: ${u?.message??String(u)}
`}}this.buffer=this.buffer.substring(i),r=this.findCompleteBlock(this.buffer)}}};ye();function OZe(t){if(!Array.isArray(t)||t.length===0)return{high:0,medium:0,low:0,total:0,averageScore:0};let e=0,n=0,r=0,o=0;for(let i of t){let s=i.rerank_score??i.score??0;o+=s,s>=.7?e++:s>=.3?n++:r++}return{high:e,medium:n,low:r,total:t.length,averageScore:o/t.length}}function RZe(t){let e=[];return t.high>0&&e.push(`${t.high} high`),t.medium>0&&e.push(`${t.medium} medium`),t.low>0&&e.push(`${t.low} low`),e.length===0?"[Relevance: no results]":`[Relevance: ${e.join(", ")}]`}function Axe(t){if(!Array.isArray(t))return"";let e=t.filter(r=>r.includeInContext!==!1);return e.length===0?"No relevant documents found.":e.map((r,o)=>{let i=r.title||"Untitled",s=r.path||"",a=r.__sourceId||r.collection_name||r.source_id||o+1,l=null;if(r.mtime){let c=new Date(r.mtime);isNaN(c.getTime())||(l=c.toISOString())}return`<document>
<id>${a}</id>
<title>${i}</title>${s&&s!==i?`
<path>${s}</path>`:""}${l?`
<modified>${l}</modified>`:""}
<content>
${r.content||""}
</content>
</document>`}).filter(r=>r.length>0).join(`

`)}function LZe(t){try{let e=JSON.parse(t);return Array.isArray(e)?Axe(e):"Invalid search results format."}catch(e){return ee("Failed to format localSearch result string:",e),"Error processing search results."}}function DZe(t){return Array.isArray(t)?t.map(e=>({title:e.title||e.path||"Untitled",path:e.path||e.title||"",score:e.rerank_score||e.score||0,explanation:e.explanation||null})):[]}function g9(t){if(typeof t=="number"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}if(typeof t=="string"){let e=new Date(t);return isNaN(e.getTime())?"":e.toISOString()}return""}function oWt(t){if(!t)return"";let e=[],n=t;try{if(Array.isArray(n.lexicalMatches)&&n.lexicalMatches.length>0){let r=new Set,o=new Set;for(let a of n.lexicalMatches)typeof a?.field=="string"&&r.add(a.field),typeof a?.query=="string"&&o.add(a.query);let i=Array.from(r).join("/"),s=Array.from(o).slice(0,3).join(", ");e.push(`Lexical(${i}): ${s}${o.size>3?", ...":""}`)}if(typeof n.semanticScore=="number"&&n.semanticScore>0&&e.push(`Semantic: ${(n.semanticScore*100).toFixed(1)}%`),n.folderBoost&&typeof n.folderBoost.boostFactor=="number"){let r=n.folderBoost,o=r.folder||"root";e.push(`Folder +${r.boostFactor.toFixed(2)} (${o})`)}if(n.graphConnections&&typeof n.graphConnections=="object"){let r=n.graphConnections,o=[];(r.backlinks??0)>0&&o.push(`${r.backlinks} backlinks`),(r.coCitations??0)>0&&o.push(`${r.coCitations} co-cites`),(r.sharedTags??0)>0&&o.push(`${r.sharedTags} tags`),typeof r.score=="number"?e.push(`Graph ${r.score.toFixed(1)}${o.length?` (${o.join(", ")})`:""}`):o.length&&e.push(`Graph (${o.join(", ")})`)}if(n.graphBoost&&typeof n.graphBoost.boostFactor=="number"&&!n.graphConnections){let r=n.graphBoost;e.push(`Graph +${r.boostFactor.toFixed(2)} (${r.connections} connections)`)}typeof n.baseScore=="number"&&typeof n.finalScore=="number"&&n.baseScore!==n.finalScore&&e.push(`Score: ${n.baseScore.toFixed(4)}\u2192${n.finalScore.toFixed(4)}`)}catch{}return e.join(" | ")}function $Ze(t,e,n=1){let r=n,o=[];if(t.length>0){let i=t.map(s=>{let a=s.__sourceId||r++,l=s.title||"Untitled",c=s.path||"",u=s.matchType||s.source||"filter",d=g9(s.mtime);return`<document>
<id>${a}</id>
<title>${l}</title>
<path>${c}</path>
<matchType>${u}</matchType>${d?`
<modified>${d}</modified>`:""}
<content>
${s.content||""}
</content>
</document>`}).join(`

`);o.push(`<filterResults>
${i}
</filterResults>`)}if(e.length>0){let i=e.map(s=>{let a=s.__sourceId||r++,l=s.title||"Untitled",c=s.path||"",u=g9(s.mtime);return`<document>
<id>${a}</id>
<title>${l}</title>${c&&c!==l?`
<path>${c}</path>`:""}${u?`
<modified>${u}</modified>`:""}
<content>
${s.content||""}
</content>
</document>`}).join(`

`);o.push(`<searchResults>
${i}
</searchResults>`)}return o.length===0?"No relevant documents found.":o.join(`

`)}var iWt=new Set(["time-filtered","tag-match"]);function FZe(t){return!Array.isArray(t)||t.length===0?!1:t.every(e=>e.source!=null&&iWt.has(e.source))}function UZe(t){return Array.isArray(t)?t.some(e=>e.source==="time-filtered"):!1}function kxe(t,e=300){if(!Array.isArray(t)||t.length===0)return"";let n=t.map(r=>{let o=r.title||"Untitled",i=r.path||"",s=g9(r.mtime),l=rR(r.content||"").slice(0,e),c=i?`
<path>${i}</path>`:"",u=s?`
<modified>${s}</modified>`:"",d=l?`
<snippet>${l}</snippet>`:"";return`<file>
<title>${o}</title>${c}${u}${d}
</file>`}).join(`
`);return`<additionalMatches count="${t.length}" note="These results contain titles and metadata only. To read the full content of a note, call the readNote tool with its path.">
${n}
</additionalMatches>`}function BZe(t){if(!Array.isArray(t)||t.length===0){k("Search Results: (none)");return}let e=0,n=t.map(l=>{let c=g9(l.mtime),u=typeof l.rerank_score=="number"?l.rerank_score:l.score||0,d=(Number.isFinite(u)?u:0).toFixed(4),f=l.chunkId||l.path||"",p=oWt(l.explanation),m=l.includeInContext!==!1;return m&&e++,{path:f,in:m?"Y":"",mtime:c,score:d,explanation:p}}),r=n.length;k(`Search Results (debug table): ${r} rows; in-context ${e}/${r}`),HAe(n,["path","in","mtime","score","explanation"]);let o=l=>String(l||"").replace(/\|/g,"\\|"),i="| PATH | IN | MTIME | SCORE | EXPLANATION |",s="| --- | :-: | --- | ---: | --- |",a=n.map(l=>`| ${o(l.path)} | ${l.in} | ${l.mtime||""} | ${l.score} | ${o(l.explanation)} |`);jW(["",`Results: ${r} rows; in-context ${e}/${r}`,"",i,s,...a,""])}function zZe(t,e){return[t,e].map(r=>r?.trim()).filter(r=>!!r).join(`

`)}function jZe(t,e){let n=t?`
${t}
`:"";return`<localSearch${e?` timeRange="${e}"`:""}>${n}</localSearch>`}function Mxe(t,e){let n=t.trim();return n?`${n}

${e}`:e}function VZe(t,e){let n=e.trim();return!n||t.includes(n)?t:Mxe(t,`[User query]:
${n}`)}function WZe(t,e){let n=e?.trim();if(!n)return t;let o=t.lastIndexOf("[User query]:");if(o===-1){let a=t.trimEnd(),l=a.length>0?`

`:"";return`${a}${l}${n}`}let i=t.slice(0,o).trimEnd(),s=t.slice(o).trimStart();return`${i}

${n}

${s}`}function HZe(t){let e=[],n=0;for(;n<t.length;){let r=t.indexOf("![",n);if(r===-1)break;let o=lWt(t,r+2);if(o===null){n=r+2;continue}let i=o+1;for(;i<t.length&&y9(t[i]);)i++;if(t[i]!=="("){n=i;continue}let s=cWt(t,i);if(s===null){n=i+1;continue}let a=sWt(t.slice(i+1,s));a&&e.push(a),n=s+1}return e}function sWt(t){let e=t.trim();if(e.length===0)return null;if(e.startsWith("<")){let r=uWt(e,0);if(r===null)return null;let o=e.slice(1,r).trim();return o.length>0?o:null}let n=aWt(e).trim();return n.length>0?n:null}function aWt(t){let e=t.trimEnd();if(e.length===0)return"";let n=e[e.length-1];if(n==='"'||n==="'"){let o=dWt(e,n,e.length-1);if(o!==null){let i=e.slice(0,o);if(i.length>0&&y9(i[i.length-1]))return i.trimEnd()}}if(n===")"){let r=fWt(e);if(r!==null){let o=e.slice(0,r);if(o.length>0&&y9(o[o.length-1]))return o.trimEnd()}}return e}function lWt(t,e){let n=e,r=0;for(;n<t.length;){let o=t[n];if(o==="\\"){n+=2;continue}if(o==="["){r++,n++;continue}if(o==="]"){if(r===0)return n;r--,n++;continue}n++}return null}function cWt(t,e){let n=e+1,r=1,o=!0,i=!1;for(;n<t.length;){let s=t[n];if(i){if(s==="\\"){n+=2;continue}if(s===">"){i=!1,o=!1,n++;continue}n++;continue}if(o){if(y9(s)){n++;continue}if(s==="<"){i=!0,n++;continue}o=!1}if(s==="\\"){n+=2;continue}if(s==="("){r++,n++;continue}if(s===")"){if(r--,r===0)return n;n++;continue}n++}return null}function uWt(t,e){for(let n=e+1;n<t.length;n++){let r=t[n];if(r==="\\"){n++;continue}if(r===">")return n}return null}function dWt(t,e,n){for(let r=n-1;r>=0;r--)if(t[r]===e&&!KZe(t,r))return r;return null}function fWt(t){if(t.length===0||t[t.length-1]!==")")return null;let e=0;for(let n=t.length-1;n>=0;n--){let r=t[n];if(!((r===")"||r==="(")&&KZe(t,n))){if(r===")"){e++;continue}if(r==="("&&(e--,e===0))return n}}return null}function KZe(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function y9(t){return t===" "||t==="	"||t===`
`||t==="\r"}function Ai(t){return typeof t!="string"?"":t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function qZe(t){return typeof t!="string"?"":t.replace(/&apos;/g,"'").replace(/&quot;/g,'"').replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&")}Kr();Ir();var dy=class extends $C{constructor(){super(...arguments);this.lastCitationSources=null}getAvailableToolsForPlanning(){let n=Vi.getInstance();return n.getAllTools().length===0&&yR(this.chainManager.app?.vault),n.getAllTools().map(o=>o.tool).filter(o=>o.name==="getCurrentTime"||o.name==="convertTimeBetweenTimezones"||o.name==="getTimeInfoByEpoch"||o.name==="getTimeRangeMs"||o.name==="getFileTree")}async planToolCalls(n,r,o=!1){let i=this.getAvailableToolsForPlanning(),s=r;if(typeof s.bindTools!="function")return ee("[CopilotPlus] Model does not support native tool calling, skipping tool planning"),{toolCalls:[],salientTerms:this.extractSalientTermsFromQuery(n)};let a=s.bindTools(i),c=`You are a helpful AI assistant. Analyze the user's message and determine if any tools should be called.

Guidelines:
- Use tools when the user's request requires external information or computation
- For time-related queries, use getTimeRangeMs to convert time expressions to timestamps
- Use getFileTree ONLY when the user wants to discover or list notes/folders in the vault \u2014 not to read content already in context${o?`
- The user has an active note attached in this turn. Its content is already available; do NOT call getFileTree merely because the user says 'this note' or 'this file'. Only call getFileTree when the user explicitly wants to discover OTHER notes, list folders, or verify paths.`:""}
- If no tools are needed, respond with your analysis

After analyzing, extract key search terms from the user's message that would be useful for searching notes:
- Extract meaningful nouns, topics, and specific concepts
- Preserve the EXACT words and language from the user's message (works for any language)
- Exclude time expressions (those are handled by tools)

Include your extracted terms as: [SALIENT_TERMS: term1, term2, term3]`,u=[{role:e$(r),content:c},{role:"user",content:n}];k("[CopilotPlus] Requesting tool planning with native tool calling...");let d;{let g=await Nc(()=>a.stream(u)),y;for await(let w of g)y=y?y.concat(w):w;if(!y)throw new Error("[CopilotPlus] Received empty response from planning model");d=new kn({content:y.content,tool_calls:y.tool_calls,additional_kwargs:y.additional_kwargs})}let f=d.tool_calls||[],p=typeof d.content=="string"?d.content:JSON.stringify(d.content);k("[CopilotPlus] Native tool calls:",f.length);let{salientTerms:m}=this.extractPlanningFieldsFromResponse(p,n),h=[];for(let g of f){let y=i.find(w=>w.name===g.name);y?(h.push({tool:y,args:g.args}),k(`[CopilotPlus] Tool call: ${g.name}`,g.args)):ee(`[CopilotPlus] Tool '${g.name}' not found in available tools`)}return{toolCalls:h,salientTerms:m}}extractPlanningFieldsFromResponse(n,r){let o,i=n.match(/\[SALIENT_TERMS:\s*([^\]]+?)\s*\]/i);if(i){let s=i[1].split(",").map(a=>a.trim()).filter(a=>a.length>0);o=s.length>0?s:this.extractSalientTermsFromQuery(r)}else o=this.extractSalientTermsFromQuery(r);return{salientTerms:o}}extractSalientTermsFromQuery(n){return n.split(/[\s\p{P}]+/u).filter(r=>r.length>=3).slice(0,10)}async processAtCommands(n,r,o){let i=n.toLowerCase(),s=this.removeAtCommands(n),a=[...r];if(i.includes("@vault")&&(a.some(c=>c.tool.name==="localSearch")||a.push({tool:i9,args:{query:s,salientTerms:o.salientTerms,timeRange:o.timeRange}})),(i.includes("@websearch")||i.includes("@web"))&&!a.some(c=>c.tool.name==="webSearch")){let u=await Sl.instance.getCurrentChainManager().memoryManager.getMemory().loadMemoryVariables({}),d=BW(u);a.push({tool:s9,args:{query:s,chatHistory:d}})}return i.includes("@memory")&&(a.some(c=>c.tool.name==="updateMemory")||a.push({tool:n9,args:{statement:s}})),a}removeAtCommands(n){return n.split(" ").filter(r=>!oR.includes(r.toLowerCase())).join(" ").trim()}async processImageUrls(n){let r=[],o=await g0.processUrlBatch(n,r,this.chainManager.app.vault);return g0.showFailedImagesNotice(r),o}async processChatInputImages(n){let r=[],o=await g0.processChatImageBatch(n,r,this.chainManager.app.vault);return g0.showFailedImagesNotice(r),o}async extractImagesFromContextBlock(n,r){let i=new RegExp(`<${r.tagName}>([\\s\\S]*?)<\\/${r.tagName}>`).exec(n);if(!i)return[];let s=i[1],l=/<content>([\s\S]*?)<\/content>/.exec(s),c=l?qZe(l[1]):"";if(!c)return[];let d=new RegExp(`<${r.identifierTag}>(.*?)<\\/${r.identifierTag}>`).exec(s),f=d?d[1]:void 0;k(`[CopilotPlus] Extracting images from ${r.displayName}:`,f||`no ${r.identifierTag}`);let p=r.useForResolution?f:void 0;return this.extractEmbeddedImages(c,p)}async extractEmbeddedImages(n,r){let o=/!\[\[(.*?\.(png|jpg|jpeg|gif|webp|bmp|svg))\]\]/g,i=[],s=[...n.matchAll(o)];for(let l of s){let c=l[1];if(r){let u=app.metadataCache.getFirstLinkpathDest(c,r);u?i.push(u.path):(ee(`Could not resolve embedded image: ${c} from source: ${r}`),i.push(c))}else i.push(c)}let a=HZe(n);for(let l of a){if(!l)continue;if(l.match(/^https?:\/\//)){i.push(l);continue}let c=l.replace(/^\.\//,"").replace(/^\//,"");if(r){let u=app.metadataCache.getFirstLinkpathDest(c,r);u?i.push(u.path):i.push(c)}else i.push(c)}return i}async buildMessageContent(n,r){let o=[],i=[],s=q(),a=[];if(s.passMarkdownImages){let d=r.contextEnvelope;if(!d)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot extract images.");let f=d.layers.find(p=>p.id==="L3_TURN");if(f){let p=[{tagName:"active_note",identifierTag:"path",displayName:"active note",useForResolution:!0},{tagName:"active_web_tab",identifierTag:"url",displayName:"active web tab",useForResolution:!1}];for(let m of p){let h=await this.extractImagesFromContextBlock(f.text,m);h.length>0&&a.push({urls:h,type:"embedded"})}}}for(let d of a){let f=await this.processImageUrls(d.urls);i.push(...f.successfulImages),o.push(...f.failureDescriptions)}let l=r.content;if(l&&l.length>0){let d=await this.processChatInputImages(l);i.push(...d.successfulImages),o.push(...d.failureDescriptions)}let c=n;o.length>0&&(c=`${n}

Note: 
${o.join(`
`)}
`);let u=[{type:"text",text:c}];return i.length>0&&u.push(...i),u}hasCapability(n,r){let o=n,i=o.modelName||o.model||"";return this.chainManager.chatModelManager.findModelByName(i)?.capabilities?.includes(r)??!1}isMultimodalModel(n){return this.hasCapability(n,"vision")}appendComposerInstructionsIfNeeded(n,r){if(!r.message||!r.message.includes("@composer"))return n;let o=`<OUTPUT_FORMAT>
${mPe}
</OUTPUT_FORMAT>`;return`${n}

${o}`}async streamMultimodalResponse(n,r,o,i,s,a,l){let c=this.chainManager.memoryManager.getMemory(),u=this.chainManager.chatModelManager.getChatModel(),d=this.isMultimodalModel(u),f=[],p=r.contextEnvelope;if(!p)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");k("[CopilotPlus] Using envelope-based context construction");let m=sy.convert(p,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),h=m.find(x=>x.role==="system");h&&f.push({role:e$(u),content:h.content}),await FC(c,f);let g=m.find(x=>x.role==="user");if(g){let x,b=o.length>0,_=S=>{let P="[User query]:";if(S.includes(P))return S;let A=S.trimEnd(),O=[];A.length>0&&O.push(A);let D=a.trim()||r.originalMessage?.trim()||"";return D.length>0?O.push(`${P}
${D}`):O.push(P),O.join(`

`)};if(b){let S=this.formatAllToolOutputs(o),P=_(g.content);x=Mxe(S,P);let A=U9e(q().enableInlineCitations);A&&(x=WZe(x,A))}else x=_(g.content);if(n.includes("<OUTPUT_FORMAT>")&&!x.includes("<OUTPUT_FORMAT>")){let S=n.match(/<OUTPUT_FORMAT>[\s\S]*?<\/OUTPUT_FORMAT>/);S&&(x+=`

`+S[0])}let T=d?await this.buildMessageContent(x,r):x;f.push({role:"user",content:T})}k("Final request to AI",{messages:f.length});let y=u?.modelName;UC({messages:f,modelName:y,contextEnvelope:r.contextEnvelope});let w=new h9(Cv,t9),v=await Nc(()=>this.chainManager.chatModelManager.getChatModel().stream(f,{signal:i.signal}));for await(let x of v){if(i.signal.aborted){k("CopilotPlus multimodal stream iteration aborted",{reason:i.signal.reason});break}for await(let b of w.processChunk(x))s.processChunk(b)}}async run(n,r,o,i,s){let{updateLoadingMessage:a}=s,l=this.chainManager.chatModelManager.getChatModel(),u=!this.hasCapability(l,"reasoning"),d=new of(o,u),f=[];if(!await _p({isCopilotPlus:!0})){await this.handleError(new Error("Invalid license key"),d.processErrorChunk.bind(d));let v=d.close().content;return this.handleResponse(v,n,r,i,o,void 0)}try{k("==== Step 1: Planning tools ====");let v,x=n.contextEnvelope;if(!x)throw new Error("[CopilotPlus] Context envelope is required but not available. Cannot proceed with CopilotPlus chain.");let _=x.layers.find($=>$.id==="L5_USER")?.text||n.originalMessage||"";try{let $=this.chainManager.chatModelManager.getChatModel(),W=!!x.layers.find(te=>te.id==="L3_TURN")?.segments?.some(te=>te.metadata?.source==="current_turn"&&/<active_note[\s>]/.test(te.content)),F=await this.planToolCalls(_,$,W),Z,V=F.toolCalls.find(te=>te.tool.name==="getTimeRangeMs");if(V){let te=await Cv.callTool(V.tool,V.args),fe=me=>me?.startTime?.epoch!==void 0&&me?.endTime?.epoch!==void 0?{startTime:me.startTime.epoch,endTime:me.endTime.epoch}:me;if(typeof te=="string")try{let me=JSON.parse(te);me.error||(Z=fe(me))}catch{ee("[CopilotPlus] Failed to parse getTimeRangeMs result:",te)}else if(te){let me=te;me.error||(Z=fe(me))}k("[CopilotPlus] Executed getTimeRangeMs, result:",Z)}let H=F.toolCalls.filter(te=>te.tool.name==="getFileTree"&&RA()?(k("Skipping getFileTree in project mode"),!1):te.tool.name==="getTimeRangeMs"&&Z?(k("Skipping getTimeRangeMs - already executed during planning"),!1):!0);v=await this.processAtCommands(_,H,{salientTerms:F.salientTerms,timeRange:Z})}catch($){return this.handleResponse(AAe($),n,r,i,o)}let T=n.contextEnvelope?.layers.find($=>$.id==="L5_USER")?.text,S=this.removeAtCommands(T||n.originalMessage||n.message),{toolOutputs:P,sources:A}=await this.executeToolCalls(v,a);f=A;let O=P.filter($=>$.output!=null),D=this.appendComposerInstructionsIfNeeded(S,n);k("Invoking LLM with envelope-based context construction"),await this.streamMultimodalResponse(D,n,O,r,d,S,a)}catch(v){a?.(Td.DEFAULT),v instanceof Error&&v.name==="AbortError"||r.signal.aborted?k("CopilotPlus stream aborted by user",{reason:r.signal.reason}):await this.handleError(v,d.processErrorChunk.bind(d))}if(r.signal.aborted&&r.signal.reason==="new-chat")return o(""),"";let m=d.close(),h=m.content,g={wasTruncated:m.wasTruncated,tokenUsage:m.tokenUsage??void 0},y=q(),w=this.lastCitationSources&&this.lastCitationSources.length>0?this.lastCitationSources:(f||[]).map(v=>({title:v.title,path:v.path}));return h=z8(h,w,y.enableInlineCitations),await this.handleResponse(h,n,r,i,o,f,void 0,g),h}async executeToolCalls(n,r){let o=[],i=[],s=n.some(a=>a.tool.name==="localSearch");for(let a of n){if(a.tool.name==="getFileTree"&&s){k("Skipping getFileTree since localSearch is already active");continue}k(`Step 2: Calling tool: ${a.tool.name}`),a.tool.name==="localSearch"?r?.(Td.READING_FILES):a.tool.name==="webSearch"?r?.(Td.SEARCHING_WEB):a.tool.name==="getFileTree"&&r?.(Td.READING_FILE_TREE);let l=await Cv.callTool(a.tool,a.args);if(a.tool.name==="localSearch"){let u={result:typeof l=="string"?l:JSON.stringify(l),success:l!=null},d=this.getTimeExpression(n),f=this.processLocalSearchResult(u,d);i.push(...f.sources),o.push({tool:a.tool.name,output:f.formattedForLLM})}else o.push({tool:a.tool.name,output:l})}return{toolOutputs:o,sources:iP(i)}}getTimeExpression(n){let r=n.find(o=>o.tool.name==="getTimeRangeMs");return r?r.args.timeExpression:""}prepareLocalSearchResult(n,r){let o=q(),s=n.filter(A=>A.includeInContext!==!1),a=OZe(s),l=RZe(a),c=FZe(s),u=UZe(s),d,f;if(u){let A=[...s].sort((O,D)=>(D.mtime||0)-(O.mtime||0));d=A.slice(0,o.maxSourceChunks),f=A.slice(o.maxSourceChunks)}else c?(d=[],f=s):s.length>o.maxSourceChunks?(d=s.slice(0,o.maxSourceChunks),f=s.slice(o.maxSourceChunks)):(d=s,f=[]);let p=d.reduce((A,O)=>A+(O.content?O.content.length:0),0),m=d;if(p>iee){let A=iee/p;k("Truncating document contents to fit context length. Truncation ratio:",A),m=d.map(O=>({...O,content:O.content?.slice(0,Math.floor((O.content?.length||0)*A))||""}))}let h=m.map((A,O)=>({...A,__sourceId:O+1,content:rR(A.content||"")})),g=h.filter(A=>A.isFilterResult===!0),y=h.filter(A=>A.isFilterResult!==!0),v=g.length>0?$Ze(g,y):d.length===0&&f.length>0?kxe(f):Axe(h);d.length>0&&f.length>0?(u?k(`Time-dominant search: ${d.length} recent notes (full content), ${f.length} older notes (metadata-only)`):k(`Two-tier search: ${d.length} full-content docs, ${f.length} metadata-only docs`),v=`${v}

${kxe(f)}`):c&&k(`Tag-only search: ${f.length} notes (metadata-only)`);let x=h.slice(0,Math.min(20,h.length)).map(A=>({title:A.title||A.path||"Untitled",path:A.path||A.title||""})),b=j8(x);this.lastCitationSources=h.slice(0,Math.min(20,h.length)).map(A=>({title:A.title||A.path||"Untitled",path:A.path||void 0}));let _=$9e(b,o.enableInlineCitations).trim(),S=zZe("Answer the question based only on the following context:",v),P=_?`${l}

${S}

${_}`:`${l}

${S}`;return jZe(P,r)}processLocalSearchResult(n,r){let o=[],i,s;if(!n.success)return i=`<localSearch>
Search failed.
</localSearch>`,s=`Search failed: ${n.result}`,{formattedForLLM:i,formattedForDisplay:s,sources:o};try{let a=JSON.parse(n.result),l=a&&typeof a=="object"&&a.type==="local_search"&&Array.isArray(a.documents)?a.documents:null;if(!Array.isArray(l))return i=`<localSearch>
Invalid search results format.
</localSearch>`,s="Search results were in an unexpected format.",{formattedForLLM:i,formattedForDisplay:s,sources:o};BZe(l),o=DZe(l),i=this.prepareLocalSearchResult(l,r||""),s=_v.format("localSearch",i)}catch(a){ee("Failed to parse localSearch results:",a);let l=LZe(n.result);i=r?`<localSearch timeRange="${r}">
${l}
</localSearch>`:`<localSearch>
${l}
</localSearch>`,s=_v.format("localSearch",i)}return{formattedForLLM:i,formattedForDisplay:s,sources:o}}async getSystemPrompt(){return xv(this.chainManager.userMemoryManager)}formatAllToolOutputs(n){return n.length===0?"":`# Additional context:

`+n.map(o=>{let i=typeof o.output=="string"?o.output:JSON.stringify(o.output);return`<${o.tool}>
${i}
</${o.tool}>`}).join(`

`)}};var Qz=class extends dy{};It();ye();ns();Se();qe();Kr();ye();function Dxe(t){return t.map(e=>e.content).filter(e=>e&&e.trim().length>0).join(`

`)}var lP=class{constructor(e){this.modelName=e}buildToolSpecificInstructions(e){let n=[];for(let o of e)o.customPromptInstructions&&n.push(o.customPromptInstructions);let r=this.buildCopilotCommandInstructions(e);return r&&n.push(r),n.length>0?n.join(`

`):""}buildCopilotCommandInstructions(e){let n=[];for(let r of e)if(!(!r.copilotCommands||r.copilotCommands.length===0))for(let o of r.copilotCommands)n.push(`- ${o}: call the tool named ${r.id}`);return n.length===0?null:["When the user explicitly includes a Copilot command alias (e.g., @vault) in their message, treat it as a direct request to call the mapped tool before proceeding.","Honor these aliases exactly (case-insensitive):",...n,"If the referenced tool is unavailable, explain that the command cannot be fulfilled instead of ignoring it."].join(`
`)}enhanceSystemPrompt(e,n,r,o){let i=this.buildSystemPromptSections(e,n,r,o);return Dxe(i)}buildSystemPromptSections(e,n,r,o){let i=o||[],s=this.buildToolSpecificInstructions(i).trim(),l=[{id:"base-system-prompt",label:"System prompt with memory",source:"src/system-prompts/systemPromptBuilder.ts#getSystemPromptWithMemory",content:e.trimEnd()},{id:"autonomous-agent-intro",label:"Autonomous agent introduction",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Autonomous Agent Mode

You are now in autonomous agent mode. You can use tools to gather information and complete tasks step by step.

Tools are provided via native function calling - use them when needed to complete tasks.
`}],c=n.trim();return c.length>0&&l.push({id:"tool-descriptions",label:"Tool descriptions (native tool calling via bindTools)",source:"Native tool calling - schemas provided via bindTools()",content:`Available tools:
${c}`}),l.push({id:"tool-usage-guidelines",label:"Tool usage guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`# Tool Usage Guidelines

## Time-based Queries
When users ask about temporal periods (e.g., "what did I do last month", "show me notes from last week"), you MUST:
1. First call getTimeRangeMs to convert the time expression to a proper time range
2. Then use localSearch with the timeRange parameter from step 1
3. For salientTerms, ONLY use words that exist in the user's original query (excluding time expressions)

Example for "what did I do last month":
1. Call getTimeRangeMs with timeExpression: "last month"
2. Use localSearch with query matching the user's question
3. salientTerms: [] - empty because "what", "I", "do" are not meaningful search terms

Example for "meetings about project X last week":
1. Call getTimeRangeMs with timeExpression: "last week"
2. Use localSearch with query "meetings about project X"
3. salientTerms: ["meetings", "project", "X"] - these words exist in the original query

## File-related Queries

### Handle ambiguity in folder/note paths
When user mentions a folder name (e.g., "meetings folder") or a note name (e.g., "meeting note template") without providing an exact path,
you MUST first call getFileTree to find the folder or notes best matching the user's query.
If multiple results or no result, you should ask the user to provide a more specific path.
`}),s.length>0&&l.push({id:"tool-specific-instructions",label:"Tool-specific instructions",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildToolSpecificInstructions",content:s}),l.push({id:"general-guidelines",label:"General guidelines",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#BaseModelAdapter.buildSystemPromptSections",content:`## Answer Source Priority (CRITICAL)
You are the user's personal knowledge assistant. Always ground your answers in real sources rather than your own training data. Follow this priority chain:

1. **Explicit context first.** If the user has attached notes, documents, URLs, YouTube transcripts, tweets, or any other content to the conversation, use that content as your primary source. The user added it for a reason.
2. **Vault second.** For any question that could plausibly be answered by the user's notes, search the vault (localSearch). The user's own writing, meeting notes, journal entries, and saved references are highly valuable.
3. **Web third.** If the vault has no relevant results, or the question is about external/current information the vault is unlikely to contain, search the web.
4. **Your own knowledge last.** Only fall back on your training data when all of the above have been exhausted or are clearly inapplicable (e.g., explaining a general concept, writing code, or creative tasks that don't need source material).

When in doubt, search the vault. It is always better to check and find nothing than to skip the search and miss relevant notes.

## General Guidelines
- NEVER mention tool names like "localSearch", "webSearch", etc. in your responses. Use natural language like "searching your vault", "searching the web", etc.

You can use multiple tools in sequence. After each tool execution, you'll receive the results and can decide whether to use more tools or provide your final response.

Always explain your reasoning before using tools. Be conversational and clear about what you're doing.
When you've gathered enough information, provide your final response without any tool calls.

## Citation Integrity (CRITICAL)
- ONLY cite sources from tools you ACTUALLY called and received results from
- NEVER fabricate or hallucinate search results, web searches, or any tool outputs
- If you did not call a tool, do not claim you did or cite results from it
- Each citation must correspond to a real document or result returned by a tool in this conversation`}),l}enhanceUserMessage(e,n){return e}needsSpecialHandling(){return!1}},Nxe=class extends lP{isGPT5Model(){return this.modelName.includes("gpt-5")||this.modelName.includes("gpt5")}buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o),s=r||[],a=s.includes("writeFile")||s.includes("editFile"),l=[];this.isGPT5Model()?l.push(`GPT-5 SPECIFIC RULES:
- Use maximum 2 tool calls initially, then provide an answer
- Call each tool ONCE per unique query
- For optional parameters: OMIT them entirely if not needed (don't pass empty strings/null)
- For localSearch: OMIT timeRange if not doing time-based search`):l.push("CRITICAL FOR GPT MODELS: You MUST use tools when the user's request requires them. Do not just describe what you plan to do - actually call the tools."),a&&l.push(`\u{1F6A8} FILE EDITING WITH COMPOSER TOOLS \u{1F6A8}

When user asks you to edit or modify a file, you MUST:
1. Determine if it's a small edit (use editFile) or major rewrite (use writeFile)
2. Call the tool immediately - do not just describe what you plan to do

For editFile, pass the exact text to find and its replacement:
- path: vault-relative file path
- oldText: exact text to find (include surrounding context lines to make it unique)
- newText: replacement text (empty string to delete)

\u274C WRONG: "I'll help you add item 4 to the list. Let me update that for you." [No tool call = FAILURE]
\u2705 CORRECT: Actually call editFile or writeFile with proper parameters`),l.push("FINAL REMINDER FOR GPT MODELS: If the user asks you to search, find, edit, or modify anything, you MUST call the appropriate tool immediately. Do not wait for another turn.");let c=l.join(`

`);return i.push({id:"gpt-specific-guidelines",label:"GPT-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GPTModelAdapter.buildSystemPromptSections",content:c}),i}enhanceUserMessage(e,n){return n?this.getBaseEnhancement(e,n):e}getBaseEnhancement(e,n){if(!n)return e;let r=e.toLowerCase(),o=r.includes("find")||r.includes("search")||r.includes("my notes"),i=r.includes("edit")||r.includes("modify")||r.includes("update")||r.includes("change")||r.includes("fix")||r.includes("add")||r.includes("typo");return o?`${e}

REMINDER: Call the localSearch tool now.`:i?`${e}

\u{1F6A8} GPT REMINDER: Use editFile for small edits (oldText/newText parameters) or writeFile for full rewrites.`:e}needsSpecialHandling(){return!0}},Oxe=class extends lP{isThinkingModel(){return this.modelName.includes("claude-3-7-sonnet")||this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-3.7-sonnet")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-opus-4")}isClaudeSonnet4(){return this.modelName.includes("claude-sonnet-4")||this.modelName.includes("claude-4-sonnet")||this.modelName.includes("claude-sonnet-4-20250514")}buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o);if(!this.isThinkingModel())return i;let s=[`IMPORTANT FOR CLAUDE THINKING MODELS:
- You are a thinking model with internal reasoning capability
- Your thinking process will be automatically wrapped in <think> tags - do not manually add thinking tags
- Call tools AFTER your thinking is complete
- Do not provide final answers before using tools - use tools first, then provide your response based on the results

CORRECT FLOW FOR THINKING MODELS:
1. Think through the problem (this happens automatically)
2. Use tools to gather information
3. Wait for tool results
4. Provide final response based on gathered information

INCORRECT: Providing a final answer before using tools
CORRECT: Using tools first, then providing answer based on results`];return this.isClaudeSonnet4()&&s.push(`\u{1F6A8} CRITICAL INSTRUCTIONS FOR CLAUDE SONNET 4 - AUTONOMOUS AGENT MODE \u{1F6A8}

\u26A0\uFE0F  WARNING: You have a specific tendency to write complete responses immediately after tool calls. This BREAKS the autonomous agent pattern!

\u{1F504} CORRECT AUTONOMOUS AGENT ITERATION PATTERN:
1. User asks question
2. Brief sentence about what you'll do (1 sentence max)
3. Use tools to gather information
4. \u270B STOP after tool calls - Do not write anything else
5. Wait for tool results (system provides them)
6. Evaluate results and either: Use more tools OR provide final answer

\u2705 IDEAL RESPONSE FLOW:
- Brief action statement (1 sentence)
- Tool calls
- STOP (wait for results)
- Brief transition statement (1 sentence)
- More tool calls OR final answer

\u{1F3AF} CORRECT PATTERN:
I'll search your vault for piano practice information.
[Call localSearch tool]
[RESPONSE ENDS HERE - NO MORE TEXT]

\u274C WRONG PATTERN (DO NOT DO THIS):
[Call tool]
Based on the search results, here's a complete practice plan...
[This is FORBIDDEN - you haven't received results yet!]

\u{1F511} KEY UNDERSTANDING FOR CLAUDE 4:
- Brief 1-sentence explanations BEFORE tool calls are good
- Each response is ONE STEP in a multi-step process
- After tool calls, STOP and wait for the system to provide results
- Your thinking is automatically handled in <think> blocks

\u26A1 AUTONOMOUS AGENT RULES FOR CLAUDE 4:
1. If you need tools: Brief sentence + tool calls, then STOP
2. If you receive tool results: Evaluate if you need more tools
3. If you need more tools: Brief sentence + more tool calls, then STOP
4. If you have enough info: THEN provide your final response

REMEMBER: One brief sentence before tools is perfect. Nothing after tool calls.`),i.push({id:"claude-thinking-guidelines",label:"Claude thinking model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#ClaudeModelAdapter.buildSystemPromptSections",content:s.join(`

`)}),i}needsSpecialHandling(){return this.isThinkingModel()}},Rxe=class extends lP{buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o),l=[`\u{1F6A8} CRITICAL INSTRUCTIONS FOR GEMINI - AUTONOMOUS AGENT MODE \u{1F6A8}

You MUST use tools to complete tasks. DO NOT ask the user questions about how to proceed.
${(r||[]).includes("localSearch")?`
When the user mentions "my notes" or "my vault", use the localSearch tool.

\u274C WRONG:
"Let's start by searching your notes. What kind of information should I look for?"

\u2705 CORRECT: Call localSearch immediately with the user's topic as the query`:""}`.trim()];return l.push(`GEMINI SPECIFIC RULES:
1. When user mentions "my notes" about X \u2192 use localSearch with query "X"
2. DO NOT ask clarifying questions about search terms
3. DO NOT wait for permission to use tools
4. Use tools based on the user's request

\u{1F6A8} CRITICAL: SEQUENTIAL vs PARALLEL TOOL CALLS \u{1F6A8}

When one tool's OUTPUT is needed as INPUT to another tool, you MUST make them in SEPARATE responses:
1. Call the FIRST tool
2. STOP and wait for the result
3. In the NEXT response, use the result from step 1 in the SECOND tool call

\u274C WRONG (DO NOT DO THIS):
User: "Recap my last week"
- Call getTimeRangeMs AND localSearch together with made-up timeRange values
- This is WRONG because you're hallucinating the timeRange values!

\u2705 CORRECT (DO THIS):
User: "Recap my last week"
- FIRST: Call getTimeRangeMs with timeExpression "last week"
- WAIT for result
- SECOND: Call localSearch using the actual timeRange from the result

RULE: NEVER make up or guess parameter values. If you need a tool's output, call that tool FIRST, then WAIT for the result.

Remember: The user has already told you what to do. Execute it NOW with the available tools.`),i.push({id:"gemini-specific-guidelines",label:"Gemini-specific guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#GeminiModelAdapter.buildSystemPromptSections",content:l.join(`

`)}),i}enhanceUserMessage(e,n){return n?`${e}

REMINDER: Use the tools immediately. Do not ask questions. For "my notes", use localSearch.`:e}needsSpecialHandling(){return!0}},Lxe=class extends lP{buildSystemPromptSections(e,n,r,o){let i=super.buildSystemPromptSections(e,n,r,o);return i.push({id:"copilot-plus-guidelines",label:"Copilot Plus model guidance",source:"src/LLMProviders/chainRunner/utils/modelAdapter.ts#CopilotPlusModelAdapter.buildSystemPromptSections",content:`\u{1F6A8} CRITICAL: NO HALLUCINATED TOOL CALLS OR SOURCES \u{1F6A8}

You are a Copilot Plus model. You MUST follow these rules strictly:

## Tool Call Integrity
- You can ONLY reference results from tools you have ACTUALLY called in this conversation
- NEVER claim to have performed a web search unless you called the webSearch tool AND received results
- NEVER claim to have searched notes unless you called localSearch AND received results
- If you want to search the web, you MUST call the webSearch tool first - do not make up results

## Citation Rules
- Every citation [1], [2], etc. MUST correspond to a real source returned by a tool
- Do NOT invent sources like "General web search results for X" unless webSearch was actually called
- If you only called localSearch, your citations can ONLY reference notes from that search
- Count your actual tool calls - if you only made 1 tool call, you cannot have citations from multiple different tools

## Before Writing Citations
Ask yourself: "Did I actually call this tool and receive this result?"
- If YES: You may cite it
- If NO: Do NOT cite it or claim you did

REMEMBER: It is better to say "I only searched your notes, not the web" than to fabricate web search results.

## Formatting Guidelines
- AVOID using markdown tables - they often render poorly in chat interfaces
- Instead of tables, use bullet points, numbered lists, or simple formatted text
- Only use tables when the user explicitly requests tabular format`}),i}needsSpecialHandling(){return!0}},ej=class{static createAdapter(e){let n=(e.modelName||e.model||"").toLowerCase();if(k(`Creating model adapter for: ${n}`),n.includes("gpt")){let r=new Nxe(n);return r.isGPT5Model()?k("Using GPTModelAdapter with GPT-5 specific enhancements"):k("Using GPTModelAdapter"),r}return n.includes("claude")?(k("Using ClaudeModelAdapter"),new Oxe(n)):n.includes("gemini")||n.includes("google/gemini")?(k("Using GeminiModelAdapter"),new Rxe(n)):n.includes("copilot-plus")?(k("Using CopilotPlusModelAdapter"),new Lxe(n)):(k("Using BaseModelAdapter (default)"),new lP(n))}};function GZe(t){let e=["find","search","look for","look up","my notes","in my vault","from my vault","check the web","search online","from the internet","current time","what time","timer","youtube","video","transcript"],n=t.toLowerCase();return e.some(r=>n.includes(r))}function pWt(t){let{systemSections:e,rawHistory:n,adapterName:r,originalUserMessage:o,enhancedUserMessage:i}=t,s=[...e];if(n&&n.length>0){let l=wye(n);if(l.length>0){let u=dqe(l).map((d,f)=>`${f+1}. ${d.role.toUpperCase()}
${d.content}`);s.push({id:"chat-history",label:"Restored chat history from memory",source:"src/LLMProviders/chainRunner/utils/chatHistoryUtils.ts#processRawChatHistory",content:u.join(`

`)})}}s.push({id:"user-original-message",label:"Original user message",source:"Chat input",content:o});let a=i===o?" (unchanged)":"";return s.push({id:"user-enhanced-message",label:`User message after ${r}.enhanceUserMessage${a}`,source:`src/LLMProviders/chainRunner/utils/modelAdapter.ts#${r}.enhanceUserMessage`,content:i}),s}function mWt(t){return t.map(e=>`${`[Section: ${e.label} | Source: ${e.source}]`}
${e.content}`).join(`

`)}function YZe(t){let e=pWt(t),n=mWt(e),r=Dxe(t.systemSections);return{sections:e,annotatedPrompt:n,systemPrompt:r}}async function hWt(t){let{chainManager:e,adapter:n,basePrompt:r,toolDescriptions:o,toolNames:i,toolMetadata:s,userMessage:a}=t,l=n.buildSystemPromptSections(r,o,i,s),u=await e.memoryManager.getMemory().loadMemoryVariables({}),d=Array.isArray(u.history)?u.history:[],f=a.originalMessage||a.message,p=GZe(a.message),m=n.enhanceUserMessage(a.message,p);return YZe({systemSections:l,rawHistory:d,adapterName:n.constructor?.name||"ModelAdapter",originalUserMessage:f,enhancedUserMessage:m})}async function gWt(t){return xv(t.userMemoryManager)}async function ZZe(t){let{chainManager:e,adapter:n,availableTools:r,toolDescriptions:o,userMessage:i}=t,s=Vi.getInstance(),a=r.map(u=>u.name),l=r.map(u=>s.getToolMetadata(u.name)).filter(u=>u!==void 0),c=await gWt(e);return hWt({chainManager:e,adapter:n,basePrompt:c,toolDescriptions:o,toolNames:a,toolMetadata:l,userMessage:i})}function JZe(){return{status:"idle",startTime:null,elapsedSeconds:0,steps:[]}}function $xe(t){if(t.status==="idle")return"";let e=JSON.stringify(t.steps.map(n=>n.summary));return`<!--AGENT_REASONING:${t.status}:${t.elapsedSeconds}:${e}-->`}function tj(t){let e=t.match(/<!--AGENT_REASONING:(\w+):(\d+):(.+?)-->/);if(!e)return null;let[n,r,o,i]=e,s=[];try{s=JSON.parse(i)}catch{s=[]}return{hasReasoning:!0,status:r,elapsedSeconds:parseInt(o,10),steps:s,contentAfter:t.replace(n,"").trim()}}function XZe(t,e,n,r){if(!e.success)return`${Fxe(t,r)} failed`;switch(t){case"localSearch":{if(n&&n.count>0){let o=n.titles.slice(0,3),i=n.count-o.length,s=`Found ${n.count} note${n.count!==1?"s":""}: ${o.join(", ")}`;return i>0&&(s+=` +${i} more`),s}return"No matching notes found"}case"webSearch":return"Retrieved web search results";case"getTimeRangeMs":return"Calculated time range";case"readFile":return"Read file content";case"readNote":{let o=r?.notePath;return o?`Read "${o.split("/").pop()?.replace(/\.md$/i,"")||o}"`:"Read note content"}case"createNote":return"Created new note";case"appendToNote":return"Appended to note";case"editNote":return"Edited note";case"deleteNote":return"Deleted note";case"youtubeTranscript":case"youtubeTranscription":return"Fetched video transcript";case"fetchUrl":return"Fetched URL content";case"getFileTree":return"Retrieved vault file tree";case"getTagList":return"Retrieved vault tags";case"getCurrentTime":return"Got current time";case"getTimeInfoByEpoch":return"Converted timestamp";case"convertTimeBetweenTimezones":return"Converted timezone";case"obsidianDailyNote":{let o=r?.command,i=r?.vault,s=i&&i.trim().length>0?` from "${i}"`:"";return o==="daily:path"?`Got daily note path${s}`:`Loaded today's daily note${s}`}case"obsidianRandomRead":{let o=r?.vault;return o&&o.trim().length>0?`Loaded a random note from "${o}"`:"Loaded a random note"}case"obsidianProperties":{if(r?.command==="property:read"){let i=r?.name;return i?`Read property "${i}"`:"Read property"}return"Listed vault properties"}case"obsidianTasks":return"Listed vault tasks";case"obsidianLinks":{let o=r?.command;return o==="backlinks"?"Listed backlinks":o==="links"?"Listed outgoing links":o==="orphans"?"Listed orphaned notes":o==="unresolved"?"Listed unresolved links":"Queried link graph"}case"obsidianTemplates":{if(r?.command==="template:read"){let i=r?.name;return i?`Read template "${i}"`:"Read template"}return"Listed templates"}case"obsidianBases":{let o=r?.command;return o==="base:views"?"Listed base views":o==="base:query"?"Queried base data":"Listed bases"}case"indexVault":return"Indexed vault";case"updateMemory":return"Updated memory";case"writeFile":case"editFile":{let o=r?.path,i=o?o.split("/").pop()||o:"file",s=e.result||"";return s.includes('"rejected"')||s.includes("rejected")?`Edit rejected for "${i}"`:s.includes('"failed"')||s.includes("Error")?`Edit failed for "${i}"`:t==="writeFile"?`Wrote to "${i}"`:`Edited "${i}"`}default:return"Done"}}function Fxe(t,e,n){switch(t){case"localSearch":{if(n&&n.recallTerms&&n.recallTerms.length>0){let o=n.recallTerms.filter(i=>typeof i=="string"&&i.trim().length>0&&!i.includes("[object ")&&i!=="[object Object]");if(o.length>0){let i=o.slice(0,6).map(l=>`"${l}"`).join(", "),s=o.length-6,a=s>0?` +${s} more`:"";return`Searching notes for ${i}${a}`}}let r=e?.query;return r?`Searching notes for "${r.length>50?r.slice(0,50)+"...":r}"`:"Searching notes"}case"webSearch":{let r=e?.query;return r?`Searching web for "${r.length>30?r.slice(0,30)+"...":r}"`:"Searching the web"}case"getTimeRangeMs":return"Calculating time range";case"readFile":{let r=e?.path;return r?`Reading "${r.split("/").pop()||r}"`:"Reading file"}case"readNote":{let r=e?.notePath;return r?`Reading "${r.split("/").pop()?.replace(/\.md$/i,"")||r}"`:"Reading note"}case"createNote":return"Creating new note";case"appendToNote":return"Appending to note";case"editNote":return"Editing note";case"deleteNote":return"Deleting note";case"youtubeTranscript":case"youtubeTranscription":return"Fetching video transcript";case"fetchUrl":return"Fetching URL content";case"getFileTree":return"Browsing vault file tree";case"getTagList":return"Loading vault tags";case"getCurrentTime":return"Getting current time";case"getTimeInfoByEpoch":return"Converting timestamp";case"convertTimeBetweenTimezones":return"Converting timezone";case"obsidianDailyNote":{let r=e?.command,o=e?.vault,i=o&&o.trim().length>0?` from "${o}"`:"";return r==="daily:path"?`Getting daily note path${i}`:`Reading today's daily note${i}`}case"obsidianRandomRead":{let r=e?.vault;return r&&r.trim().length>0?`Reading a random note from "${r}"`:"Reading a random note"}case"obsidianProperties":{if(e?.command==="property:read"){let o=e?.name;return o?`Reading property "${o}"`:"Reading property"}return"Listing vault properties"}case"obsidianTasks":return"Listing vault tasks";case"obsidianLinks":{let r=e?.command;return r==="backlinks"?"Listing backlinks":r==="links"?"Listing outgoing links":r==="orphans"?"Listing orphaned notes":r==="unresolved"?"Listing unresolved links":"Querying link graph"}case"obsidianTemplates":{if(e?.command==="template:read"){let o=e?.name;return o?`Reading template "${o}"`:"Reading template"}return"Listing templates"}case"obsidianBases":{let r=e?.command;return r==="base:views"?"Listing base views":r==="base:query"?"Querying base data":"Listing bases"}case"indexVault":return"Indexing vault";case"updateMemory":return"Saving to memory";case"writeFile":{let r=e?.path;return r?`Writing to "${r.split("/").pop()||r}"`:"Writing to file"}case"editFile":{let r=e?.path;return r?`Editing "${r.split("/").pop()||r}"`:"Editing file"}default:return"Processing"}}function yWt(t,e){return t.length>e?t.slice(0,e-3)+"...":t}function QZe(t){if(!t||t.trim().length===0)return null;let e=t.trim().split(`
`)[0];return yWt(e,100)}function wWt(t,e){let n=new Set(t.toLowerCase().split(/\s+/).filter(Boolean)),r=new Set(e.toLowerCase().split(/\s+/).filter(Boolean));if(n.size===0&&r.size===0)return 1;if(n.size===0||r.size===0)return 0;let o=0;for(let l of n)r.has(l)&&o++;let i=n.size+r.size-o,s=o/i,a=o/Math.min(n.size,r.size);return Math.max(s,a)}function Uxe(t,e,n=.6){for(let r of e)if(wWt(t,r)>=n)return r;return null}var vWt=/^(user|assistant|system)\s*$/;function e7e(t){return t&&t.split(`
`).filter(e=>!vWt.test(e)).join(`
`)}var t7e=`## Agent Behavior
- You have a limited number of tool calls. Use them wisely.
- NEVER search for the same or very similar query twice. If results were insufficient, try substantially different terms.
- After 1-2 searches, synthesize an answer from the results you have. Do not keep searching unless the results are clearly insufficient.
- If you have enough information to answer, respond directly without calling any more tools.`,nj=class extends dy{constructor(){super(...arguments);this.llmFormattedMessages=[];this.lastDisplayedContent="";this.reasoningState=JZe();this.reasoningTimerInterval=null;this.accumulatedContent="";this.allReasoningSteps=[];this.abortHandledByTimer=!1}getAvailableTools(){let n=q(),r=Vi.getInstance();r.getAllTools().length===0&&yR(this.chainManager.app?.vault);let o=new Set(n.autonomousAgentEnabledToolIds||[]);return r.getEnabledTools(o,!!this.chainManager.app?.vault)}startReasoningTimer(n,r){this.reasoningState={status:"reasoning",startTime:Date.now(),elapsedSeconds:0,steps:[]},this.accumulatedContent="",this.allReasoningSteps=[],this.abortHandledByTimer=!1;let o=["Understanding your question","Analyzing your request","Processing your query","Thinking about this","Considering your question","Working on this","Pondering the possibilities","Diving into your request","Let me think about this","Exploring your question","Getting my thoughts together","Examining the details","Looking into this","Mulling this over","On it","Firing up the neurons","Connecting the dots","Brewing some ideas","Spinning up the gears","Warming up the engines","Crunching the details","Putting on my thinking cap","Consulting my notes","Gathering my thoughts","Rolling up my sleeves"],i=o[Math.floor(Math.random()*o.length)];this.addReasoningStep(i),this.reasoningTimerInterval=window.setInterval(()=>{if(r?.signal.aborted&&this.reasoningState.status==="reasoning"){this.stopReasoningTimer(),this.reasoningState.status="complete",this.abortHandledByTimer=!0;let s=this.buildReasoningBlockMarkup(),a="The response was interrupted.",l=s?s+`

`+a:a;n(l);return}if(this.reasoningState.startTime&&this.reasoningState.status==="reasoning"){this.reasoningState.elapsedSeconds=Math.floor((Date.now()-this.reasoningState.startTime)/1e3);let s=this.buildReasoningBlockMarkup(),a=s?s+(this.accumulatedContent?`

`+this.accumulatedContent:""):this.accumulatedContent;n(a)}},100)}addReasoningStep(n,r,o=!1){let i={timestamp:Date.now(),summary:n,toolName:r};this.allReasoningSteps.push(i),!o&&(this.reasoningState.steps.push(i),this.reasoningState.steps.length>4&&this.reasoningState.steps.shift())}stopReasoningTimer(){this.reasoningTimerInterval&&(window.clearInterval(this.reasoningTimerInterval),this.reasoningTimerInterval=null),this.reasoningState.status="collapsed"}buildReasoningBlockMarkup(){if(this.reasoningState.status==="complete"||this.reasoningState.status==="collapsed"){let n={...this.reasoningState,steps:this.allReasoningSteps};return $xe(n)}return $xe(this.reasoningState)}static async generateSystemPrompt(n,r,o){let i=await xv(o),s=Vi.getInstance(),l=n.map(u=>s.getToolMetadata(u.name)).filter(u=>u!==void 0).filter(u=>u.customPromptInstructions).map(u=>`For ${u.displayName}: ${u.customPromptInstructions}`).join(`
`),c=[i];return l&&c.push(`## Tool Guidelines
${l}`),c.push(t7e),c.join(`

`)}async buildToolPromptDebugReport(n){let r=this.getAvailableTools(),o=ej.createAdapter(this.chainManager.chatModelManager.getChatModel()),i=r.map(s=>`${s.name}: ${s.description}`).join(`
`);return ZZe({chainManager:this.chainManager,adapter:o,availableTools:r,toolDescriptions:i,userMessage:n})}applyCiCOrderingToLocalSearchResult(n,r){return VZe(n,r)}async run(n,r,o,i,s){this.llmFormattedMessages=[],this.lastDisplayedContent="";let a=await _p({isAutonomousAgent:!0}),l=this.chainManager.chatModelManager.getChatModel(),c=ej.createAdapter(l),u=new of(o,!0);if(!a){await this.handleError(new Error("Invalid license key"),u.processErrorChunk.bind(u));let m=u.close().content;return this.handleResponse(m,n,r,i,o,void 0)}let d=l?.modelName;if(!n.contextEnvelope)throw new Error("[Agent] Context envelope is required but not available. Cannot proceed with autonomous agent.");k("[Agent] Using native tool calling with ReAct pattern");let p=await this.prepareAgentConversation(n,l,s.updateLoadingMessage);try{this.startReasoningTimer(o,r);let m=await this.runReActLoop({boundModel:p.loopDeps.boundModel,chatModel:l,tools:p.loopDeps.availableTools,messages:p.messages,originalPrompt:p.originalUserPrompt,abortController:r,updateCurrentAiMessage:o,processLocalSearchResult:p.loopDeps.processLocalSearchResult,applyCiCOrderingToLocalSearchResult:p.loopDeps.applyCiCOrderingToLocalSearchResult,adapter:c});if(this.abortHandledByTimer)return this.lastDisplayedContent="","";let h=iP(m.sources);return p.messages.length>0&&UC({messages:[...p.messages],modelName:d,contextEnvelope:n.contextEnvelope}),await this.handleResponse(m.finalResponse,n,r,i,o,h.length>0?h:void 0,this.llmFormattedMessages.join(`

`),m.responseMetadata),this.lastDisplayedContent="",m.finalResponse}catch(m){if(this.stopReasoningTimer(),m.name==="AbortError"||r.signal.aborted)return k("Autonomous agent stream aborted by user",{reason:r.signal.reason}),"";z("Autonomous agent failed, falling back to regular Plus mode:",m);try{return await new dy(this.chainManager).run(n,r,o,i,s)}catch(h){z("Fallback to regular Plus mode also failed:",h),this.lastDisplayedContent&&u.processChunk({content:this.lastDisplayedContent});let g=Xt(m),y=`

Fallback to regular Plus mode also failed: `+Xt(h);await this.handleError(new Error(g+y),u.processErrorChunk.bind(u));let w=u.close().content;return this.handleResponse(w,n,r,i,o,void 0,w)}}}async prepareAgentConversation(n,r,o){let i=[],s=this.getAvailableTools(),a=r.modelName||r.model||"unknown";if(typeof r.bindTools!="function")throw new Error(`Model ${a} does not support native tool calling (bindTools not available). Agent mode requires a model with tool calling support.`);let l=r.bindTools(s),c={availableTools:s,boundModel:l,processLocalSearchResult:this.processLocalSearchResult.bind(this),applyCiCOrderingToLocalSearchResult:this.applyCiCOrderingToLocalSearchResult.bind(this)},u=n.contextEnvelope,d=sy.convert(u,{includeSystemMessage:!0,mergeUserContent:!0,debug:!1}),f=this.chainManager.memoryManager.getMemory(),p=d.find(T=>T.role==="system"),m=Vi.getInstance(),g=s.map(T=>m.getToolMetadata(T.name)).filter(T=>T!==void 0).filter(T=>T.customPromptInstructions).map(T=>`For ${T.displayName}: ${T.customPromptInstructions}`).join(`
`),y=[p?.content||"",g?`
## Tool Guidelines
${g}`:"",t7e].filter(Boolean).join(`

`);y&&i.push(new Vu({content:y}));let x=u.layers.find(T=>T.id==="L5_USER")?.text||""||n.originalMessage||n.message,b=[];await FC(f,b);for(let T of b)T.role==="user"?i.push(new Zo(T.content)):i.push(new kn(T.content));let _=d.find(T=>T.role==="user");if(_){let S=this.isMultimodalModel(r)?await this.buildMessageContent(_.content,n):_.content;i.push(new Zo(S))}return{messages:i,collectedSources:[],originalUserPrompt:x,loopDeps:c}}async runReActLoop(n){let{boundModel:r,tools:o,messages:i,originalPrompt:s,abortController:a,updateCurrentAiMessage:l,processLocalSearchResult:c,applyCiCOrderingToLocalSearchResult:u}=n,d=q().autonomousAgentMaxIterations,f=[],p=Date.now(),m=[],h=0,g=0,y;for(;g<d&&!a.signal.aborted;){let T=Date.now()-p;if(T>=see){ee(`Agent loop timed out after ${Math.round(T/1e3)}s`);break}g++;let{content:S,aiMessage:P,streamingResult:A}=await this.streamModelResponse(r,i,a,l);y={wasTruncated:A.wasTruncated,tokenUsage:A.tokenUsage??void 0};let O=S?.trim();k(`[Agent] Iteration ${g} model output:`,O?O.slice(0,200):"(empty)");let D=P.tool_calls||[];if(k(`[Agent] Iteration ${g}: ${D.length} tool call(s)`),D.length===0){k(`[Agent] Iteration ${g}: Final response (no tool calls)`),this.stopReasoningTimer(),this.reasoningState.status="complete",i.push(P);let V=S;if(!V||V.trim()===""){let G=P.tool_call_chunks??[];ee(`[Agent] Empty response detected (iteration ${g}). Content length: ${S?.length??0}, tool_call_chunks from model: ${G.length}, parsed tool_calls: ${D.length}. This may indicate tool calls were dropped or the model produced only thinking tokens.`),V="The model did not produce a response. Please try again or switch to a different model."}let H=this.buildReasoningBlockMarkup(),te=20,fe=5,me="";for(let G=0;G<V.length&&!a.signal.aborted;G+=te){me+=V.slice(G,G+te);let J=H?H+`

`+me:me;l(J),G+te<V.length&&await new Promise(M=>window.setTimeout(M,fe))}let j=H?H+`

`+V:V;return l(j),{finalResponse:j,sources:f,responseMetadata:y}}let $=e7e(S),B=new kn({content:$,tool_calls:P.tool_calls});if(i.push(B),g>1&&$&&$.trim().length>0){let V=QZe($);V&&this.addReasoningStep(V)}let W=[],F=[],Z=[];for(let V of D){if(V.name==="localSearch"){let H=V.args?.query;if(H){let te=Uxe(H,m)??Uxe(H,F);if(te){k(`[Agent] Dedup: "${H}" (similar to: "${te}")`),i.push(vye(V.id||PG(),V.name,`You already searched for a similar query: "${te}". Synthesize your answer from existing results.`));continue}F.push(H),Z.push(H)}else Z.push(null)}else Z.push(null);W.push(V)}for(let V=0;V<W.length;V++){let H=W[V];if(a.signal.aborted)break;let te={name:H.name,args:H.args},fe=Fxe(H.name,te.args);this.addReasoningStep(fe,H.name),TYe(te,g);let me=await _Ye(te,o,s),j;if(H.name==="localSearch"&&me.success){let M=c(me);f.push(...M.sources),j={titles:M.sources.map(E=>E.title),count:M.sources.length},me.result=u(M.formattedForLLM,s||"")}if(IYe(H.name,me),H.name==="localSearch"&&me.success){let M=Z[V];M&&m.push(M)}let G=XZe(H.name,me,j,te.args);(!me.success||j)&&this.addReasoningStep(G,H.name);let J=vye(H.id||PG(),H.name,me.result);i.push(J)}if(W.length===0&&D.length>0){if(h++,k(`[Agent] All ${D.length} tool call(s) skipped as duplicates (${h} consecutive)`),h>=2){k("[Agent] Model stuck in search loop, forcing synthesis without tools"),this.addReasoningStep("Synthesizing answer from search results"),i.push(new Zo(`You have already searched and found relevant results. Do not call any tools. Answer the following question now based ONLY on the search results above:

`+s));let V=await this.streamModelResponse(n.chatModel,i,a,l);y={wasTruncated:V.streamingResult.wasTruncated,tokenUsage:V.streamingResult.tokenUsage??void 0},this.stopReasoningTimer(),this.reasoningState.status="complete";let H=this.buildReasoningBlockMarkup(),te=V.content||"Unable to synthesize a response from the search results.",fe=H?H+`

`+te:te;return l(fe),{finalResponse:fe,sources:f,responseMetadata:y}}}else h=0}this.stopReasoningTimer(),this.reasoningState.status="complete";let w=this.buildReasoningBlockMarkup();if(a.signal.aborted){if(k("Agent reasoning interrupted by user"),this.abortHandledByTimer)return{finalResponse:"",sources:f,responseMetadata:y};let T="The response was interrupted.";return{finalResponse:w?w+`

`+T:T,sources:f,responseMetadata:y}}let v=Date.now()-p,x=v>=see;x?ee(`Agent loop timed out after ${Math.round(v/1e3)}s`):ee(`Agent reached max iterations (${d})`);let b=x?"I've reached the time limit for reasoning. Here's what I found so far based on the search results.":"I've reached the maximum number of tool calls. Here's what I found so far based on the search results.";return{finalResponse:w?w+`

`+b:b,sources:f,responseMetadata:y}}async streamModelResponse(n,r,o,i){let s=new Map,a=new of(()=>{},!0),l="";try{let c=await Nc(()=>n.stream(r,{signal:o.signal}));for await(let g of c){if(o.signal.aborted)break;let y=g;if(y.response_metadata?.finish_reason==="MALFORMED_FUNCTION_CALL")throw ee("Backend returned MALFORMED_FUNCTION_CALL - falling back to non-agent mode"),new Error("MALFORMED_FUNCTION_CALL: Model does not support native tool calling");let v=y.tool_call_chunks;if(v&&Array.isArray(v))for(let b of v)mqe(s,b);let x=typeof y.content=="string"?y.content:"";x&&(l+=x),a.processChunk(y)}let u=a.close(),d=u.content,f=l.trim(),p=d.trim();f&&!p&&k(`[Agent] Model produced content that was entirely stripped (likely think blocks): ${f.slice(0,300)}`);let m=EG(s),h=new kn({content:d,tool_calls:m.map(g=>({id:g.id,name:g.name,args:g.args,type:"tool_call"}))});return{content:d,aiMessage:h,streamingResult:u}}catch(c){if(z(`Stream error: ${c.message}`),c.name==="AbortError"||o.signal.aborted){let u=a.close();return{content:u.content,aiMessage:new kn({content:u.content}),streamingResult:u}}throw c}}};ye();Se();qe();Nf();ph();var uJe=require("obsidian");eP();var SR=[{tag:"note_context",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"active_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"embedded_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"vault_note",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"retrieved_document",sourceType:"note",recoverable:!0,sourceExtractor:"path"},{tag:"url_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"web_tab_context",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"active_web_tab",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"youtube_video_context",sourceType:"youtube",recoverable:!0,sourceExtractor:"url"},{tag:"twitter_content",sourceType:"url",recoverable:!0,sourceExtractor:"url"},{tag:"embedded_pdf",sourceType:"pdf",recoverable:!0,sourceExtractor:"name"},{tag:"selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"web_selected_text",sourceType:"selected_text",recoverable:!1,sourceExtractor:null},{tag:"localSearch",sourceType:"note",recoverable:!0,sourceExtractor:null}],S9=new Map;for(let t of SR)S9.set(t.tag,t);function dP(t){return S9.get(t)?.sourceType??"unknown"}function T9(t){return S9.get(t)?.recoverable??!1}function TR(t,e){let n=S9.get(e);if(!n?.sourceExtractor)return"";let r=n.sourceExtractor;return new RegExp(`<${r}>([^<]+)</${r}>`).exec(t)?.[1]??""}function uj(t){let e=/<content>([\s\S]*?)<\/content>/.exec(t);return e?e[1]:t}var pf={previewCharsPerSection:500,maxSections:20,verbatimThreshold:5e3};function fP(t,e=500,n=20){let r=t.split(/(?=^#{1,6}\s+)/m).filter(a=>a.trim());if(r.length<=1)return Yxe(t,e*4);let o=r.slice(0,n),i=r.length>n,s=o.map(a=>{let l=a.trim().split(`
`),c=l[0],u=l.slice(1).join(`
`).trim();return u.length<=e?a.trim():`${c}
${Yxe(u,e)}`}).join(`

`);return i?`${s}

[... ${r.length-n} more sections omitted ...]`:s}function Yxe(t,e){if(t.length<=e)return t;let n=t.slice(0,e),r=/[.!?]\s+/g,o=-1,i;for(;(i=r.exec(n))!==null;)i.index>e*.5&&(o=i.index+1);if(o>0)return n.slice(0,o)+" ...";let s=n.lastIndexOf(`

`);if(s>e*.5)return n.slice(0,s)+`

...`;let a=n.lastIndexOf(" ");return a>e*.8?n.slice(0,a)+" ...":n+"..."}function I9(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function zWt(){return["localSearch","note_context","active_note","retrieved_document","url_content","youtube_video_context"].map(e=>({pattern:new RegExp(`<${e}[^>]*>[\\s\\S]*?</${e}>`,"g"),tag:e}))}var jWt=zWt(),IR="Tool 'readNote' result: ";function VWt(t,e){if(t[e]!=="{")return null;let n=0,r=!1,o=!1;for(let i=e;i<t.length;i++){let s=t[i];if(o){o=!1;continue}if(s==="\\"&&r){o=!0;continue}if(s==='"'){r=!r;continue}if(!r){if(s==="{")n++;else if(s==="}"&&(n--,n===0))return{json:t.slice(e,i+1),endPos:i+1}}}return null}function PR(t,e={}){return Array.isArray(t)?t.map(n=>n.type==="text"&&typeof n.text=="string"?{...n,text:g7e(n.text,e)}:n):typeof t=="string"?g7e(t,e):t}function g7e(t,e={}){let n=e.verbatimThreshold??pf.verbatimThreshold,r=t;for(let{pattern:o,tag:i}of jWt)o.lastIndex=0,r=r.replace(o,s=>s.length<n?s:HWt(s,i,e));return r=WWt(r,n,e),r}function WWt(t,e,n){let r="",o=0;for(;o<t.length;){let i=t.indexOf(IR,o);if(i===-1){r+=t.slice(o);break}r+=t.slice(o,i);let s=i+IR.length,a=VWt(t,s);if(!a){r+=IR,o=s;continue}try{let l=JSON.parse(a.json);if(l.content&&l.content.length>e){let c=qWt(l,n);r+=`${IR}${JSON.stringify(c)}`}else r+=IR+a.json}catch{r+=IR+a.json}o=a.endPos}return r}function HWt(t,e,n={}){if(!T9(e))return t;if(e==="localSearch")return KWt(t,n);let r=TR(t,e),o=uj(t),i=dP(e),s=n.previewCharsPerSection??pf.previewCharsPerSection,a=n.maxSections??pf.maxSections,l=fP(o,s,a);return`<prior_context source="${I9(r)}" type="${i}">
${l}
</prior_context>`}function KWt(t,e={}){let n=e.previewCharsPerSection??pf.previewCharsPerSection,r=/<document>([\s\S]*?)<\/document>/g,o=[],i;for(;(i=r.exec(t))!==null;){let a=i[1],l=/<path>([^<]+)<\/path>/.exec(a),c=/<title>([^<]+)<\/title>/.exec(a),u=/<content>([\s\S]*?)<\/content>/.exec(a),d=l?.[1]??"",f=c?.[1]??d.split("/").pop()??"Untitled",p=u?.[1]??"",m=p.length>n?p.slice(0,n)+"...":p;o.push({path:d,title:f,preview:m.trim()})}if(o.length===0){let a=uj(t);return`<prior_context source="localSearch" type="note">
${fP(a,n,e.maxSections??pf.maxSections)}
</prior_context>`}let s=o.map((a,l)=>`${l+1}. [[${a.title}]] (${a.path})
   ${a.preview}`).join(`

`);return`<prior_context source="localSearch" type="note">
[${o.length} search results - use localSearch to re-query]

${s}
</prior_context>`}function qWt(t,e={}){let{content:n,notePath:r,noteTitle:o,...i}=t;if(!n||typeof n!="string")return t;let s=e.previewCharsPerSection??pf.previewCharsPerSection,a=e.maxSections??pf.maxSections,l=fP(n,s,a);return{...i,notePath:r,noteTitle:o,content:`[COMPACTED - use readNote to get full content]

${l}`,_wasCompacted:!0}}ye();Se();var GWt=Object.defineProperty;var ER=(t,e)=>{for(var n in e)GWt(t,n,{get:e[n],enumerable:!0})};ph();var YWt=`Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.

EXAMPLE
Current summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.

New lines of conversation:
Human: Why do you think artificial intelligence is a force for good?
AI: Because artificial intelligence will help humans reach their full potential.

New summary:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.
END OF EXAMPLE

Current summary:
{summary}

New lines of conversation:
{new_lines}

New summary:`,y7e=new ki({inputVariables:["summary","new_lines"],template:YWt}),ZWt=`You are an assistant to a human, powered by a large language model trained by OpenAI.

You are designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, you are able to generate human-like text based on the input you receive, allowing you to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.

You are constantly learning and improving, and your capabilities are constantly evolving. You are able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. You have access to some personalized information provided by the human in the Context section below. Additionally, you are able to generate your own text based on the input you receive, allowing you to engage in discussions and provide explanations and descriptions on a wide range of topics.

Overall, you are a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether the human needs help with a specific question or just wants to have a conversation about a particular topic, you are here to assist.

Context:
{entities}

Current conversation:
{history}
Last line:
Human: {input}
You:`,w7e=new ki({inputVariables:["entities","history","input"],template:ZWt}),JWt=`You are an AI assistant reading the transcript of a conversation between an AI and a human. Extract all of the proper nouns from the last line of conversation. As a guideline, a proper noun is generally capitalized. You should definitely extract all names and places.

The conversation history is provided just in case of a coreference (e.g. "What do you know about him" where "him" is defined in a previous line) -- ignore items mentioned there that are not in the last line.

Return the output as a single comma-separated list, or NONE if there is nothing of note to return (e.g. the user is just issuing a greeting or having a simple conversation).

EXAMPLE
Conversation history:
Person #1: my name is Jacob. how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff.
Output: Jacob,Langchain
END OF EXAMPLE

EXAMPLE
Conversation history:
Person #1: how's it going today?
AI: "It's going great! How about you?"
Person #1: good! busy working on Langchain. lots to do.
AI: "That sounds like a lot of work! What kind of things are you doing to make Langchain better?"
Last line:
Person #1: i'm trying to improve Langchain's interfaces, the UX, its integrations with various products the user might want ... a lot of stuff. I'm working with Person #2.
Output: Langchain, Person #2
END OF EXAMPLE

Conversation history (for reference only):
{history}
Last line of conversation (for extraction):
Human: {input}

Output:`,v7e=new ki({inputVariables:["history","input"],template:JWt}),XWt=`You are an AI assistant helping a human keep track of facts about relevant people, places, and concepts in their life. Update and add to the summary of the provided entity in the "Entity" section based on the last line of your conversation with the human. If you are writing the summary for the first time, return a single sentence.
The update should only include facts that are relayed in the last line of conversation about the provided entity, and should only contain facts about the provided entity.

If there is no new information about the provided entity or the information is not worth noting (not an important or relevant fact to remember long-term), output the exact string "UNCHANGED" below.

Full conversation history (for context):
{history}

Entity to summarize:
{entity}

Existing summary of {entity}:
{summary}

Last line of conversation:
Human: {input}
Updated summary (or the exact string "UNCHANGED" if there is no new information about {entity} above):`,x7e=new ki({inputVariables:["entity","summary","history","input"],template:XWt});$n();Rb();Wu();Bb();Kr();var QWt=class extends zu{addUserMessage(t){return this.addMessage(new Zo(t))}addAIMessage(t){return this.addMessage(new kn(t))}async addMessages(t){for(let e of t)await this.addMessage(e)}clear(){throw new Error("Not implemented.")}},P9=class extends QWt{constructor(e){super(...arguments);I(this,"lc_namespace",["langchain","stores","message","in_memory"]);I(this,"messages",[]);this.messages=e??[]}async getMessages(){return this.messages}async addMessage(e){this.messages.push(e)}async clear(){this.messages=[]}};$n();var AR=class{},b7e=(t,e)=>{if(e!==void 0)return t[e];let n=Object.keys(t);if(n.length===1)return t[n[0]]},kR=(t,e)=>{let n=b7e(t,e);if(!n)throw new Error(`input values have ${Object.keys(t).length} keys, you must specify an input key or pass only 1 key as input`);return n},E9=(t,e)=>{let n=b7e(t,e);if(!n&&n!=="")throw new Error(`output values have ${Object.keys(t).length} keys, you must specify an output key or pass only 1 key as output`);return n};function Zxe(t,e){let n=Object.keys(t).filter(r=>!e.includes(r)&&r!=="stop");if(n.length!==1)throw new Error(`One input key expected, but got ${n.length}`);return n[0]}var eHt={};ER(eHt,{BaseChatMemory:()=>iu});var iu=class extends AR{constructor(e){super();I(this,"chatHistory");I(this,"returnMessages",!1);I(this,"inputKey");I(this,"outputKey");this.chatHistory=e?.chatHistory??new P9,this.returnMessages=e?.returnMessages??this.returnMessages,this.inputKey=e?.inputKey??this.inputKey,this.outputKey=e?.outputKey??this.outputKey}async saveContext(e,n){await this.chatHistory.addUserMessage(kR(e,this.inputKey)),await this.chatHistory.addAIMessage(E9(n,this.outputKey))}async clear(){await this.chatHistory.clear()}};pP();Kr();var gj=class extends iu{constructor(e){let{returnMessages:n,inputKey:r,outputKey:o,chatHistory:i,humanPrefix:s,aiPrefix:a,llm:l,prompt:c,summaryChatMessageClass:u}=e;super({returnMessages:n,inputKey:r,outputKey:o,chatHistory:i});I(this,"memoryKey","history");I(this,"humanPrefix","Human");I(this,"aiPrefix","AI");I(this,"llm");I(this,"prompt",y7e);I(this,"summaryChatMessageClass",Vu);this.memoryKey=e?.memoryKey??this.memoryKey,this.humanPrefix=s??this.humanPrefix,this.aiPrefix=a??this.aiPrefix,this.llm=l,this.prompt=c??this.prompt,this.summaryChatMessageClass=u??this.summaryChatMessageClass}async predictNewSummary(e,n){let r=ui(e,this.humanPrefix,this.aiPrefix);return await new Ka({llm:this.llm,prompt:this.prompt}).predict({summary:n,new_lines:r})}},nJe=class extends gj{constructor(e){super(e);I(this,"buffer","")}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){return this.returnMessages?{[this.memoryKey]:[new this.summaryChatMessageClass(this.buffer)]}:{[this.memoryKey]:this.buffer}}async saveContext(e,n){await super.saveContext(e,n);let r=await this.chatHistory.getMessages();this.buffer=await this.predictNewSummary(r.slice(-2),this.buffer)}async clear(){await super.clear(),this.buffer=""}};Kr();var rJe=class extends gj{constructor(e){super(e);I(this,"movingSummaryBuffer","");I(this,"maxTokenLimit",2e3);this.maxTokenLimit=e?.maxTokenLimit??this.maxTokenLimit}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=await this.chatHistory.getMessages();this.movingSummaryBuffer&&(n=[new this.summaryChatMessageClass(this.movingSummaryBuffer),...n]);let r;return this.returnMessages?r=n:r=ui(n,this.humanPrefix,this.aiPrefix),{[this.memoryKey]:r}}async saveContext(e,n){await super.saveContext(e,n),await this.prune()}async prune(){let e=await this.chatHistory.getMessages();this.movingSummaryBuffer&&(e=[new this.summaryChatMessageClass(this.movingSummaryBuffer),...e]);let n=await this.llm.getNumTokens(ui(e,this.humanPrefix,this.aiPrefix));if(n>this.maxTokenLimit){let r=[];for(;n>this.maxTokenLimit;){let o=e.shift();o&&(r.push(o),n=await this.llm.getNumTokens(ui(e,this.humanPrefix,this.aiPrefix)))}this.movingSummaryBuffer=await this.predictNewSummary(r,this.movingSummaryBuffer)}}async clear(){await super.clear(),this.movingSummaryBuffer=""}};Kr();var R9=class extends iu{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});I(this,"humanPrefix","Human");I(this,"aiPrefix","AI");I(this,"memoryKey","history");this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:n}:{[this.memoryKey]:ui(n,this.humanPrefix,this.aiPrefix)}}};Kr();var L9=class extends iu{constructor(e){super({returnMessages:e?.returnMessages??!1,chatHistory:e?.chatHistory,inputKey:e?.inputKey,outputKey:e?.outputKey});I(this,"humanPrefix","Human");I(this,"aiPrefix","AI");I(this,"memoryKey","history");I(this,"k",5);this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.k=e?.k??this.k}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:n.slice(-this.k*2)}:{[this.memoryKey]:ui(n.slice(-this.k*2),this.humanPrefix,this.aiPrefix)}}};var dHt={};ER(dHt,{formatDocumentsAsString:()=>ebe});var ebe=t=>t.map(e=>e.pageContent).join(`

`);iv();var oJe=class extends AR{constructor(e){super();I(this,"vectorStoreRetriever");I(this,"inputKey");I(this,"memoryKey");I(this,"returnDocs");I(this,"metadata");this.vectorStoreRetriever=e.vectorStoreRetriever,this.inputKey=e.inputKey,this.memoryKey=e.memoryKey??"memory",this.returnDocs=e.returnDocs??!1,this.metadata=e.metadata}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=kR(e,this.inputKey),r=await this.vectorStoreRetriever.invoke(n);return{[this.memoryKey]:this.returnDocs?r:ebe(r)}}async saveContext(e,n){let r=typeof this.metadata=="function"?this.metadata(e,n):this.metadata,o=Object.entries(e).filter(([i])=>i!==this.memoryKey).concat(Object.entries(n)).map(([i,s])=>`${i}: ${s}`).join(`
`);await this.vectorStoreRetriever.addDocuments([new fi({pageContent:o,metadata:r})])}};pP();Rb();var iJe=class extends zu{};var sJe=class extends iJe{constructor(){super();I(this,"lc_namespace",["langchain","stores","entity","in_memory"]);I(this,"store");this.store=Object.create(null)}async get(e,n){return e in this.store?this.store[e]:n}async set(e,n){this.store[e]=n}async delete(e){delete this.store[e]}async exists(e){return e in this.store}async clear(){this.store=Object.create(null)}};Kr();var aJe=class extends iu{constructor(e){super({chatHistory:e.chatHistory,returnMessages:e.returnMessages??!1,inputKey:e.inputKey,outputKey:e.outputKey});I(this,"entityExtractionChain");I(this,"entitySummarizationChain");I(this,"entityStore");I(this,"entityCache",[]);I(this,"k",3);I(this,"chatHistoryKey","history");I(this,"llm");I(this,"entitiesKey","entities");I(this,"humanPrefix");I(this,"aiPrefix");this.llm=e.llm,this.humanPrefix=e.humanPrefix,this.aiPrefix=e.aiPrefix,this.chatHistoryKey=e.chatHistoryKey??this.chatHistoryKey,this.entitiesKey=e.entitiesKey??this.entitiesKey,this.entityExtractionChain=new Ka({llm:this.llm,prompt:e.entityExtractionPrompt??v7e}),this.entitySummarizationChain=new Ka({llm:this.llm,prompt:e.entitySummarizationPrompt??x7e}),this.entityStore=e.entityStore??new sJe,this.entityCache=e.entityCache??this.entityCache,this.k=e.k??this.k}get memoryKeys(){return[this.chatHistoryKey]}get memoryVariables(){return[this.entitiesKey,this.chatHistoryKey]}async loadMemoryVariables(e){let n=this.inputKey??Zxe(e,this.memoryVariables),r=await this.chatHistory.getMessages(),o=ui(r.slice(-this.k*2),this.humanPrefix,this.aiPrefix),i=await this.entityExtractionChain.predict({history:o,input:e[n]}),s=i.trim()==="NONE"?[]:i.split(",").map(c=>c.trim()),a={};for(let c of s)a[c]=await this.entityStore.get(c,"No current information known.");this.entityCache=[...s];let l=this.returnMessages?r.slice(-this.k*2):o;return{[this.chatHistoryKey]:l,[this.entitiesKey]:a}}async saveContext(e,n){await super.saveContext(e,n);let r=this.inputKey??Zxe(e,this.memoryVariables),o=await this.chatHistory.getMessages(),i=ui(o.slice(-this.k*2),this.humanPrefix,this.aiPrefix),s=e[r];for(let a of this.entityCache){let l=await this.entityStore.get(a,"No current information known."),c=await this.entitySummarizationChain.predict({summary:l,entity:a,history:i,input:s});c.trim()!=="UNCHANGED"&&await this.entityStore.set(a,c.trim())}}async clear(){await super.clear(),await this.entityStore.clear()}};var lJe=class extends iu{constructor(e){super({chatHistory:e?.chatHistory,returnMessages:e?.returnMessages??!1,inputKey:e?.inputKey,outputKey:e?.outputKey});I(this,"humanPrefix","Human");I(this,"aiPrefix","AI");I(this,"memoryKey","history");I(this,"memories",[]);this.memories=e?.memories??this.memories,this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.checkRepeatedMemoryVariable(),this.checkInputKey()}checkRepeatedMemoryVariable(){let e=[];for(let n of this.memories){let r=e.filter(o=>n.memoryKeys.includes(o));if(r.length>0)throw new Error(`The same variables ${[...r]} are found in multiple memory objects, which is not allowed by CombinedMemory.`);e.push(...n.memoryKeys)}}checkInputKey(){for(let e of this.memories)e.chatHistory!==void 0&&e.inputKey===void 0&&console.warn(`When using CombinedMemory, input keys should be set so the input is known. Was not set on ${e}.`)}async loadMemoryVariables(e){let n={};for(let r of this.memories){let o=await r.loadMemoryVariables(e);n={...n,...o}}return n}async saveContext(e,n){for(let r of this.memories)await r.saveContext(e,n)}async clear(){for(let e of this.memories)typeof e.clear=="function"&&await e.clear()}get memoryKeys(){let e=[];for(let n of this.memories)e.push(...n.memoryKeys);return e}};Kr();var cJe=class extends iu{constructor(e){super(e);I(this,"humanPrefix","Human");I(this,"aiPrefix","AI");I(this,"memoryKey","history");I(this,"maxTokenLimit",2e3);I(this,"llm");this.llm=e.llm,this.humanPrefix=e?.humanPrefix??this.humanPrefix,this.aiPrefix=e?.aiPrefix??this.aiPrefix,this.memoryKey=e?.memoryKey??this.memoryKey,this.maxTokenLimit=e?.maxTokenLimit??this.maxTokenLimit}get memoryKeys(){return[this.memoryKey]}async loadMemoryVariables(e){let n=await this.chatHistory.getMessages();return this.returnMessages?{[this.memoryKey]:n}:{[this.memoryKey]:ui(n,this.humanPrefix,this.aiPrefix)}}async saveContext(e,n){await super.saveContext(e,n);let r=await this.chatHistory.getMessages(),o=await this.llm.getNumTokens(ui(r,this.humanPrefix,this.aiPrefix));if(o>this.maxTokenLimit){let i=[];for(;o>this.maxTokenLimit;)i.push(r.shift()),o=await this.llm.getNumTokens(ui(r,this.humanPrefix,this.aiPrefix))}}};Kr();var fHt={};ER(fHt,{BaseChatMemory:()=>iu,BaseConversationSummaryMemory:()=>gj,BaseMemory:()=>AR,BufferMemory:()=>R9,BufferWindowMemory:()=>L9,ChatMessageHistory:()=>P9,CombinedMemory:()=>lJe,ConversationSummaryBufferMemory:()=>rJe,ConversationSummaryMemory:()=>nJe,ConversationTokenBufferMemory:()=>cJe,ENTITY_MEMORY_CONVERSATION_TEMPLATE:()=>w7e,EntityMemory:()=>aJe,VectorStoreRetrieverMemory:()=>oJe,getBufferString:()=>ui,getInputValue:()=>kR,getOutputValue:()=>E9});var yj=class t{constructor(){this.initMemory(),Ho(()=>{let e=this.memory?.chatHistory;this.initMemory(e)})}static getInstance(){return t.instance||(t.instance=new t),t.instance}initMemory(e){let n=q().contextTurns;this.memory=new L9({k:n*2,memoryKey:"history",inputKey:"input",returnMessages:!0,chatHistory:e}),this.debug&&k("Memory initialized with context turns:",n)}getMemory(){return this.memory}async clearChatMemory(){this.debug&&k("Clearing chat memory"),await this.memory.clear()}async loadMemoryVariables(){let e=await this.memory.loadMemoryVariables({});return this.debug&&k("Loaded memory variables:",e),e}async saveContext(e,n){let r=typeof n=="string"?PR(n):{...n,output:PR(n.output)};this.debug&&k("Saving to memory - Input:",e,"Output (compacted):",r),await this.memory.saveContext(e,r)}};Se();ph();Ir();var wj=class t{constructor(){this.initChatPrompt(),this.initQAPrompt(),Ho(()=>{this.initChatPrompt(),this.initQAPrompt()}),OA(()=>{this.initChatPrompt(),this.initQAPrompt()})}static getInstance(){return t.instance||(t.instance=new t),t.instance}initChatPrompt(){let e=r_(),n=br();n&&RA()&&(e=n.systemPrompt);let r=this.escapeTemplateString(e);this.chatPrompt=ou.fromMessages([fh.fromTemplate(r),new Pv("history"),ff.fromTemplate("{input}")])}initQAPrompt(){let e=`{system_message}

Answer the question with as detailed as possible based only on the following context:
{context}

Question: {question}
`;this.qaPrompt=ou.fromMessages([fh.fromTemplate(e)])}escapeTemplateString(e){return e.replace(/\{/g,"{{").replace(/\}/g,"}}")}getChatPrompt(){return this.chatPrompt}async getQAPrompt({question:e,context:n,systemMessage:r}){return await this.qaPrompt.format({question:e,context:n,system_message:r})}};var vj=class{constructor(e){this.retrievedDocuments=[];this.pendingModelError=null;this.app=e,this.memoryManager=yj.getInstance(),this.chatModelManager=Np.getInstance(),this.promptManager=wj.getInstance(),this.userMemoryManager=new o_(e),this.initialize().catch(n=>z("ChainManager initialize failed",n)),Ho(()=>{this.createChainWithNewModel().catch(n=>z("createChainWithNewModel failed",n))})}getRetrievedDocuments(){return this.retrievedDocuments}async initialize(){await this.createChainWithNewModel()}validateChainType(e){if(e==null)throw new Error("No chain type set")}validateChatModel(){if(this.pendingModelError)throw this.pendingModelError;if(!this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())){let e="Chat model is not initialized properly, check your API key in Copilot setting and make sure you have API access.";throw new rA(e)}}storeRetrieverDocuments(e){this.retrievedDocuments=e}async createChainWithNewModel(e={},n=!0){let r,o=ym(),i=br();if(!(o==="project"&&!i))try{if(r=o==="project"?i?.projectModelKey:Iu(),!r)throw new rA("No model key found. Please select a model in settings.");if(n){let s=$f(r,q().activeModels);if(s||(console.error("Resetting default model. No model configuration found for: ",r),s=Gh[0],r=s.name+"|"+s.provider),o==="project"&&!s.projectEnabled){let l=q().activeModels.find(c=>c.enabled&&c.projectEnabled);if(l)s=l,r=l.name+"|"+l.provider,new uJe.Notice(`Model ${s.name} is not available in project mode. Switching to ${l.name}.`);else throw new Error("No project-enabled models available. Please enable a model for project mode in settings.")}let a={...s,...i?.modelConfigs};await this.chatModelManager.setChatModel(a),this.pendingModelError=null}this.chatModelManager.validateChatModel(this.chatModelManager.getChatModel())?(this.validateChainType(o),e.refreshIndex&&await this.refreshVaultIndex()):console.error("createChainWithNewModel: skipping chain-type housekeeping \u2014 no chat model set."),k(`Setting model to ${r}`)}catch(s){this.pendingModelError=s instanceof Error?s:new Error(String(s)),z(`createChainWithNewModel failed: ${s}`),k(`modelKey: ${r||Iu()}`)}}getChainRunner(){let e=ym(),n=q();switch(e){case"llm_chain":return new hB(this);case"vault_qa":return new pz(this);case"copilot_plus":return n.enableAutonomousAgent?new nj(this):new dy(this);case"project":return new Qz(this);default:throw new Error(`Unsupported chain type: ${String(e)}`)}}async refreshVaultIndex(){if(!q().enableSemanticSearchV3)return;await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1)}async runChain(e,n,r,o,i={}){let{ignoreSystemMessage:s=!1}=i,a=e.contextEnvelope?.layers.find(u=>u.id==="L5_USER")?.text;k(`Step 0: Initial user message:
`,a||e.originalMessage||e.message),this.validateChatModel();let l=this.chatModelManager.getChatModel();if(s||QD(l)){let u=ou.fromMessages([new Pv("history"),ff.fromTemplate("{input}")]);QD(l)&&(u=ou.fromMessages([[uo,r_()||""],u])),this.createChainWithNewModel({prompt:u},!1).catch(d=>z("createChainWithNewModel failed",d))}return await this.getChainRunner().run(e,n,r,o,i)}};Ir();ye();Se();qe();var D9=class t{constructor(e){this.app=e}static getInstance(e){return t.instance||(t.instance=new t(e)),t.instance}clearAllLoadStates(){rke({success:[],failed:[],processingFiles:[],total:[]})}async executeWithProcessTracking(e,n,r){this.setFileOrUrlStartProcess(e);try{let o=await r();return this.setFileOrUrlProcessSuccessful(e),o}catch(o){let i=uv(o)?"Rate limit exceeded. (Rate limit: 50 files or 100MB per 3 hours, whichever is reached first)":Xt(o);throw this.setFileOrUrlProcessFailed(e,n,i),o}}setFileOrUrlStartProcess(e){Kn.set(n$,n=>{let r={...n};return r.failed.find(o=>o.path===e)&&(r.failed=r.failed.filter(o=>o.path!==e)),r.success.includes(e)&&(r.success=r.success.filter(o=>o!==e)),r.processingFiles.includes(e)||(r.processingFiles=[...r.processingFiles,e]),r.total.includes(e)||(r.total=[...r.total,e]),r})}setFileOrUrlProcessSuccessful(e){ig("processingFiles",n=>n.filter(r=>r!==e)),ig("success",n=>n.includes(e)?n:[...n,e])}setFileOrUrlProcessFailed(e,n,r){ig("processingFiles",o=>o.filter(i=>i!==e)),ig("failed",o=>{if(!o.find(s=>s.path===e)){let s={path:e,type:n,error:r,timestamp:Date.now()};return[...o,s]}return o})}preComputeAllItems(e,n){k(`[preComputeAllItems] Starting pre-computation for project: ${e.name}`);let r=[];r.push(...n.map(s=>s.path));let o=e.contextSource?.webUrls?.trim()||"";if(o){let s=o.split(`
`).filter(a=>a.trim());r.push(...s)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let s=i.split(`
`).filter(a=>a.trim());r.push(...s)}if(r.length>0){let s=[...new Set([...r])];ig("total",a=>s),k(`[preComputeAllItems] Project ${e.name}: Added ${r.length} items to tracking (${s.length} total unique items)`)}}markAllCachedItemsAsSuccess(e,n,r){k(`[markAllCachedItemsAsSuccess] Starting for project: ${e.name||"default"}`);let o=e.contextSource?.webUrls?.trim()||"";if(o){let a=o.split(`
`).filter(l=>l.trim()).filter(l=>n.webContexts[l]);a.forEach(l=>{this.markCachedItemAsSuccess(l)}),a.length>0&&k(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${a.length} cached Web URLs as successful`)}let i=e.contextSource?.youtubeUrls?.trim()||"";if(i){let a=i.split(`
`).filter(l=>l.trim()).filter(l=>n.youtubeContexts[l]);a.forEach(l=>{this.markCachedItemAsSuccess(l)}),a.length>0&&k(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${a.length} cached YouTube URLs as successful`)}if(n.fileContexts){let s=new Set(r.filter(l=>l.extension==="md").map(l=>l.path)),a=Object.keys(n.fileContexts).filter(l=>s.has(l));a.forEach(l=>{this.markCachedItemAsSuccess(l)}),a.length>0&&k(`[markAllCachedItemsAsSuccess] Project ${e.name}: Marked ${a.length} cached files that match current project patterns as successful.`)}}markCachedItemAsSuccess(e){ig("total",n=>n.includes(e)?n:[...n,e]),ig("success",n=>n.includes(e)?n:[...n,e])}makeItemFailed(e,n,r){ig("total",o=>o.includes(e)?o:[...o,e]),ig("failed",o=>{if(!o.find(s=>s.path===e)){let s={path:e,type:n,error:r,timestamp:Date.now()};return[...o,s]}return o})}};var Sl=class t{constructor(e,n){this.previousProjectRecords=[];this.app=e,this.plugin=n,this.currentProjectId=null,this.chainMangerInstance=new vj(e),this.projectContextCache=ti.getInstance(),this.fileParserManager=new iy(di.getInstance(),this.app.vault,!0,null),this.loadTracker=D9.getInstance(this.app),JAe(()=>{this.getCurrentChainManager().createChainWithNewModel()}),QAe(()=>{if(RA())return;let r=q(),o=r.enableSemanticSearchV3&&r.indexVaultToVectorStore==="ON MODE SWITCH"&&(ym()==="vault_qa"||ym()==="copilot_plus");this.getCurrentChainManager().createChainWithNewModel({refreshIndex:o})}),OA(r=>{this.switchProject(r)}),this.setupProjectListChangeMonitor()}setupProjectListChangeMonitor(){this.previousProjectRecords=[],this.projectRecordsUnsubscriber?.(),this.projectRecordsUnsubscriber=$5e(e=>{let n=this.previousProjectRecords.map(o=>o.project),r=e.map(o=>o.project);this.previousProjectRecords=e,this.currentProjectId&&!r.some(o=>o.id===this.currentProjectId)&&br()?.id===this.currentProjectId&&(ee(`[ProjectManager] Active project id="${this.currentProjectId}" no longer exists, clearing selection`),this.switchProject(null).catch(o=>z("[ProjectManager] Failed to switch away from removed project",o)));for(let o of r){let i=n.find(s=>s.id===o.id);i&&this.hasMeaningfulProjectConfigChange(i,o)&&(this.compareAndUpdateCache(i,o).catch(s=>z("[ProjectManager] compareAndUpdateCache failed",s)),this.currentProjectId===o.id&&br()?.id===o.id&&(Gx(o),Promise.all([this.loadProjectContext(o,!0),this.getCurrentChainManager().createChainWithNewModel()]).catch(s=>{z(`[Projects] Failed to refresh current project after config change id=${o.id}`,s)})))}})}hasMeaningfulProjectConfigChange(e,n){let r={...e,UsageTimestamps:0},o={...n,UsageTimestamps:0};return JSON.stringify(r)!==JSON.stringify(o)}static getInstance(e,n){return t.instance||(t.instance=new t(e,n)),t.instance}getCurrentChainManager(){return this.chainMangerInstance}getCurrentProjectId(){return this.currentProjectId}touchProjectUsageTimestamps(e){Xu.getInstance(this.app).touchProjectLastUsed(e.id)}getProjectUsageTimestampsManager(){return Xu.getInstance(this.app).getProjectUsageTimestampsManager()}async switchProject(e){if(!(e&&this.currentProjectId===e.id)&&!(!e&&this.currentProjectId===null))try{if(this.loadTracker.clearAllLoadStates(),rg(!0),k("Project loading started..."),!e){await this.saveCurrentProjectMessage(),this.currentProjectId=null,br()!==null&&Gx(null),await this.loadNextProjectMessage(),this.refreshChatView();return}let n=e.id;await this.saveCurrentProjectMessage(),this.currentProjectId=n,await this.loadNextProjectMessage(),await this.getCurrentChainManager().createChainWithNewModel(),this.fileParserManager=new iy(di.getInstance(),this.app.vault,!0,e),await this.loadProjectContext(e),this.refreshChatView(),this.touchProjectUsageTimestamps(e),k(`Switched to project: ${e.name}`)}catch(n){throw z(`Failed to switch project: ${n}`),n}finally{rg(!1)}}async saveCurrentProjectMessage(){await this.plugin.autosaveCurrentChat()}async loadNextProjectMessage(){await this.plugin.chatUIState.handleProjectSwitch()}async loadProjectContext(e,n=!1){n&&(this.loadTracker.clearAllLoadStates(),rg(!0));try{if(!e.contextSource)return ee(`[loadProjectContext] Project ${e.name}: No contextSource. Aborting.`),null;k(`[loadProjectContext] Starting for project: ${e.name}`);let r=await this.projectContextCache.getOrInitializeCache(e),o=this.getProjectAllFiles(e);this.loadTracker.preComputeAllItems(e,o),this.loadTracker.markAllCachedItemsAsSuccess(e,r,o);let[i]=await Promise.all([this.processMarkdownFiles(e,r,o),this.processWebUrls(e,r),this.processYoutubeUrls(e,r)]);return i.timestamp=Date.now(),await this.projectContextCache.setCacheSafely(e,i),await this.processNonMarkdownFiles(e,o,i),k(`[loadProjectContext] Completed for project: ${e.name}.`),i}catch(r){throw z(`[loadProjectContext] Failed for project ${e.name}:`,r),r}finally{n&&rg(!1)}}async compareAndUpdateCache(e,n){try{if(!await this.projectContextCache.get(e))return!0;let o=e.contextSource?.inclusions||"",i=n.contextSource?.inclusions||"",s=e.contextSource?.exclusions||"",a=n.contextSource?.exclusions||"";(o!==i||s!==a)&&(await this.projectContextCache.invalidateMarkdownContext(n),k(`Markdown configuration changed for project ${n.name}, marking for reload`));let l=e.contextSource?.webUrls||"",c=n.contextSource?.webUrls||"";if(l!==c){let f=l.split(`
`).filter(m=>m.trim()),p=c.split(`
`).filter(m=>m.trim());await this.projectContextCache.removeWebUrls(n,f.filter(m=>!p.includes(m)))}let u=e.contextSource?.youtubeUrls||"",d=n.contextSource?.youtubeUrls||"";if(u!==d){let f=u.split(`
`).filter(m=>m.trim()),p=d.split(`
`).filter(m=>m.trim());await this.projectContextCache.removeYoutubeUrls(n,f.filter(m=>!p.includes(m)))}}catch(r){z(`Error comparing project configurations: ${r}`)}}refreshChatView(){let e=this.app.workspace.getLeavesOfType(No)[0]?.view;e&&e.updateView()}async getProjectContext(e){let n=QN().find(o=>o.id===e);if(!n)return ee(`[getProjectContext] Project not found for ID: ${e}`),null;k(`[getProjectContext] Getting context for project: ${n.name} (ID: ${e})`);let r=this.projectContextCache.getSync(n);if(!r||r.markdownNeedsReload){r?k(`[getProjectContext] Project ${n.name}: Markdown needs reload. Triggering full load.`):k(`[getProjectContext] Project ${n.name}: Memory cache miss. Triggering full load.`);let o=await this.loadProjectContext(n,!0);if(!o)return z(`[getProjectContext] Project ${n.name}: loadProjectContext returned null.`),null;r=o}else k(`[getProjectContext] Project ${n.name}: Memory cache hit and markdown OK. Using existing context.`);return this.formatProjectContextWithFiles(r,n)}async formatProjectContextWithFiles(e,n){let r=[];if(e.markdownContext&&r.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&r.push(`## Web Content
${Object.values(e.webContexts).join(`

`)}`),Object.keys(e.youtubeContexts).length>0&&r.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`

`)}`),Object.keys(e.fileContexts).length>0){let o=Object.entries(e.fileContexts).filter(([i])=>i.split(".").pop()?.toLowerCase()!=="md");if(o.length>0){let i=o.map(async([a,l])=>{let c=a.split("/"),u=c[c.length-1],d=u.split(".").pop()||"",f=await this.projectContextCache.getOrReuseFileContext(n,a)||"[Content not available]";return`[[${u}]]
path: ${a}
type: ${d}
modified: ${new Date(l.timestamp).toISOString()}

${f}`}),s=await Promise.all(i);s.length>0&&r.push(`## Other Files
${s.join(`

`)}`)}}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:

<ProjectContext>
${r.join(`

`)}
</ProjectContext>
`}formatProjectContext(e){let n=[];if(e.markdownContext&&n.push(`## Markdown Files
${e.markdownContext}`),Object.keys(e.webContexts).length>0&&n.push(`## Web Content
${Object.values(e.webContexts).join(`

`)}`),Object.keys(e.youtubeContexts).length>0&&n.push(`## YouTube Content
${Object.values(e.youtubeContexts).join(`

`)}`),Object.keys(e.fileContexts).length>0){let r="";for(let[o,i]of Object.entries(e.fileContexts)){let s=o.split("/"),a=s[s.length-1],l=a.split(".").pop()||"";r+=`[[${a}]]
path: ${o}
type: ${l}
modified: ${new Date(i.timestamp).toISOString()}

`}r&&n.push(`## Other Files
${r}`)}return`
# Project Context
The following information is the relevant context for this project. Use this information to inform your responses when appropriate:

<ProjectContext>
${n.join(`

`)}
</ProjectContext>
`}async processMarkdownFiles(e,n,r){if(k(`[processMarkdownFiles] Starting for project: ${e.name}`),n.markdownNeedsReload||!n.markdownContext||!n.markdownContext.trim()){k(`[processMarkdownFiles] Project ${e.name}: Processing markdown content.`);let o=await this.processMarkdownFileContext(r);this.projectContextCache.updateProjectMarkdownFilesFromPatterns(e,n,r),n.markdownContext=o,n.markdownNeedsReload=!1,k(`[processMarkdownFiles] Project ${e.name}: Markdown content updated.`)}else k(`[processMarkdownFiles] Project ${e.name}: Markdown content already up-to-date.`);return k(`[processMarkdownFiles] Completed for project: ${e.name}. Total fileContexts: ${Object.keys(n.fileContexts||{}).length}`),n}async processMarkdownFileContext(e){let n=e.filter(o=>o.extension==="md");k(`Found ${n.length} markdown files to process for project context`);let r=await Promise.all(n.map(async o=>{let i="",s="";try{let[a,l]=await this.loadTracker.executeWithProcessTracking(o.path,"md",async()=>Promise.all([this.app.vault.adapter.stat(o.path),this.app.vault.read(o)]));s=`[[${o.basename}]]
path: ${o.path}
type: ${o.extension}
created: ${a?new Date(a.ctime).toISOString():"unknown"}
modified: ${a?new Date(a.mtime).toISOString():"unknown"}`,i=l,k(`Completed processing markdown file: ${o.path}`)}catch(a){z(`Error processing file ${o.path}: ${a}`),i=`[Error: ${Xt(a)}]`}return`${s}

${i}`}));return k("All markdown files processed for project context"),r.join(`

`)}async processWebUrls(e,n){k(`[processWebUrls] Starting for project: ${e.name}`);let r=e.contextSource?.webUrls?.trim()||"";if(!r)return Object.keys(n.webContexts).length>0&&(k(`[processWebUrls] Project ${e.name}: Clearing all Web contexts as none are configured.`),n.webContexts={}),n;let o=r.split(`
`).filter(u=>u.trim());k(`[processWebUrls] Project ${e.name}: Found ${o.length} URLs in config.`);let i=Object.keys(n.webContexts),s=o.filter(u=>!n.webContexts[u]);s.length>0&&k(`[processWebUrls] Project ${e.name}: Fetching content for ${s.length} new/updated Web URLs.`);let a=i.filter(u=>!o.includes(u));if(a.length>0){k(`[processWebUrls] Project ${e.name}: Removing ${a.length} obsolete Web URL contexts.`);for(let u of a)delete n.webContexts[u]}let l=s.map(async u=>{let d=await this.processWebUrlContext(u);return d&&k(`[processWebUrls] Project ${e.name}: Successfully fetched content for URL: ${u.substring(0,50)}...`),{url:u,context:d}});return(await Promise.all(l)).forEach(u=>{u&&u.context?n.webContexts[u.url]=u.context:u&&!u.context&&ee(`[processWebUrls] Project ${e.name}: Fetched empty content for Web URL: ${u.url}`)}),k(`[processWebUrls] Completed for project: ${e.name}. Total Web contexts: ${Object.keys(n.webContexts).length}`),n}async processYoutubeUrls(e,n){k(`[processYoutubeUrls] Starting for project: ${e.name}`);let r=e.contextSource?.youtubeUrls?.trim()||"";if(!r)return Object.keys(n.youtubeContexts).length>0&&(k(`[processYoutubeUrls] Project ${e.name}: Clearing all YouTube contexts as none are configured.`),n.youtubeContexts={}),n;let o=r.split(`
`).filter(u=>u.trim());k(`[processYoutubeUrls] Project ${e.name}: Found ${o.length} YouTube URLs in config.`);let i=Object.keys(n.youtubeContexts),s=o.filter(u=>!n.youtubeContexts[u]);s.length>0&&k(`[processYoutubeUrls] Project ${e.name}: Fetching transcripts for ${s.length} new/updated YouTube URLs.`);let a=i.filter(u=>!o.includes(u));if(a.length>0){k(`[processYoutubeUrls] Project ${e.name}: Removing ${a.length} obsolete YouTube URL contexts.`);for(let u of a)delete n.youtubeContexts[u]}let l=s.map(async u=>{let d=await this.processYoutubeUrlContext(u);return d&&k(`[processYoutubeUrls] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${u.substring(0,50)}...`),{url:u,context:d}});return(await Promise.all(l)).forEach(u=>{u&&u.context?n.youtubeContexts[u.url]=u.context:u&&!u.context&&ee(`[processYoutubeUrls] Project ${e.name}: Fetched empty transcript for YouTube URL: ${u.url}`)}),k(`[processYoutubeUrls] Completed for project: ${e.name}. Total YouTube contexts: ${Object.keys(n.youtubeContexts).length}`),n}async processWebUrlContext(e){if(!e?.trim())return"";try{let n=tO.getInstance(),{urlContext:r}=await this.loadTracker.executeWithProcessTracking(e,"web",async()=>{let o=await n.processUrls(e);if(o.processedErrorUrls[e])throw new Error(o.processedErrorUrls[e]);return o});return r||""}catch(n){return z(`Failed to process web URL: ${n}`),""}}async processYoutubeUrlContext(e){if(!e?.trim())return"";try{let n=await this.loadTracker.executeWithProcessTracking(e,"youtube",async()=>di.getInstance().youtube4llm(e));return n.response.transcript?`

YouTube transcript from ${e}:
${n.response.transcript}`:""}catch(n){return z(`Failed to process YouTube URL ${e}: ${n}`),new mP.Notice(`Failed to process YouTube URL ${e}: ${Xt(n)}`),""}}async processNonMarkdownFiles(e,n,r){let o=n.filter(c=>c.extension!=="md");if(k(`[loadProjectContext] Project ${e.name}: Checking for non-markdown processing: ${o.length} files .`),o.length<=0)return;this.fileParserManager=new iy(di.getInstance(),this.app.vault,!0,e);let i=[],s=[];for(let c of o)r.fileContexts[c.path]?.cacheKey?i.push(c):s.push(c);let a=[...i,...s],l=0;for(let c of a){let u=c.path;if(this.fileParserManager.supportsExtension(c.extension))try{await this.loadTracker.executeWithProcessTracking(u,"nonMd",async()=>{let d=await this.projectContextCache.getOrReuseFileContext(e,u);d?(await DC(c,d,this.app.vault),l++):(k(`[loadProjectContext] Project ${e.name}: Parsing/caching new/updated file: ${u}`),await this.fileParserManager.parseFile(c,this.app.vault),l++)})}catch(d){if(z(`[loadProjectContext] Project ${e.name}: Error parsing file ${u}:`,d),uv(d))throw d}}l>0&&k(`[loadProjectContext] Project ${e.name}: Processed and cached ${l} non-markdown files.`)}async retryFailedItem(e){try{if(!this.currentProjectId){ee("[retryFailedItem] No current project, aborting retry");return}let n=QN().find(r=>r.id===this.currentProjectId);if(!n){z(`[retryFailedItem] Current project not found: ${this.currentProjectId}`);return}switch(k(`[retryFailedItem] Starting retry for ${e.type} item: ${e.path}`),e.type){case"web":await this.retryWebUrl(n,e.path);break;case"youtube":await this.retryYoutubeUrl(n,e.path);break;case"md":await this.retryMarkdownFile(n,e.path);break;case"nonMd":await this.retryNonMarkdownFile(n,e.path);break;default:ee("[retryFailedItem] Unknown item type:",e.type);return}k(`[retryFailedItem] Successfully retried ${e.type} item: ${e.path}`),new mP.Notice(`Retry successful: ${e.path}`)}catch(n){z(`[retryFailedItem] Failed to retry ${e.type} item ${e.path}:`,n),new mP.Notice(`Retry failed: ${Xt(n)}`)}}async retryWebUrl(e,n){let r=await this.processWebUrlContext(n);if(!r){ee(`[retryWebUrl] Project ${e.name}: Fetched empty content for Web URL: ${n}`);return}k(`[retryWebUrl] Project ${e.name}: Successfully fetched content for URL: ${n.substring(0,50)}...`),await this.projectContextCache.updateWebUrl(e,n,r)}async retryYoutubeUrl(e,n){let r=await this.processYoutubeUrlContext(n);if(!r){ee(`[retryYoutubeUrl] Project ${e.name}: Fetched empty transcript for YouTube URL: ${n}`);return}k(`[retryYoutubeUrl] Project ${e.name}: Successfully fetched transcript for YouTube URL: ${n.substring(0,50)}...`),await this.projectContextCache.updateYoutubeUrl(e,n,r)}async retryMarkdownFile(e,n){let r=this.app.vault.getAbstractFileByPath(n);if(!(r instanceof mP.TFile)||r.extension!=="md")throw new Error(`File not found or not a markdown file: ${n}`);try{await this.loadTracker.executeWithProcessTracking(r.path,"md",async()=>{}),k(`[retryMarkdownFile] Successfully reprocessed markdown file: ${n}`),await this.projectContextCache.invalidateMarkdownContext(e)}catch(o){throw z(`[retryMarkdownFile] Error processing file ${n}: ${o}`),o}}async retryNonMarkdownFile(e,n){let r=this.app.vault.getAbstractFileByPath(n);if(!(r instanceof mP.TFile)||r.extension==="md")throw new Error(`File not found or is a markdown file: ${n}`);if(!this.fileParserManager.supportsExtension(r.extension))throw new Error(`Unsupported file extension: ${r.extension}`);try{await this.loadTracker.executeWithProcessTracking(n,"nonMd",async()=>this.fileParserManager.parseFile(r,this.app.vault)),k(`[retryNonMarkdownFile] Successfully reprocessed non-markdown file: ${n}`)}catch(o){throw z(`[retryNonMarkdownFile] Error processing file ${n}: ${o}`),o}}getProjectAllFiles(e){let{inclusions:n,exclusions:r}=Bo({inclusions:e.contextSource.inclusions,exclusions:e.contextSource.exclusions,isProject:!0});return this.app.vault.getFiles().filter(o=>Qr(o,n,r,!0))}onunload(){this.projectRecordsUnsubscriber?.(),this.projectRecordsUnsubscriber=void 0,this.projectContextCache.cleanup()}};Ir();HS();ye();var WJe=require("obsidian");rn();var $9=N(U());Kt();var Xn=$9.forwardRef(({className:t,type:e,...n},r)=>$9.createElement("input",{type:e,className:oe("!tw-h-9 !tw-min-w-[50px] !tw-rounded-md !tw-border tw-border-solid tw-border-border !tw-bg-transparent !tw-px-3 !tw-py-1 !tw-text-sm !tw-transition-colors md:!tw-text-base","focus-visible:!tw-shadow-sm focus-visible:!tw-outline-none focus-visible:!tw-ring-1 focus-visible:!tw-ring-ring","placeholder:tw-text-sm","tw-flex tw-w-full tw-shadow-sm placeholder:tw-text-muted disabled:tw-cursor-not-allowed disabled:tw-opacity-50",t),ref:r,...n}));Xn.displayName="Input";var U9=N(U());var yJe=N(U(),1);var mJe=N(U(),1),xHt=N(yo(),1);var Zs=N(U(),1);var mHt=N(U(),1);function dJe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function fJe(...t){return e=>{let n=!1,r=t.map(o=>{let i=dJe(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():dJe(t[o],null)}}}}var F9=N(Ve(),1);function pJe(t){let e=hHt(t),n=Zs.forwardRef((r,o)=>{let{children:i,...s}=r,a=Zs.Children.toArray(i),l=a.find(yHt);if(l){let c=l.props.children,u=a.map(d=>d===l?Zs.Children.count(c)>1?Zs.Children.only(null):Zs.isValidElement(c)?c.props.children:null:d);return(0,F9.jsx)(e,{...s,ref:o,children:Zs.isValidElement(c)?Zs.cloneElement(c,void 0,u):null})}return(0,F9.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function hHt(t){let e=Zs.forwardRef((n,r)=>{let{children:o,...i}=n;if(Zs.isValidElement(o)){let s=vHt(o),a=wHt(i,o.props);return o.type!==Zs.Fragment&&(a.ref=r?fJe(r,s):s),Zs.cloneElement(o,a)}return Zs.Children.count(o)>1?Zs.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var gHt=Symbol("radix.slottable");function yHt(t){return Zs.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===gHt}function wHt(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function vHt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var hJe=N(Ve(),1),bHt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gJe=bHt.reduce((t,e)=>{let n=pJe(`Primitive.${e}`),r=mJe.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,hJe.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var wJe=N(Ve(),1),CHt="Label",vJe=yJe.forwardRef((t,e)=>(0,wJe.jsx)(gJe.label,{...t,ref:e,onMouseDown:n=>{n.target.closest("button, input, select, textarea")||(t.onMouseDown?.(n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));vJe.displayName=CHt;var tbe=vJe;JW();Kt();var SHt=$A("tw-text-sm tw-font-medium tw-leading-none peer-disabled:tw-cursor-not-allowed peer-disabled:tw-opacity-70"),hi=U9.forwardRef(({className:t,...e},n)=>U9.createElement(tbe,{ref:n,className:oe(SHt(),t),...e}));hi.displayName=tbe.displayName;var NR=N(U());var su=N(U(),1);var bJe=N(U(),1);function xJe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function nbe(...t){return e=>{let n=!1,r=t.map(o=>{let i=xJe(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():xJe(t[o],null)}}}}function xj(...t){return bJe.useCallback(nbe(...t),t)}var Ev=N(U(),1),CJe=N(Ve(),1);function _Je(t,e=[]){let n=[];function r(i,s){let a=Ev.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Ev.useMemo(()=>m,Object.values(m));return(0,CJe.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Ev.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Ev.createContext(s));return function(a){let l=a?.[t]||i;return Ev.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,THt(o,...e)]}function THt(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Ev.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var O_r=!!(typeof window<"u"&&window.document&&window.document.createElement);function rbe(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var $p=N(U(),1);var SJe=N(U(),1),hP=globalThis?.document?SJe.useLayoutEffect:()=>{};var B9=N(U(),1);var IHt=$p[" useInsertionEffect ".trim().toString()]||hP;function TJe({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=PHt({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=$p.useRef(t!==void 0);$p.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=$p.useCallback(u=>{if(a){let d=EHt(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function PHt({defaultProp:t,onChange:e}){let[n,r]=$p.useState(t),o=$p.useRef(n),i=$p.useRef(e);return IHt(()=>{i.current=e},[e]),$p.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function EHt(t){return typeof t=="function"}var $_r=Symbol("RADIX:SYNC_STATE");var z9=N(U(),1);function IJe(t){let e=z9.useRef({value:t,previous:t});return z9.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var PJe=N(U(),1);function EJe(t){let[e,n]=PJe.useState(void 0);return hP(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});let r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;let i=o[0],s,a;if("borderBoxSize"in i){let l=i.borderBoxSize,c=Array.isArray(l)?l[0]:l;s=c.inlineSize,a=c.blockSize}else s=t.offsetWidth,a=t.offsetHeight;n({width:s,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var ed=N(U(),1);var AJe=N(U(),1);function AHt(t,e){return AJe.useReducer((n,r)=>e[n][r]??n,t)}var obe=t=>{let{present:e,children:n}=t,r=kHt(e),o=typeof n=="function"?n({present:r.isPresent}):ed.Children.only(n),i=xj(r.ref,MHt(o));return typeof n=="function"||r.isPresent?ed.cloneElement(o,{ref:i}):null};obe.displayName="Presence";function kHt(t){let[e,n]=ed.useState(),r=ed.useRef(null),o=ed.useRef(t),i=ed.useRef("none"),s=t?"mounted":"unmounted",[a,l]=AHt(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return ed.useEffect(()=>{let c=j9(r.current);i.current=a==="mounted"?c:"none"},[a]),hP(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=j9(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),hP(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=j9(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=j9(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:ed.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function j9(t){return t?.animationName||"none"}function MHt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var MJe=N(U(),1),$Ht=N(yo(),1);var Js=N(U(),1);var V9=N(Ve(),1);function kJe(t){let e=NHt(t),n=Js.forwardRef((r,o)=>{let{children:i,...s}=r,a=Js.Children.toArray(i),l=a.find(RHt);if(l){let c=l.props.children,u=a.map(d=>d===l?Js.Children.count(c)>1?Js.Children.only(null):Js.isValidElement(c)?c.props.children:null:d);return(0,V9.jsx)(e,{...s,ref:o,children:Js.isValidElement(c)?Js.cloneElement(c,void 0,u):null})}return(0,V9.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function NHt(t){let e=Js.forwardRef((n,r)=>{let{children:o,...i}=n;if(Js.isValidElement(o)){let s=DHt(o),a=LHt(i,o.props);return o.type!==Js.Fragment&&(a.ref=r?nbe(r,s):s),Js.cloneElement(o,a)}return Js.Children.count(o)>1?Js.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var OHt=Symbol("radix.slottable");function RHt(t){return Js.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===OHt}function LHt(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function DHt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var NJe=N(Ve(),1),FHt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],W9=FHt.reduce((t,e)=>{let n=kJe(`Primitive.${e}`),r=MJe.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,NJe.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var mf=N(Ve(),1),H9="Checkbox",[UHt,rSr]=_Je(H9),[BHt,ibe]=UHt(H9);function zHt(t){let{__scopeCheckbox:e,checked:n,children:r,defaultChecked:o,disabled:i,form:s,name:a,onCheckedChange:l,required:c,value:u="on",internal_do_not_use_render:d}=t,[f,p]=TJe({prop:n,defaultProp:o??!1,onChange:l,caller:H9}),[m,h]=su.useState(null),[g,y]=su.useState(null),w=su.useRef(!1),v=m?!!s||!!m.closest("form"):!0,x={checked:f,disabled:i,setChecked:p,control:m,setControl:h,name:a,form:s,value:u,hasConsumerStoppedPropagationRef:w,required:c,defaultChecked:m_(o)?!1:o,isFormControl:v,bubbleInput:g,setBubbleInput:y};return(0,mf.jsx)(BHt,{scope:e,...x,children:jHt(d)?d(x):r})}var OJe="CheckboxTrigger",RJe=su.forwardRef(({__scopeCheckbox:t,onKeyDown:e,onClick:n,...r},o)=>{let{control:i,value:s,disabled:a,checked:l,required:c,setControl:u,setChecked:d,hasConsumerStoppedPropagationRef:f,isFormControl:p,bubbleInput:m}=ibe(OJe,t),h=xj(o,u),g=su.useRef(l);return su.useEffect(()=>{let y=i?.form;if(y){let w=()=>d(g.current);return y.addEventListener("reset",w),()=>y.removeEventListener("reset",w)}},[i,d]),(0,mf.jsx)(W9.button,{type:"button",role:"checkbox","aria-checked":m_(l)?"mixed":l,"aria-required":c,"data-state":FJe(l),"data-disabled":a?"":void 0,disabled:a,value:s,...r,ref:h,onKeyDown:rbe(e,y=>{y.key==="Enter"&&y.preventDefault()}),onClick:rbe(n,y=>{d(w=>m_(w)?!0:!w),m&&p&&(f.current=y.isPropagationStopped(),f.current||y.stopPropagation())})})});RJe.displayName=OJe;var K9=su.forwardRef((t,e)=>{let{__scopeCheckbox:n,name:r,checked:o,defaultChecked:i,required:s,disabled:a,value:l,onCheckedChange:c,form:u,...d}=t;return(0,mf.jsx)(zHt,{__scopeCheckbox:n,checked:o,defaultChecked:i,disabled:a,required:s,onCheckedChange:c,name:r,form:u,value:l,internal_do_not_use_render:({isFormControl:f})=>(0,mf.jsxs)(mf.Fragment,{children:[(0,mf.jsx)(RJe,{...d,ref:e,__scopeCheckbox:n}),f&&(0,mf.jsx)($Je,{__scopeCheckbox:n})]})})});K9.displayName=H9;var LJe="CheckboxIndicator",sbe=su.forwardRef((t,e)=>{let{__scopeCheckbox:n,forceMount:r,...o}=t,i=ibe(LJe,n);return(0,mf.jsx)(obe,{present:r||m_(i.checked)||i.checked===!0,children:(0,mf.jsx)(W9.span,{"data-state":FJe(i.checked),"data-disabled":i.disabled?"":void 0,...o,ref:e,style:{pointerEvents:"none",...t.style}})})});sbe.displayName=LJe;var DJe="CheckboxBubbleInput",$Je=su.forwardRef(({__scopeCheckbox:t,...e},n)=>{let{control:r,hasConsumerStoppedPropagationRef:o,checked:i,defaultChecked:s,required:a,disabled:l,name:c,value:u,form:d,bubbleInput:f,setBubbleInput:p}=ibe(DJe,t),m=xj(n,p),h=IJe(i),g=EJe(r);su.useEffect(()=>{let w=f;if(!w)return;let v=window.HTMLInputElement.prototype,b=Object.getOwnPropertyDescriptor(v,"checked").set,_=!o.current;if(h!==i&&b){let T=new Event("click",{bubbles:_});w.indeterminate=m_(i),b.call(w,m_(i)?!1:i),w.dispatchEvent(T)}},[f,h,i,o]);let y=su.useRef(m_(i)?!1:i);return(0,mf.jsx)(W9.input,{type:"checkbox","aria-hidden":!0,defaultChecked:s??y.current,required:a,disabled:l,name:c,value:u,form:d,...e,tabIndex:-1,ref:m,style:{...e.style,...g,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});$Je.displayName=DJe;function jHt(t){return typeof t=="function"}function m_(t){return t==="indeterminate"}function FJe(t){return m_(t)?"indeterminate":t?"checked":"unchecked"}vt();Kt();var To=NR.forwardRef(({className:t,...e},n)=>NR.createElement(K9,{ref:n,className:oe("tw-border-solid !tw-bg-transparent tw-p-0 !tw-shadow tw-transition-colors","hover:!tw-bg-interactive-accent hover:!tw-text-on-accent data-[state=checked]:!tw-bg-interactive-accent data-[state=checked]:!tw-text-on-accent","tw-peer tw-size-4 tw-shrink-0 tw-rounded-sm tw-border tw-border-interactive-accent focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-cursor-not-allowed disabled:tw-opacity-50",t),...e},NR.createElement(sbe,{className:oe("tw-flex tw-items-center tw-justify-center tw-text-current")},NR.createElement(Ro,{className:"tw-size-4"}))));To.displayName=K9.displayName;var Fp=N(U());Kt();var hf=Fp.forwardRef(({className:t,value:e,...n},r)=>{let o=Fp.useRef(null),i=Fp.useCallback(()=>{let a=o.current;if(a){a.setCssProps({"--copilot-autosize-height":"auto"});let l=Math.min(a.scrollHeight,300);a.setCssProps({"--copilot-autosize-height":`${l}px`})}},[]);Fp.useLayoutEffect(()=>{i()},[e,i]),Fp.useEffect(()=>(i(),window.addEventListener("resize",i),()=>window.removeEventListener("resize",i)),[i]);let s=a=>{o.current=a,typeof r=="function"?r(a):r&&(r.current=a)};return Fp.createElement("textarea",{className:oe("tw-min-w-fit tw-resize-y tw-overflow-auto tw-border-solid","tw-flex tw-max-h-[300px] tw-min-h-[60px] tw-w-full tw-rounded-md tw-border tw-bg-transparent tw-px-3 tw-py-2 tw-text-base tw-shadow-sm placeholder:tw-text-muted focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-cursor-not-allowed disabled:tw-opacity-50 md:tw-text-sm","tw-h-[var(--copilot-autosize-height,_auto)]",t),value:e,ref:s,onChange:a=>{i(),n.onChange?.(a)},onInput:i,onCompositionEnd:i,onPaste:()=>{window.setTimeout(i,0)},...n})});hf.displayName="Textarea";var qr=N(U());ws();Se();var py=N(U());qe();vt();It();var WHt=[],abe=({capabilities:t=WHt,iconSize:e=16})=>py.default.createElement(py.default.Fragment,null,t.sort((n,r)=>n.localeCompare(r)).map(n=>{switch(n){case"reasoning":return py.default.createElement(Cm,{key:n,className:"tw-text-model-capabilities-blue",style:{width:e,height:e}});case"vision":return py.default.createElement(ow,{key:n,className:"tw-text-model-capabilities-green",style:{width:e,height:e}});case"websearch":return py.default.createElement(Br,{key:n,className:"tw-text-model-capabilities-blue",style:{width:e,height:e}});default:return null}})),lbe=({model:t,iconSize:e=14})=>{let n=t.displayName||t.name;return py.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-1"},py.default.createElement("span",{className:"tw-truncate tw-text-sm hover:tw-text-normal"},n),t.capabilities&&t.capabilities.length>0&&py.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-0.5"},py.default.createElement(abe,{capabilities:t.capabilities,iconSize:e})))},UJe=t=>{let e=t.displayName||t.name,n=`(${cl(t.provider)})`;return`${e} ${n}`},OR=t=>{let e=t.displayName||t.name,n=`(${cl(t.provider,t)})`,r=t.capabilities?.map(o=>{switch(o){case"reasoning":return"Reasoning";case"vision":return"Vision";case"websearch":return"Websearch";default:return""}}).join("|")||"";return`${e} ${n} ${r}`};Kt();vt();ye();var my=N(U());function BJe(){return my.default.createElement("ul",{className:"tw-m-0 tw-px-4 tw-text-sm"},my.default.createElement("li",null,my.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{}")," represents the selected text."),my.default.createElement("li",null,my.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{[[Note Title]]}")," represents a note."),my.default.createElement("li",null,my.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{activeNote}")," represents the active note."),my.default.createElement("li",null,my.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{#tag1, #tag2}")," represents ALL notes with ANY of the specified tags in their property (an OR operation)."))}var cbe="{copilot-selection}",hy={title:"",content:"",showInContextMenu:!0,showInSlashMenu:!0,order:0,modelKey:"",lastUsedMs:0},Av="copilot-command-context-menu-enabled",kv="copilot-command-slash-enabled",gy="copilot-command-context-menu-order",Mv="copilot-command-model-key",Nv="copilot-command-last-used",zJe=[{title:"Fix grammar and spelling",content:"Fix the grammar and spelling of {}. Preserve all formatting, line breaks, and special characters. Do not add or remove any content. Return only the corrected text.",showInContextMenu:!0,showInSlashMenu:!0,order:1e3,modelKey:"",lastUsedMs:0},{title:"Translate to Chinese",content:`Translate {} into Chinese:
    1. Preserve the meaning and tone
    2. Maintain appropriate cultural context
    3. Keep formatting and structure
    Return only the translated text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1010,modelKey:"",lastUsedMs:0},{title:"Summarize",content:"Create a bullet-point summary of {}. Each bullet point should capture a key point. Return only the bullet-point summary.",showInContextMenu:!0,showInSlashMenu:!0,order:1020,modelKey:"",lastUsedMs:0},{title:"Simplify",content:"Simplify {} to a 6th-grade reading level (ages 11-12). Use simple sentences, common words, and clear explanations. Maintain the original key concepts. Return only the simplified text.",showInContextMenu:!0,showInSlashMenu:!0,order:1030,modelKey:"",lastUsedMs:0},{title:"Explain like I am 5",content:`Explain {} in simple terms that a 5-year-old would understand:
    1. Use basic vocabulary
    2. Include simple analogies
    3. Break down complex concepts
    Return only the simplified explanation.`,showInContextMenu:!0,showInSlashMenu:!0,order:1040,modelKey:"",lastUsedMs:0},{title:"Emojify",content:`Add relevant emojis to enhance {}. Follow these rules:
    1. Insert emojis at natural breaks in the text
    2. Never place two emojis next to each other
    3. Keep all original text unchanged
    4. Choose emojis that match the context and tone
    Return only the emojified text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1050,modelKey:"",lastUsedMs:0},{title:"Make shorter",content:`Reduce {} to half its length while preserving these elements:
    1. Main ideas and key points
    2. Essential details
    3. Original tone and style
    Return only the shortened text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1060,modelKey:"",lastUsedMs:0},{title:"Make longer",content:`Expand {} to twice its length by:
    1. Adding relevant details and examples
    2. Elaborating on key points
    3. Maintaining the original tone and style
    Return only the expanded text.`,showInContextMenu:!0,showInSlashMenu:!0,order:1070,modelKey:"",lastUsedMs:0},{title:"Generate table of contents",content:"Generate a hierarchical table of contents for {}. Use appropriate heading levels (H1, H2, H3, etc.). Include page numbers if present. Return only the table of contents.",showInContextMenu:!1,showInSlashMenu:!1,order:1080,modelKey:"",lastUsedMs:0},{title:"Generate glossary",content:'Create a glossary of important terms, concepts, and phrases from {}. Format each entry as "Term: Definition". Sort entries alphabetically. Return only the glossary.',showInContextMenu:!1,showInSlashMenu:!1,order:1090,modelKey:"",lastUsedMs:0},{title:"Remove URLs",content:"Remove all URLs from {}. Preserve all other content and formatting. URLs may be in various formats (http, https, www). Return only the text with URLs removed.",showInContextMenu:!1,showInSlashMenu:!1,order:1100,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet",content:`Rewrite {} as a single tweet with these requirements:
    1. Maximum 280 characters
    2. Use concise, impactful language
    3. Maintain the core message
    Return only the tweet text.`,showInContextMenu:!1,showInSlashMenu:!1,order:1110,modelKey:"",lastUsedMs:0},{title:"Rewrite as tweet thread",content:`Convert {} into a Twitter thread following these rules:
    1. Each tweet must be under 240 characters
    2. Start with "THREAD START" on its own line
    3. Separate tweets with "

---

"
    4. End with "THREAD END" on its own line
    5. Make content engaging and clear
    Return only the formatted thread.`,showInContextMenu:!1,showInSlashMenu:!1,order:1120,modelKey:"",lastUsedMs:0},{title:"Clip YouTube Transcript",content:`
Based on the YouTube video information and transcript provided in the context, generate a complete Obsidian note in the following format.

IMPORTANT: If no YouTube video context is found, remind the user to:
1. Open a YouTube video in Web Viewer (or use @ to select a YouTube web tab)
2. Then use this command again

Generate the note with this exact structure:

---
title: "<video title>"
description: "<first 200 chars of description>"
channel: "<channel name>"
url: "<video url>"
duration: "<duration>"
published: <upload date in YYYY-MM-DD format>
thumbnailUrl: "<YouTube thumbnail URL: i.ytimg.com/vi/VIDEO_ID/maxresdefault.jpg with https protocol>"
genre:
  - "<genre>"
watched:
---
![<video title>](<video url>)

> [!summary]- Description
> <full video description, preserve line breaks>

## Summary

<Brief 2-3 paragraph summary of the video content>

## Key Takeaways

<List 5-8 key takeaways as bullet points>

## Mindmap

CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
- Root node format: root(Topic Name) - use round brackets, NO double brackets
- Child nodes: just plain text, no brackets needed
- Do NOT use quotes, parentheses, brackets, or any special characters in text
- Do NOT use icons or emojis
- Keep all node text short and simple - max 3-4 words per node
- Use only letters, numbers, and spaces

Example of CORRECT syntax:
\`\`\`mermaid
mindmap
  root(Video Main Topic)
    First Theme
      Detail one
      Detail two
    Second Theme
      Detail three
    Third Theme
\`\`\`

## Notable Quotes

<List 5-10 notable quotes from the transcript. Format each as:>
- [<timestamp>: <quote text>](<video_url>&t=<seconds>s)

Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1130,modelKey:"",lastUsedMs:0},{title:"Clip Web Page",content:`
Based on the web page content provided in the context (from Obsidian Web Clipper or Web Viewer), generate a complete Obsidian note.

IMPORTANT: If no web page context is found, remind the user to:
1. Open a web page in Web Viewer (or use @ to select a web tab)
2. Or open a note clipped by Obsidian Web Clipper
3. Then use this command again

Generate the note with this exact structure:

---
title: "<page title>"
source: "<page url>"
description: "<brief description>"
tags:
  - "clippings"
---

## Summary

<Brief 2-3 paragraph summary of the page content>

## Key Takeaways

<List 5-8 key takeaways as bullet points>

## Mindmap

CRITICAL Mermaid mindmap syntax rules - MUST follow exactly:
- Root node format: root(Topic Name) - use round brackets, NO double brackets
- Child nodes: just plain text, no brackets needed
- Do NOT use quotes, parentheses, brackets, or any special characters in text
- Keep all node text short and simple - max 3-4 words per node

\`\`\`mermaid
mindmap
  root(Main Topic)
    Theme One
      Detail
    Theme Two
      Detail
\`\`\`

## Notable Quotes

<List 3-5 notable quotes from the content, if any>

Return only the markdown content without any explanations or comments.`,showInContextMenu:!1,showInSlashMenu:!0,order:1140,modelKey:"",lastUsedMs:0}];ye();var RR=require("obsidian");Se();Id();Id();var gP=Jh(),yP=Oo([]),ube=new Set;function wP(t){ube.add(t)}function vP(t){ube.delete(t)}function bj(t){return ube.has(t)}function Cj(t){let e=gP.get(yP);gP.set(yP,e.filter(n=>n.title!==t))}function xP(t,e){let n=gP.get(yP),r;(e?n.findIndex(i=>i.title===e):-1)!==-1?r=n.map(i=>i.title===e?t:i):r=[...n,t],gP.set(yP,r)}function q9(t){gP.set(yP,t)}function G9(){return Wl(yP,{store:gP})}function td(){return gP.get(yP)}rD();qe();Ky();It();function Y9(t,e,n){let r=t.trim();return r?t!==r?"Command name cannot have leading or trailing spaces":n&&t===n?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(r)?'Command name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===r.toLowerCase())?"A command with this name already exists":null:"Command name cannot be empty"}function LR(t){return encodeURIComponent(t.toLowerCase())}function h_(){return(0,RR.normalizePath)(q().customPromptsFolder)}function DR(t){return`${h_()}/${t}.md`}function $R(t){if(!(t instanceof RR.TFile)||t.extension!=="md")return!1;let e=h_();return!(!t.path.startsWith(e+"/")||t.path.slice(e.length+1).includes("/"))}function jJe(t){return app.metadataCache.getFileCache(t)?.frontmatter?.[gy]!=null}async function _j(t){let e=await app.vault.read(t),n=Qh(e),r=app.metadataCache.getFileCache(t),o=r?.frontmatter?.[Av]??hy.showInContextMenu,i=r?.frontmatter?.[kv]??hy.showInSlashMenu,s=r?.frontmatter?.[Nv]??hy.lastUsedMs,a=r?.frontmatter?.[gy]??hy.order,l=r?.frontmatter?.[Mv]??hy.modelKey;return{title:t.basename,modelKey:l,content:n,showInContextMenu:o,showInSlashMenu:i,order:a,lastUsedMs:s}}async function Z9(){let t=app.vault.getFiles().filter(n=>$R(n)),e=await Promise.all(t.map(_j));return q9(e),e}function Sj(t){return Xh(t,"manual",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0,getManualOrder:e=>e.order})}function HHt(t){return Xh(t,"recent",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:e=>e.lastUsedMs})}function KHt(t){return Xh(t,"name",{getName:e=>e.title,getCreatedAtMs:()=>0,getLastUsedAtMs:()=>0})}function J9(t){switch(q().promptSortStrategy){case"timestamp":return HHt(t);case"alphabetical":return KHt(t);case"manual":return Sj(t);default:return t}}async function Tj(t,e,n=!1){let o=(await Ij(t,e,app.vault,app.workspace.getActiveFile())).processedPrompt;if(o.includes(`{${bu}}`)||n)return o;let i=o.indexOf(cbe);return i===-1?e.trim()?o+`

<`+bu+">"+e+"</"+bu+">":o:o.slice(0,i)+e+o.slice(i+cbe.length)}var qHt=/\{(?!copilot-selection\}|\[\[)([^}]+)\}/g;async function GHt(t,e,n){let r=new Map,o=new Set,i;for(;(i=qHt.exec(t))!==null;){let s=i[1].trim(),a={content:"",files:[]},l=s.toLowerCase();if(l==="activenote")if(n){let c=await IA(n,e);c&&(a.content=`<${NS}>
<path>${n.path}</path>
## ${UW(n)}

${c}
</${NS}>`,a.files.push(n))}else new RR.Notice("No active note found.");else{if(l==="activewebtab")continue;if(s.startsWith("#")){let c=s.slice(1).split(",").map(f=>f.trim()),u=$W(e,c),d=[];for(let f of u){let p=await IA(f,e);p&&(d.push(`<${NS}>
<path>${f.path}</path>
## ${UW(f)}

${p}
</${NS}>`),a.files.push(f))}a.content=d.join(`

`)}else{let c=OAe(s),u=JD(e,c),d=[];for(let f of u){let p=await IA(f,e);p&&(d.push(`<${NS}>
<path>${f.path}</path>
## ${UW(f)}

${p}
</${NS}>`),a.files.push(f))}a.content=d.join(`

`)}}a.content?(r.set(s,a.content),a.files.forEach(c=>o.add(c))):l!=="activenote"&&l!=="activewebtab"&&(s.startsWith('"')||ee(`No notes found for variable: ${s}`))}return{variablesMap:r,includedFiles:o}}async function Ij(t,e,n,r,o=!1){let i=q(),s=new Set;if(!i.enableCustomPromptTemplating)return!o&&t.includes("{}")&&!e&&r&&s.add(r),{processedPrompt:t+`

`,includedFiles:Array.from(s)};let{variablesMap:a,includedFiles:l}=await GHt(t,n,r);l.forEach(p=>s.add(p));let c=t,u="",d=null;!o&&c.includes("{}")&&(c=c.replace(/\{\}/g,`{${bu}}`),e?u+=`<${bu}>
${e}
</${bu}>`:r?(d=await IA(r,n),u+=`<${bu} type="active_note">
${d||""}
</${bu}>`,s.add(r)):u+=`<${bu}>
(No selected text or active note available)
</${bu}>`);for(let[p,m]of a.entries())p.toLowerCase()==="activenote"&&d!==null||(u?u+=`

<${iD} name="${p}">
${m}
</${iD}>`:u+=`<${iD} name="${p}">
${m}
</${iD}>`);let f=NAe(c,n);for(let p of f)if(!s.has(p)){let m=await IA(p,n);if(m){let h=await n.adapter.stat(p.path),g=h?new Date(h.ctime).toISOString():"Unknown",y=h?new Date(h.mtime).toISOString():"Unknown",w=`<${oD}>
<title>${p.basename}</title>
<path>${p.path}</path>
<ctime>${g}</ctime>
<mtime>${y}</mtime>
<content>
${m}
</content>
</${oD}>`;u&&(u+=`

`),u+=`${w}`,s.add(p)}}return{processedPrompt:u?`${c}

${u}`:`${c}

`,includedFiles:Array.from(s)}}function VJe(t,e){let r=`${t} (copy)`,o=1;for(;e.some(i=>i.title.toLowerCase()===r.toLowerCase());)o++,r=`${t} (copy ${o})`;return r}function X9(){let e=td().reduce((n,r)=>n>r.order?n:r.order,0);return e===Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+10}async function dbe(t,e){try{wP(t.path),await app.fileManager.processFrontMatter(t,n=>{n[Av]==null&&(n[Av]=e.showInContextMenu),n[kv]==null&&(n[kv]=e.showInSlashMenu),n[gy]==null&&(n[gy]=e.order),n[Mv]==null&&(n[Mv]=e.modelKey),n[Nv]==null&&(n[Nv]=e.lastUsedMs)})}finally{vP(t.path)}}function YHt({commands:t,command:e,onConfirm:n,onCancel:r}){let i=Ht().activeModels.filter(f=>f.enabled).map(f=>({label:UJe(f),value:ln(f)})),[s,a]=(0,qr.useState)(e),[l,c]=(0,qr.useState)({}),u=(f,p)=>{a(m=>({...m,[f]:p})),c(m=>({...m,[f]:void 0}))},d=()=>{let f={},p=Y9(s.title,t,e.title);if(p&&(f.title=p),s.content.trim()||(f.content="Prompt is required"),Object.keys(f).length>0){c(f);return}n(s)};return qr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},qr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},qr.default.createElement(hi,{htmlFor:"title"},"Name"),qr.default.createElement(Xn,{id:"title",value:s.title,onChange:f=>u("title",f.target.value),placeholder:"Enter command name"}),l.title&&qr.default.createElement("div",{className:"tw-text-sm tw-text-error"},l.title)),qr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},qr.default.createElement(hi,{htmlFor:"content"},"Prompt"),qr.default.createElement(BJe,null),qr.default.createElement(hf,{id:"content",value:s.content,onChange:f=>u("content",f.target.value),placeholder:"Enter command prompt",className:"tw-min-h-[200px]"}),l.content&&qr.default.createElement("div",{className:"tw-text-sm tw-text-error"},l.content)),qr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},qr.default.createElement(hi,{htmlFor:"modelKey"},"Model (Optional)"),qr.default.createElement("div",{className:"tw-group tw-relative tw-w-full"},qr.default.createElement("select",{value:s.modelKey,onChange:f=>{let p=f.target.value;if(!p){u("modelKey","");return}if(!i.find(h=>h.value===p)){z(`Model ${p} not found`),u("modelKey","");return}u("modelKey",f.target.value)},className:oe("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-text-sm !tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal")},qr.default.createElement("option",{value:""},"Inherit from chat model"),i.map(f=>qr.default.createElement("option",{key:f.value,value:f.value.toString()},f.label))),qr.default.createElement("div",{className:oe("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal")},qr.default.createElement(hr,{className:"tw-size-4"})))),qr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},qr.default.createElement(To,{id:"showInContextMenu",checked:s.showInContextMenu,onCheckedChange:f=>u("showInContextMenu",f)}),qr.default.createElement(hi,{htmlFor:"showInContextMenu"},"Show in context menu")),qr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},qr.default.createElement(To,{id:"showInSlashMenu",checked:s.showInSlashMenu,onCheckedChange:f=>u("showInSlashMenu",f)}),qr.default.createElement(hi,{htmlFor:"showInSlashMenu"},"Show in slash menu")),qr.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},qr.default.createElement(X,{variant:"secondary",onClick:r},"Cancel"),qr.default.createElement(X,{variant:"default",onClick:d},"Save")))}var g_=class extends WJe.Modal{constructor(n,r,o,i){super(n);this.commands=r;this.command=o;this.onUpdate=i;this.setTitle("Edit Command")}onOpen(){let{contentEl:n}=this;this.root=sr(n,this.app);let r=o=>{this.onUpdate(o),this.close()};this.root.render(qr.default.createElement(YHt,{commands:this.commands,command:this.command,onConfirm:r,onCancel:()=>this.close()}))}onClose(){this.root.unmount()}};var Pj=require("obsidian");Nf();qe();av();var Xs=class t{static getInstance(){return t.instance||(t.instance=new t),t.instance}async createCommand(e,n={}){let r={skipStoreUpdate:!1,autoOrder:!0,...n},o=DR(e.title);try{wP(o);let i=e.order;r.autoOrder&&(i=X9()),e={...e,order:i};let s=h_();await Fr(s);let a=app.vault.getAbstractFileByPath(o),l;a instanceof Pj.TFile?(await app.vault.modify(a,e.content),l=a):l=await app.vault.create(o,e.content),await app.fileManager.processFrontMatter(l,c=>{c[Av]=e.showInContextMenu,c[kv]=e.showInSlashMenu,c[gy]=e.order,c[Mv]=e.modelKey,c[Nv]=e.lastUsedMs}),r.skipStoreUpdate||xP(e,e.title)}finally{vP(o)}}async recordUsage(e){await this.updateCommand({...e,lastUsedMs:Date.now()},e.title)}async updateCommand(e,n,r=!1){let o=DR(e.title),i=DR(n),s=e.title!==n;try{wP(o),s&&wP(i),r||xP(e,n);let a=app.vault.getAbstractFileByPath(o);if(s){if(app.vault.getAbstractFileByPath(o))throw new Gn("Error saving custom prompt. Please check if the title already exists.");let c=app.vault.getAbstractFileByPath(i);c instanceof Pj.TFile&&(await app.vault.rename(c,o),a=app.vault.getAbstractFileByPath(o))}a||(await this.createCommand(e,{skipStoreUpdate:r,autoOrder:!0}),a=app.vault.getAbstractFileByPath(DR(e.title))),a instanceof Pj.TFile&&(await app.vault.modify(a,e.content),await app.fileManager.processFrontMatter(a,l=>{l[Av]=e.showInContextMenu,l[kv]=e.showInSlashMenu,l[gy]=e.order,l[Mv]=e.modelKey,l[Nv]=e.lastUsedMs}))}finally{vP(o),s&&vP(i)}}async updateCommands(e){q9(e),await Promise.all(e.map(n=>this.updateCommand(n,n.title,!0)))}async reorderCommands(e){let n=[...e];for(let r=0;r<n.length;r++)n[r]={...n[r],order:r*10};await this.updateCommands(n)}async deleteCommand(e){let n=DR(e.title);try{wP(n),Cj(e.title);let r=app.vault.getAbstractFileByPath(n);r instanceof Pj.TFile&&await Qc(app,r)}finally{vP(n)}}};var Q9=`
You are an AI assistant designed to execute user instructions with precision. Your responses should be:

- Direct and focused: Address only what is explicitly requested
- Concise: Avoid unnecessary elaboration unless the user asks for details
- Context-aware: When text is selected or highlighted, treat it as the primary target for any requested action
- Action-oriented: Prioritize completing the task over explaining the process

Key principles:

- Follow instructions literally and completely
- Assume selected/highlighted text is the focus unless told otherwise
- Use all provided context: Consider any additional information, examples, or constraints the user provides to better complete the task
- Add explanations only when explicitly requested or when clarification is essential
- Maintain the user's preferred format and style

Response format: Match the format implied by the user's request (e.g., if they ask for a list, provide a list; if they ask for a rewrite, provide only the rewritten text).
`;function eY(t,e){if(!e)return t;let n=t.includes("{}"),r=/\{activenote\}/i.test(t),o=[];return n||o.push("{}"),r||o.push("{activeNote}"),o.length>0?t+`

${o.join(`

`)}`:t}Ir();var Ml=N(U());vt();var urt=require("obsidian");var eo=N(U());Kt();var Ki=N(U());function tY(t,e,n){return Math.min(Math.max(t,e),n)}function nY(t={}){let{initialPosition:e={x:0,y:0},bounds:n="window",dragRef:r,getPosition:o,onPositionChange:i,writeToDom:s=!0}=t,[a,l]=(0,Ki.useState)(e),[c,u]=(0,Ki.useState)(!1),d=(0,Ki.useRef)(null),f=r??d,p=(0,Ki.useRef)(e),m=(0,Ki.useRef)({x:0,y:0}),h=(0,Ki.useRef)(null),g=(0,Ki.useRef)(null),y=(0,Ki.useRef)(null),w=(0,Ki.useRef)(!0),v=(0,Ki.useCallback)(S=>{if(!s)return;let P=f.current;P&&P.setCssProps({"--copilot-drag-x":`${S.x}px`,"--copilot-drag-y":`${S.y}px`})},[f,s]),x=(0,Ki.useCallback)(S=>{let P=S.x,A=S.y,O=f.current;if(n==="window"&&O){let $=O.win,B=O.getBoundingClientRect(),W=$.innerWidth-B.width,F=$.innerHeight-B.height;P=tY(P,0,Math.max(0,W)),A=tY(A,0,Math.max(0,F))}else if(n==="parent"&&O?.parentElement){let $=O.getBoundingClientRect(),B=O.parentElement.getBoundingClientRect(),W=B.left,F=B.top,Z=B.right-$.width,V=B.bottom-$.height;P=tY(P,W,Math.max(W,Z)),A=tY(A,F,Math.max(F,V))}let D={x:P,y:A};return p.current=D,v(D),i?.(D),D},[n,f,v,i]),b=(0,Ki.useCallback)(()=>{if(g.current!=null)return;let S=f.current?.win??window;g.current=S.requestAnimationFrame(()=>{g.current=null;let P=h.current;P&&(h.current=null,x(P))})},[x,f]);(0,Ki.useLayoutEffect)(()=>{v(p.current)},[v]);let _=(0,Ki.useCallback)(S=>{let P=p.current,A=typeof S=="function"?S(P):S;p.current=A,l(A),v(A),i?.(A)},[v,i]),T=(0,Ki.useCallback)(S=>{if(S.button!==0||(S.preventDefault(),y.current))return;u(!0);let P=o?o():p.current;p.current=P,v(P),m.current={x:S.clientX-P.x,y:S.clientY-P.y};let A=f.current?.doc??activeDocument,O=A.defaultView??window,D=A.body;D.classList.add("tw-select-none","tw-cursor-grabbing");let $=F=>{h.current={x:F.clientX-m.current.x,y:F.clientY-m.current.y},b()},B=F=>{if(y.current!==B)return;A.removeEventListener("mousemove",$,!0),A.removeEventListener("mouseup",W,!0),g.current!=null&&(O.cancelAnimationFrame(g.current),g.current=null);let Z=h.current;h.current=null;let V=Z?x(Z):p.current;D.classList.remove("tw-select-none","tw-cursor-grabbing"),y.current=null,F&&w.current&&(l(V),u(!1))},W=()=>{B(!0)};y.current=B,A.addEventListener("mousemove",$,!0),A.addEventListener("mouseup",W,!0)},[x,f,o,b,v]);return(0,Ki.useEffect)(()=>()=>{w.current=!1,y.current?.(!1)},[]),(0,Ki.useLayoutEffect)(()=>{v(p.current)}),{position:a,setPosition:_,isDragging:c,dragRef:f,handleMouseDown:T}}var hc=N(U());function HJe(t){let{enabled:e=!0,getRect:n,getConstraints:r,onResize:o}=t,[i,s]=(0,hc.useState)(!1),a=(0,hc.useRef)(null),l=(0,hc.useRef)(null),c=(0,hc.useRef)(null),u=(0,hc.useRef)(null),d=(0,hc.useRef)(null),f=(0,hc.useRef)(o);(0,hc.useEffect)(()=>{f.current=o},[o]);let p=(0,hc.useRef)(r);(0,hc.useEffect)(()=>{p.current=r},[r]);let m=(0,hc.useCallback)(h=>g=>{if(!e)return;let y=n();if(!y)return;let v=g.currentTarget?.doc??activeDocument;l.current=v,c.current=v.defaultView??window,a.current={direction:h,startClientX:g.clientX,startClientY:g.clientY,width:y.width,height:y.height,left:y.left,top:y.top,right:y.right},s(!0),g.preventDefault(),g.stopPropagation()},[e,n]);return(0,hc.useEffect)(()=>{if(!i)return;let h=a.current;if(!h)return;let g=h.direction,y=g==="right"?"ew-resize":g==="bottom"?"ns-resize":g==="bottom-left"?"nesw-resize":"nwse-resize",w=l.current??activeDocument,v=c.current??window,x=w.body;x.setCssProps({"--copilot-resize-cursor":y}),x.classList.add("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]");let b=()=>{u.current!==null&&(v.cancelAnimationFrame(u.current),u.current=null)},_=()=>{let O=d.current;O&&(d.current=null,f.current(O))},T=()=>{u.current===null&&(u.current=v.requestAnimationFrame(()=>{u.current=null,_()}))},S=O=>{let D=a.current;if(!D)return;let $=O.clientX-D.startClientX,B=O.clientY-D.startClientY,W=p.current?.()??{minWidth:0,minHeight:0},F=W.minWidth,Z=W.minHeight,V=W.maxWidth??Number.POSITIVE_INFINITY,H=W.maxHeight??Number.POSITIVE_INFINITY,te=D.width,fe=D.height,me,j;(g==="right"||g==="bottom-right")&&(te=Math.min(V,Math.max(F,D.width+$))),g==="bottom-left"&&(te=Math.min(V,Math.max(F,D.width-$)),me=D.right-te,j=D.top),(g==="bottom"||g==="bottom-right"||g==="bottom-left")&&(fe=Math.min(H,Math.max(Z,D.height+B))),d.current=me===void 0?{width:te,height:fe}:{width:te,height:fe,x:me,y:j},T()},P=()=>{b(),_(),w.removeEventListener("mousemove",S,!0),w.removeEventListener("mouseup",A,!0),x.classList.remove("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]"),x.setCssProps({"--copilot-resize-cursor":""}),a.current=null,s(!1)},A=()=>{P()};return w.addEventListener("mousemove",S,!0),w.addEventListener("mouseup",A,!0),()=>{b(),d.current=null,a.current=null,w.removeEventListener("mousemove",S,!0),w.removeEventListener("mouseup",A,!0),x.classList.remove("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]"),x.setCssProps({"--copilot-resize-cursor":""})}},[i]),{isResizing:i,handleResizeStart:m}}var fbe=N(U());Kt();function KJe({onMouseDown:t,className:e}){return fbe.createElement("div",{className:oe("tw-flex tw-h-4 tw-items-center tw-justify-center","tw-cursor-grab active:tw-cursor-grabbing","hover:tw-bg-[color-mix(in_srgb,var(--background-modifier-hover)_20%,transparent)]",e),onMouseDown:t},fbe.createElement("div",{className:"tw-h-[5px] tw-w-16 tw-rounded-sm tw-bg-[color-mix(in_srgb,var(--text-muted)_40%,transparent)] hover:tw-bg-[color-mix(in_srgb,var(--text-muted)_65%,transparent)]"}))}var pbe=N(U());vt();Kt();rn();function qJe({onClose:t,className:e}){return pbe.createElement(X,{className:oe("tw-absolute tw-right-2 tw-top-1 tw-rounded tw-p-1 tw-text-normal",e),variant:"ghost2",onClick:t,title:"Close","aria-label":"Close"},pbe.createElement(Sn,{className:"tw-size-4"}))}var YJe="data-copilot-draggable-modal",GJe=`[${YJe}="true"]`;function ZJe({open:t,onClose:e,children:n,className:r,initialPosition:o,width:i="min(500px, 90vw)",resizable:s=!1,minHeight:a=260,closeOnEscapeFromOutside:l=!1,anchorBottom:c}){let{position:u,setPosition:d,dragRef:f,handleMouseDown:p,isDragging:m}=nY({initialPosition:o||{x:typeof window<"u"?(window.innerWidth-500)/2:100,y:typeof window<"u"?(window.innerHeight-400)/2:100},bounds:null}),h=(0,eo.useRef)(!1),g=(0,eo.useRef)(null),y=(0,eo.useCallback)(B=>{let W=B.currentTarget.doc,F=B.clientX,Z=B.clientY;g.current?.();let V=()=>{W.removeEventListener("mousemove",H,!0),W.removeEventListener("mouseup",te,!0),g.current===V&&(g.current=null)},H=fe=>{Math.abs(fe.clientX-F)<2&&Math.abs(fe.clientY-Z)<2||(h.current=!0,V())},te=()=>V();W.addEventListener("mousemove",H,!0),W.addEventListener("mouseup",te,!0),g.current=V,p(B)},[p]),[w,v]=(0,eo.useState)(null),[x,b]=(0,eo.useState)(null),[_,T]=(0,eo.useState)(t);t&&!_?(T(!0),v(null),b(null)):!t&&_&&T(!1),(0,eo.useEffect)(()=>{t&&(g.current?.(),g.current=null,h.current=!1,o&&d(o))},[t]),(0,eo.useEffect)(()=>()=>{g.current?.(),g.current=null},[]),(0,eo.useLayoutEffect)(()=>{if(!t||!s||w!==null&&x!==null)return;let B=f.current;if(!B)return;let W=B.getBoundingClientRect(),F=typeof window<"u"?Math.floor(window.innerHeight*.85):W.height;w===null&&v(Math.min(F,Math.max(a,W.height))),x===null&&b(W.width)},[t,s,w,x,a,f]);let S=w===null?null:Math.max(w,a);(0,eo.useLayoutEffect)(()=>{if(c===void 0||h.current||S===null)return;let B=Math.max(12,c-S);Math.abs(u.y-B)<1||d({x:u.x,y:B})},[c,S,u.x,u.y,d]),(0,eo.useLayoutEffect)(()=>{if(c!==void 0||h.current||S===null)return;let W=(f.current?.win??window).innerHeight-12-S,F=Math.max(12,Math.min(u.y,W));Math.abs(u.y-F)<1||d({x:u.x,y:F})},[c,S,u.x,u.y,d,f]);let P=(0,eo.useCallback)(()=>f.current?.getBoundingClientRect()??null,[f]),A=(0,eo.useCallback)(()=>{let B=typeof window<"u"?Math.floor(window.innerHeight*.85):Number.POSITIVE_INFINITY;return{minWidth:300,minHeight:a,maxHeight:B}},[a]),O=(0,eo.useCallback)(B=>{h.current=!0,v(W=>W===B.height?W:B.height),b(W=>W===B.width?W:B.width),typeof B.x=="number"&&d(W=>W.x===B.x?W:{...W,x:B.x})},[d]),{isResizing:D,handleResizeStart:$}=HJe({enabled:s,getRect:P,getConstraints:A,onResize:O});return(0,eo.useEffect)(()=>{if(!t)return;let B=f.current?.doc??activeDocument,W=F=>{if(F.key!=="Escape"||F.defaultPrevented)return;let Z=f.current;if(!Z)return;let V=B.activeElement,H=V instanceof Element?V.closest(GJe):null;if(H){if(H!==Z)return;F.preventDefault(),F.stopPropagation(),e();return}if(!l)return;let te=Array.from(B.querySelectorAll(GJe));te[te.length-1]===Z&&(F.preventDefault(),F.stopPropagation(),e())};return B.addEventListener("keydown",W),()=>{B.removeEventListener("keydown",W)}},[t,e,f,l]),t?eo.default.createElement("div",{ref:f,[YJe]:"true",className:oe("tw-fixed tw-z-popover","tw-left-[var(--copilot-drag-x,0px)] tw-top-[var(--copilot-drag-y,0px)]","tw-flex tw-flex-col","tw-border tw-border-solid tw-border-border tw-bg-primary",s?"tw-rounded-t-lg tw-shadow-2xl":"tw-rounded-lg tw-shadow-2xl","tw-max-h-[85vh]",s&&"tw-group",m&&"tw-cursor-grabbing tw-select-none",D&&"tw-select-none",r),style:{width:s&&x!==null?x:i,...s&&S!==null?{height:S}:{}}},eo.default.createElement("div",{className:"tw-relative tw-flex-none"},eo.default.createElement(KJe,{onMouseDown:y}),eo.default.createElement(qJe,{onClose:e})),eo.default.createElement("div",{className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-overflow-hidden"},n),s&&eo.default.createElement(eo.default.Fragment,null,eo.default.createElement("div",{className:"tw-absolute tw-bottom-0 tw-left-0 tw-h-1 tw-w-full tw-cursor-ns-resize",onMouseDown:$("bottom")}),eo.default.createElement("div",{className:"quick-ask-resize-indicator-left tw-absolute tw-bottom-0 tw-left-0 tw-size-3 tw-cursor-nesw-resize",onMouseDown:$("bottom-left")}),eo.default.createElement("div",{className:"quick-ask-resize-indicator-right tw-absolute tw-bottom-0 tw-right-0 tw-z-[10] tw-size-3 tw-cursor-nwse-resize",onMouseDown:$("bottom-right")}))):null}var rY=N(U());vt();Kt();function JJe({icon:t,label:e,className:n}){let r=t===null?null:t!==void 0?t:rY.createElement(rb,{className:"tw-size-4 tw-text-muted"});return rY.createElement("div",{className:oe("tw-flex tw-flex-none tw-items-center tw-justify-center tw-gap-2","tw-px-4 tw-py-2",n)},r,rY.createElement("span",{className:"tw-truncate tw-text-sm tw-font-medium tw-text-normal"},e))}var Ps=N(U());Kt();vt();rn();var bP=N(U());function XJe({content:t,renderMarkdown:e,className:n}){let r=bP.useRef(null),o=bP.useRef(0);return bP.useEffect(()=>{let i=r.current;if(!i)return;let s=++o.current,a=i.doc.createElement("div");i.replaceChildren(),e(t,a).then(()=>{s===o.current&&(i.replaceChildren(...Array.from(a.childNodes)),a.classList.contains("markdown-rendered")&&i.classList.add("markdown-rendered"))}).catch(()=>{s===o.current&&(i.textContent=t)})},[t,e]),bP.createElement("div",{ref:r,className:n})}function QJe({state:t,editable:e=!1,value:n,onChange:r,placeholder:o="Ready to generate...",className:i,minHeight:s="180px",disableAutoGrow:a=!1,renderMarkdown:l}){let c=Ps.useRef(null),[u,d]=Ps.useState(!1),f=t.type==="result"&&!t.isStreaming,p=!!l&&f&&!u,m=t.type==="loading"||t.type==="result"&&t.isStreaming,[h,g]=Ps.useState(m);m&&!h?(g(!0),d(!1)):!m&&h&&g(!1),Ps.useEffect(()=>{t.type==="result"&&t.isStreaming&&c.current&&(c.current.scrollTop=c.current.scrollHeight)},[t]);let y="",w=!0;if(t.type==="idle"?(y="",w=!0):t.type==="loading"?(y="loading...",w=!0):t.type==="result"&&(y=e&&n!==void 0?n:t.text,w=t.isStreaming||!e),p&&l){let x=e&&n!==void 0?n:t.text;return Ps.createElement("div",{className:oe("tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-px-4 tw-py-2",i)},Ps.createElement("div",{className:"tw-relative tw-min-h-0 tw-flex-1 tw-overflow-auto tw-rounded-md tw-border tw-border-solid tw-px-3 tw-py-2"},Ps.createElement(XJe,{content:x,renderMarkdown:l,className:"tw-pr-6 tw-text-sm"}),e&&Ps.createElement(X,{variant:"ghost2",size:"icon",className:"tw-absolute tw-right-1 tw-top-1 tw-size-6 tw-opacity-60 hover:tw-opacity-100",onClick:()=>d(!0),title:"Edit content"},Ps.createElement(nb,{className:"tw-size-3"}))))}let v=!!l&&f&&u;return a?Ps.createElement("div",{className:oe("tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-px-4 tw-py-2",i)},Ps.createElement("div",{className:"tw-relative tw-min-h-0 tw-flex-1"},Ps.createElement("textarea",{ref:c,value:y,onChange:x=>r?.(x.target.value),placeholder:o,disabled:w,className:oe("tw-min-w-fit tw-overflow-auto tw-border-solid","tw-absolute tw-inset-0 tw-w-full tw-resize-none tw-rounded-md tw-border tw-bg-transparent tw-py-2 tw-pl-3 tw-pr-8 tw-text-base tw-shadow-sm placeholder:tw-text-muted focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-cursor-not-allowed disabled:tw-opacity-50 md:tw-text-sm",w&&"tw-cursor-default tw-opacity-70")}),v&&Ps.createElement(X,{variant:"ghost2",size:"icon",className:"tw-absolute tw-right-2 tw-top-2 tw-z-[1] tw-size-6 tw-opacity-60 hover:tw-opacity-100",onClick:()=>d(!1),title:"Preview rendered content"},Ps.createElement(c$,{className:"tw-size-3"})))):Ps.createElement("div",{className:oe("tw-flex-1 tw-px-4 tw-py-2",i)},Ps.createElement(hf,{ref:c,value:y,onChange:x=>r?.(x.target.value),placeholder:o,disabled:w,className:oe("tw-min-h-[120px] tw-resize-y",w&&"tw-cursor-default tw-opacity-70"),style:{minHeight:s}}))}var FR=N(U());Kt();rn();vt();function eXe({value:t,onChange:e,onSubmit:n,onClear:r,placeholder:o="Enter follow-up instructions...",className:i,showClear:s=!0,disabled:a=!1,hint:l,autoFocus:c=!1}){let u=d=>{if(!(d.nativeEvent.isComposing||d.key==="Process")&&d.key==="Enter"&&!d.shiftKey&&!d.metaKey&&!d.ctrlKey&&!d.altKey){if(!n)return;d.preventDefault(),n()}};return FR.createElement("div",{className:oe("tw-relative tw-flex-none tw-px-4 tw-py-2",i)},FR.createElement(hf,{value:t,onChange:d=>e(d.target.value),onKeyDown:u,placeholder:o,disabled:a,autoFocus:c,className:"tw-min-h-[36px] tw-resize-none tw-py-2 tw-pr-8"}),l&&FR.createElement("span",{className:"tw-pointer-events-none tw-absolute tw-bottom-4 tw-right-6 tw-text-xs tw-text-muted"},l),s&&t&&r&&!l&&FR.createElement(X,{type:"button",variant:"ghost2",size:"fit",onClick:r,disabled:a,className:"tw-absolute tw-right-6 tw-top-4 tw-text-muted","aria-label":"Clear input"},FR.createElement(Sn,{className:"tw-size-4"})))}var cu=N(U());rn();var Io=N(U());var la=N(U(),1);var PTr=!!(typeof window<"u"&&window.document&&window.document.createElement);function Ej(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var ZHt=N(U(),1);function tXe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function oY(...t){return e=>{let n=!1,r=t.map(o=>{let i=tXe(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():tXe(t[o],null)}}}}var Ov=N(U(),1),nXe=N(Ve(),1);function rXe(t,e=[]){let n=[];function r(i,s){let a=Ov.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Ov.useMemo(()=>m,Object.values(m));return(0,nXe.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Ov.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Ov.createContext(s));return function(a){let l=a?.[t]||i;return Ov.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,JHt(o,...e)]}function JHt(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Ov.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var Up=N(U(),1);var oXe=N(U(),1),iY=globalThis?.document?oXe.useLayoutEffect:()=>{};var sY=N(U(),1);var XHt=Up[" useInsertionEffect ".trim().toString()]||iY;function iXe({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=QHt({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=Up.useRef(t!==void 0);Up.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=Up.useCallback(u=>{if(a){let d=e6t(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function QHt({defaultProp:t,onChange:e}){let[n,r]=Up.useState(t),o=Up.useRef(n),i=Up.useRef(e);return XHt(()=>{i.current=e},[e]),Up.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function e6t(t){return typeof t=="function"}var OTr=Symbol("RADIX:SYNC_STATE");var aXe=N(U(),1),s6t=N(yo(),1);var Qs=N(U(),1);var aY=N(Ve(),1);function sXe(t){let e=t6t(t),n=Qs.forwardRef((r,o)=>{let{children:i,...s}=r,a=Qs.Children.toArray(i),l=a.find(r6t);if(l){let c=l.props.children,u=a.map(d=>d===l?Qs.Children.count(c)>1?Qs.Children.only(null):Qs.isValidElement(c)?c.props.children:null:d);return(0,aY.jsx)(e,{...s,ref:o,children:Qs.isValidElement(c)?Qs.cloneElement(c,void 0,u):null})}return(0,aY.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function t6t(t){let e=Qs.forwardRef((n,r)=>{let{children:o,...i}=n;if(Qs.isValidElement(o)){let s=i6t(o),a=o6t(i,o.props);return o.type!==Qs.Fragment&&(a.ref=r?oY(r,s):s),Qs.cloneElement(o,a)}return Qs.Children.count(o)>1?Qs.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var n6t=Symbol("radix.slottable");function r6t(t){return Qs.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===n6t}function o6t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function i6t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var lXe=N(Ve(),1),a6t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],cXe=a6t.reduce((t,e)=>{let n=sXe(`Primitive.${e}`),r=aXe.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,lXe.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var Gt=N(U(),1);var UTr=!!(typeof window<"u"&&window.document&&window.document.createElement);function qi(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var y_=N(U(),1);var Rv=N(U(),1),uXe=N(Ve(),1);function dXe(t,e=[]){let n=[];function r(i,s){let a=Rv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Rv.useMemo(()=>m,Object.values(m));return(0,uXe.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Rv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Rv.createContext(s));return function(a){let l=a?.[t]||i;return Rv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,l6t(o,...e)]}function l6t(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Rv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var pXe=N(U(),1);function fXe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function mbe(...t){return e=>{let n=!1,r=t.map(o=>{let i=fXe(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():fXe(t[o],null)}}}}function hbe(...t){return pXe.useCallback(mbe(...t),t)}var ea=N(U(),1);var lY=N(Ve(),1);function gbe(t){let e=c6t(t),n=ea.forwardRef((r,o)=>{let{children:i,...s}=r,a=ea.Children.toArray(i),l=a.find(d6t);if(l){let c=l.props.children,u=a.map(d=>d===l?ea.Children.count(c)>1?ea.Children.only(null):ea.isValidElement(c)?c.props.children:null:d);return(0,lY.jsx)(e,{...s,ref:o,children:ea.isValidElement(c)?ea.cloneElement(c,void 0,u):null})}return(0,lY.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function c6t(t){let e=ea.forwardRef((n,r)=>{let{children:o,...i}=n;if(ea.isValidElement(o)){let s=p6t(o),a=f6t(i,o.props);return o.type!==ea.Fragment&&(a.ref=r?mbe(r,s):s),ea.cloneElement(o,a)}return ea.Children.count(o)>1?ea.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var u6t=Symbol("radix.slottable");function d6t(t){return ea.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===u6t}function f6t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function p6t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var cY=N(Ve(),1),m6t=N(U(),1);var h6t=N(Ve(),1);function w_(t){let e=t+"CollectionProvider",[n,r]=dXe(e),[o,i]=n(e,{collectionRef:{current:null},itemMap:new Map}),s=h=>{let{scope:g,children:y}=h,w=y_.default.useRef(null),v=y_.default.useRef(new Map).current;return(0,cY.jsx)(o,{scope:g,itemMap:v,collectionRef:w,children:y})};s.displayName=e;let a=t+"CollectionSlot",l=gbe(a),c=y_.default.forwardRef((h,g)=>{let{scope:y,children:w}=h,v=i(a,y),x=hbe(g,v.collectionRef);return(0,cY.jsx)(l,{ref:x,children:w})});c.displayName=a;let u=t+"CollectionItemSlot",d="data-radix-collection-item",f=gbe(u),p=y_.default.forwardRef((h,g)=>{let{scope:y,children:w,...v}=h,x=y_.default.useRef(null),b=hbe(g,x),_=i(u,y);return y_.default.useEffect(()=>(_.itemMap.set(x,{ref:x,...v}),()=>void _.itemMap.delete(x))),(0,cY.jsx)(f,{[d]:"",ref:b,children:w})});p.displayName=u;function m(h){let g=i(t+"CollectionConsumer",h);return y_.default.useCallback(()=>{let w=g.collectionRef.current;if(!w)return[];let v=Array.from(w.querySelectorAll(`[${d}]`));return Array.from(g.itemMap.values()).sort((_,T)=>v.indexOf(_.ref.current)-v.indexOf(T.ref.current))},[g.collectionRef,g.itemMap])}return[{Provider:s,Slot:c,ItemSlot:p},m,r]}var hXe=N(U(),1);function mXe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Aj(...t){return e=>{let n=!1,r=t.map(o=>{let i=mXe(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():mXe(t[o],null)}}}}function v_(...t){return hXe.useCallback(Aj(...t),t)}var Lv=N(U(),1),gXe=N(Ve(),1);function yXe(t,e=[]){let n=[];function r(i,s){let a=Lv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Lv.useMemo(()=>m,Object.values(m));return(0,gXe.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Lv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Lv.createContext(s));return function(a){let l=a?.[t]||i;return Lv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,g6t(o,...e)]}function g6t(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Lv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var uY=N(U(),1),y6t=N(Ve(),1),w6t=uY.createContext(void 0);function wXe(t){let e=uY.useContext(w6t);return t||e||"ltr"}var Mi=N(U(),1);var tIr=!!(typeof window<"u"&&window.document&&window.document.createElement);function dY(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var CXe=N(U(),1),_Xe=N(yo(),1);var ta=N(U(),1);var xXe=N(U(),1);function vXe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function ybe(...t){return e=>{let n=!1,r=t.map(o=>{let i=vXe(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():vXe(t[o],null)}}}}function wbe(...t){return xXe.useCallback(ybe(...t),t)}var fY=N(Ve(),1);function bXe(t){let e=v6t(t),n=ta.forwardRef((r,o)=>{let{children:i,...s}=r,a=ta.Children.toArray(i),l=a.find(b6t);if(l){let c=l.props.children,u=a.map(d=>d===l?ta.Children.count(c)>1?ta.Children.only(null):ta.isValidElement(c)?c.props.children:null:d);return(0,fY.jsx)(e,{...s,ref:o,children:ta.isValidElement(c)?ta.cloneElement(c,void 0,u):null})}return(0,fY.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function v6t(t){let e=ta.forwardRef((n,r)=>{let{children:o,...i}=n;if(ta.isValidElement(o)){let s=_6t(o),a=C6t(i,o.props);return o.type!==ta.Fragment&&(a.ref=r?ybe(r,s):s),ta.cloneElement(o,a)}return ta.Children.count(o)>1?ta.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var x6t=Symbol("radix.slottable");function b6t(t){return ta.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===x6t}function C6t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function _6t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var SXe=N(Ve(),1),S6t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],vbe=S6t.reduce((t,e)=>{let n=bXe(`Primitive.${e}`),r=CXe.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,SXe.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function TXe(t,e){t&&_Xe.flushSync(()=>t.dispatchEvent(e))}var UR=N(U(),1);function xbe(t){let e=UR.useRef(t);return UR.useEffect(()=>{e.current=t}),UR.useMemo(()=>(...n)=>e.current?.(...n),[])}var PXe=N(U(),1);var BR=N(U(),1);function IXe(t){let e=BR.useRef(t);return BR.useEffect(()=>{e.current=t}),BR.useMemo(()=>(...n)=>e.current?.(...n),[])}function EXe(t,e=globalThis?.document){let n=IXe(t);PXe.useEffect(()=>{let r=o=>{o.key==="Escape"&&n(o)};return e.addEventListener("keydown",r,{capture:!0}),()=>e.removeEventListener("keydown",r,{capture:!0})},[n,e])}var Cbe=N(Ve(),1),T6t="DismissableLayer",bbe="dismissableLayer.update",I6t="dismissableLayer.pointerDownOutside",P6t="dismissableLayer.focusOutside",AXe,MXe=Mi.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),mh=Mi.forwardRef((t,e)=>{let{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:i,onInteractOutside:s,onDismiss:a,...l}=t,c=Mi.useContext(MXe),[u,d]=Mi.useState(null),f=u?.ownerDocument??globalThis?.document,[,p]=Mi.useState({}),m=wbe(e,T=>d(T)),h=Array.from(c.layers),[g]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),y=h.indexOf(g),w=u?h.indexOf(u):-1,v=c.layersWithOutsidePointerEventsDisabled.size>0,x=w>=y,b=k6t(T=>{let S=T.target,P=[...c.branches].some(A=>A.contains(S));!x||P||(o?.(T),s?.(T),T.defaultPrevented||a?.())},f),_=M6t(T=>{let S=T.target;[...c.branches].some(A=>A.contains(S))||(i?.(T),s?.(T),T.defaultPrevented||a?.())},f);return EXe(T=>{w===c.layers.size-1&&(r?.(T),!T.defaultPrevented&&a&&(T.preventDefault(),a()))},f),Mi.useEffect(()=>{if(u)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(AXe=f.body.style.pointerEvents,f.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),kXe(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(f.body.style.pointerEvents=AXe)}},[u,f,n,c]),Mi.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),kXe())},[u,c]),Mi.useEffect(()=>{let T=()=>p({});return document.addEventListener(bbe,T),()=>document.removeEventListener(bbe,T)},[]),(0,Cbe.jsx)(vbe.div,{...l,ref:m,style:{pointerEvents:v?x?"auto":"none":void 0,...t.style},onFocusCapture:dY(t.onFocusCapture,_.onFocusCapture),onBlurCapture:dY(t.onBlurCapture,_.onBlurCapture),onPointerDownCapture:dY(t.onPointerDownCapture,b.onPointerDownCapture)})});mh.displayName=T6t;var E6t="DismissableLayerBranch",A6t=Mi.forwardRef((t,e)=>{let n=Mi.useContext(MXe),r=Mi.useRef(null),o=wbe(e,r);return Mi.useEffect(()=>{let i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),(0,Cbe.jsx)(vbe.div,{...t,ref:o})});A6t.displayName=E6t;function k6t(t,e=globalThis?.document){let n=xbe(t),r=Mi.useRef(!1),o=Mi.useRef(()=>{});return Mi.useEffect(()=>{let i=a=>{if(a.target&&!r.current){let c=function(){NXe(I6t,n,u,{discrete:!0})};var l=c;let u={originalEvent:a};a.pointerType==="touch"?(e.removeEventListener("click",o.current),o.current=c,e.addEventListener("click",o.current,{once:!0})):c()}else e.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{e.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),e.removeEventListener("pointerdown",i),e.removeEventListener("click",o.current)}},[e,n]),{onPointerDownCapture:()=>r.current=!0}}function M6t(t,e=globalThis?.document){let n=xbe(t),r=Mi.useRef(!1);return Mi.useEffect(()=>{let o=i=>{i.target&&!r.current&&NXe(P6t,n,{originalEvent:i},{discrete:!1})};return e.addEventListener("focusin",o),()=>e.removeEventListener("focusin",o)},[e,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function kXe(){let t=new CustomEvent(bbe);document.dispatchEvent(t)}function NXe(t,e,n,{discrete:r}){let o=n.originalEvent.target,i=new CustomEvent(t,{bubbles:!1,cancelable:!0,detail:n});e&&o.addEventListener(t,e,{once:!0}),r?TXe(o,i):o.dispatchEvent(i)}var RXe=N(U(),1),_be=0;function x_(){RXe.useEffect(()=>{let t=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",t[0]??OXe()),document.body.insertAdjacentElement("beforeend",t[1]??OXe()),_be++,()=>{_be===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(e=>e.remove()),_be--}},[])}function OXe(){let t=document.createElement("span");return t.setAttribute("data-radix-focus-guard",""),t.tabIndex=0,t.style.outline="none",t.style.opacity="0",t.style.position="fixed",t.style.pointerEvents="none",t}var Bp=N(U(),1);var DXe=N(U(),1);function LXe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Sbe(...t){return e=>{let n=!1,r=t.map(o=>{let i=LXe(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():LXe(t[o],null)}}}}function $Xe(...t){return DXe.useCallback(Sbe(...t),t)}var UXe=N(U(),1),$6t=N(yo(),1);var na=N(U(),1);var pY=N(Ve(),1);function FXe(t){let e=N6t(t),n=na.forwardRef((r,o)=>{let{children:i,...s}=r,a=na.Children.toArray(i),l=a.find(R6t);if(l){let c=l.props.children,u=a.map(d=>d===l?na.Children.count(c)>1?na.Children.only(null):na.isValidElement(c)?c.props.children:null:d);return(0,pY.jsx)(e,{...s,ref:o,children:na.isValidElement(c)?na.cloneElement(c,void 0,u):null})}return(0,pY.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function N6t(t){let e=na.forwardRef((n,r)=>{let{children:o,...i}=n;if(na.isValidElement(o)){let s=D6t(o),a=L6t(i,o.props);return o.type!==na.Fragment&&(a.ref=r?Sbe(r,s):s),na.cloneElement(o,a)}return na.Children.count(o)>1?na.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var O6t=Symbol("radix.slottable");function R6t(t){return na.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===O6t}function L6t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function D6t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var BXe=N(Ve(),1),F6t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],zXe=F6t.reduce((t,e)=>{let n=FXe(`Primitive.${e}`),r=UXe.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,BXe.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var zR=N(U(),1);function Tbe(t){let e=zR.useRef(t);return zR.useEffect(()=>{e.current=t}),zR.useMemo(()=>(...n)=>e.current?.(...n),[])}var KXe=N(Ve(),1),Ibe="focusScope.autoFocusOnMount",Pbe="focusScope.autoFocusOnUnmount",jXe={bubbles:!1,cancelable:!0},U6t="FocusScope",Dv=Bp.forwardRef((t,e)=>{let{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=t,[a,l]=Bp.useState(null),c=Tbe(o),u=Tbe(i),d=Bp.useRef(null),f=$Xe(e,h=>l(h)),p=Bp.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;Bp.useEffect(()=>{if(r){let w=function(_){if(p.paused||!a)return;let T=_.target;a.contains(T)?d.current=T:b_(d.current,{select:!0})},v=function(_){if(p.paused||!a)return;let T=_.relatedTarget;T!==null&&(a.contains(T)||b_(d.current,{select:!0}))},x=function(_){if(document.activeElement===document.body)for(let S of _)S.removedNodes.length>0&&b_(a)};var h=w,g=v,y=x;document.addEventListener("focusin",w),document.addEventListener("focusout",v);let b=new MutationObserver(x);return a&&b.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",w),document.removeEventListener("focusout",v),b.disconnect()}}},[r,a,p.paused]),Bp.useEffect(()=>{if(a){WXe.add(p);let h=document.activeElement;if(!a.contains(h)){let y=new CustomEvent(Ibe,jXe);a.addEventListener(Ibe,c),a.dispatchEvent(y),y.defaultPrevented||(B6t(H6t(qXe(a)),{select:!0}),document.activeElement===h&&b_(a))}return()=>{a.removeEventListener(Ibe,c),setTimeout(()=>{let y=new CustomEvent(Pbe,jXe);a.addEventListener(Pbe,u),a.dispatchEvent(y),y.defaultPrevented||b_(h??document.body,{select:!0}),a.removeEventListener(Pbe,u),WXe.remove(p)},0)}}},[a,c,u,p]);let m=Bp.useCallback(h=>{if(!n&&!r||p.paused)return;let g=h.key==="Tab"&&!h.altKey&&!h.ctrlKey&&!h.metaKey,y=document.activeElement;if(g&&y){let w=h.currentTarget,[v,x]=z6t(w);v&&x?!h.shiftKey&&y===x?(h.preventDefault(),n&&b_(v,{select:!0})):h.shiftKey&&y===v&&(h.preventDefault(),n&&b_(x,{select:!0})):y===w&&h.preventDefault()}},[n,r,p.paused]);return(0,KXe.jsx)(zXe.div,{tabIndex:-1,...s,ref:f,onKeyDown:m})});Dv.displayName=U6t;function B6t(t,{select:e=!1}={}){let n=document.activeElement;for(let r of t)if(b_(r,{select:e}),document.activeElement!==n)return}function z6t(t){let e=qXe(t),n=VXe(e,t),r=VXe(e.reverse(),t);return[n,r]}function qXe(t){let e=[],n=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{let o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)e.push(n.currentNode);return e}function VXe(t,e){for(let n of t)if(!j6t(n,{upTo:e}))return n}function j6t(t,{upTo:e}){if(getComputedStyle(t).visibility==="hidden")return!0;for(;t;){if(e!==void 0&&t===e)return!1;if(getComputedStyle(t).display==="none")return!0;t=t.parentElement}return!1}function V6t(t){return t instanceof HTMLInputElement&&"select"in t}function b_(t,{select:e=!1}={}){if(t&&t.focus){let n=document.activeElement;t.focus({preventScroll:!0}),t!==n&&V6t(t)&&e&&t.select()}}var WXe=W6t();function W6t(){let t=[];return{add(e){let n=t[0];e!==n&&n?.pause(),t=HXe(t,e),t.unshift(e)},remove(e){t=HXe(t,e),t[0]?.resume()}}}function HXe(t,e){let n=[...t],r=n.indexOf(e);return r!==-1&&n.splice(r,1),n}function H6t(t){return t.filter(e=>e.tagName!=="A")}var Ebe=N(U(),1);var GXe=N(U(),1),kj=globalThis?.document?GXe.useLayoutEffect:()=>{};var K6t=Ebe[" useId ".trim().toString()]||(()=>{}),q6t=0;function Abe(t){let[e,n]=Ebe.useState(K6t());return kj(()=>{t||n(r=>r??String(q6t++))},[t]),t||(e?`radix-${e}`:"")}var rd=N(U(),1);var JXe=["top","right","bottom","left"];var yy=Math.min,au=Math.max,Nj=Math.round,Oj=Math.floor,hh=t=>({x:t,y:t}),G6t={left:"right",right:"left",bottom:"top",top:"bottom"},Y6t={start:"end",end:"start"};function hY(t,e,n){return au(t,yy(e,n))}function wy(t,e){return typeof t=="function"?t(e):t}function vy(t){return t.split("-")[0]}function CP(t){return t.split("-")[1]}function gY(t){return t==="x"?"y":"x"}function yY(t){return t==="y"?"height":"width"}var Z6t=new Set(["top","bottom"]);function gh(t){return Z6t.has(vy(t))?"y":"x"}function wY(t){return gY(gh(t))}function XXe(t,e,n){n===void 0&&(n=!1);let r=CP(t),o=wY(t),i=yY(o),s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return e.reference[i]>e.floating[i]&&(s=Mj(s)),[s,Mj(s)]}function QXe(t){let e=Mj(t);return[mY(t),e,mY(e)]}function mY(t){return t.replace(/start|end/g,e=>Y6t[e])}var YXe=["left","right"],ZXe=["right","left"],J6t=["top","bottom"],X6t=["bottom","top"];function Q6t(t,e,n){switch(t){case"top":case"bottom":return n?e?ZXe:YXe:e?YXe:ZXe;case"left":case"right":return e?J6t:X6t;default:return[]}}function eQe(t,e,n,r){let o=CP(t),i=Q6t(vy(t),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),e&&(i=i.concat(i.map(mY)))),i}function Mj(t){return t.replace(/left|right|bottom|top/g,e=>G6t[e])}function e3t(t){return{top:0,right:0,bottom:0,left:0,...t}}function kbe(t){return typeof t!="number"?e3t(t):{top:t,right:t,bottom:t,left:t}}function _P(t){let{x:e,y:n,width:r,height:o}=t;return{width:r,height:o,top:n,left:e,right:e+r,bottom:n+o,x:e,y:n}}function tQe(t,e,n){let{reference:r,floating:o}=t,i=gh(e),s=wY(e),a=yY(s),l=vy(e),c=i==="y",u=r.x+r.width/2-o.width/2,d=r.y+r.height/2-o.height/2,f=r[a]/2-o[a]/2,p;switch(l){case"top":p={x:u,y:r.y-o.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:d};break;case"left":p={x:r.x-o.width,y:d};break;default:p={x:r.x,y:r.y}}switch(CP(e)){case"start":p[s]-=f*(n&&c?-1:1);break;case"end":p[s]+=f*(n&&c?-1:1);break}return p}var oQe=async(t,e,n)=>{let{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,a=i.filter(Boolean),l=await(s.isRTL==null?void 0:s.isRTL(e)),c=await s.getElementRects({reference:t,floating:e,strategy:o}),{x:u,y:d}=tQe(c,r,l),f=r,p={},m=0;for(let h=0;h<a.length;h++){let{name:g,fn:y}=a[h],{x:w,y:v,data:x,reset:b}=await y({x:u,y:d,initialPlacement:r,placement:f,strategy:o,middlewareData:p,rects:c,platform:s,elements:{reference:t,floating:e}});u=w??u,d=v??d,p={...p,[g]:{...p[g],...x}},b&&m<=50&&(m++,typeof b=="object"&&(b.placement&&(f=b.placement),b.rects&&(c=b.rects===!0?await s.getElementRects({reference:t,floating:e,strategy:o}):b.rects),{x:u,y:d}=tQe(c,f,l)),h=-1)}return{x:u,y:d,placement:f,strategy:o,middlewareData:p}};async function jR(t,e){var n;e===void 0&&(e={});let{x:r,y:o,platform:i,rects:s,elements:a,strategy:l}=t,{boundary:c="clippingAncestors",rootBoundary:u="viewport",elementContext:d="floating",altBoundary:f=!1,padding:p=0}=wy(e,t),m=kbe(p),g=a[f?d==="floating"?"reference":"floating":d],y=_P(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(g)))==null||n?g:g.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(a.floating)),boundary:c,rootBoundary:u,strategy:l})),w=d==="floating"?{x:r,y:o,width:s.floating.width,height:s.floating.height}:s.reference,v=await(i.getOffsetParent==null?void 0:i.getOffsetParent(a.floating)),x=await(i.isElement==null?void 0:i.isElement(v))?await(i.getScale==null?void 0:i.getScale(v))||{x:1,y:1}:{x:1,y:1},b=_P(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:a,rect:w,offsetParent:v,strategy:l}):w);return{top:(y.top-b.top+m.top)/x.y,bottom:(b.bottom-y.bottom+m.bottom)/x.y,left:(y.left-b.left+m.left)/x.x,right:(b.right-y.right+m.right)/x.x}}var iQe=t=>({name:"arrow",options:t,async fn(e){let{x:n,y:r,placement:o,rects:i,platform:s,elements:a,middlewareData:l}=e,{element:c,padding:u=0}=wy(t,e)||{};if(c==null)return{};let d=kbe(u),f={x:n,y:r},p=wY(o),m=yY(p),h=await s.getDimensions(c),g=p==="y",y=g?"top":"left",w=g?"bottom":"right",v=g?"clientHeight":"clientWidth",x=i.reference[m]+i.reference[p]-f[p]-i.floating[m],b=f[p]-i.reference[p],_=await(s.getOffsetParent==null?void 0:s.getOffsetParent(c)),T=_?_[v]:0;(!T||!await(s.isElement==null?void 0:s.isElement(_)))&&(T=a.floating[v]||i.floating[m]);let S=x/2-b/2,P=T/2-h[m]/2-1,A=yy(d[y],P),O=yy(d[w],P),D=A,$=T-h[m]-O,B=T/2-h[m]/2+S,W=hY(D,B,$),F=!l.arrow&&CP(o)!=null&&B!==W&&i.reference[m]/2-(B<D?A:O)-h[m]/2<0,Z=F?B<D?B-D:B-$:0;return{[p]:f[p]+Z,data:{[p]:W,centerOffset:B-W-Z,...F&&{alignmentOffset:Z}},reset:F}}});var sQe=function(t){return t===void 0&&(t={}),{name:"flip",options:t,async fn(e){var n,r;let{placement:o,middlewareData:i,rects:s,initialPlacement:a,platform:l,elements:c}=e,{mainAxis:u=!0,crossAxis:d=!0,fallbackPlacements:f,fallbackStrategy:p="bestFit",fallbackAxisSideDirection:m="none",flipAlignment:h=!0,...g}=wy(t,e);if((n=i.arrow)!=null&&n.alignmentOffset)return{};let y=vy(o),w=gh(a),v=vy(a)===a,x=await(l.isRTL==null?void 0:l.isRTL(c.floating)),b=f||(v||!h?[Mj(a)]:QXe(a)),_=m!=="none";!f&&_&&b.push(...eQe(a,h,m,x));let T=[a,...b],S=await jR(e,g),P=[],A=((r=i.flip)==null?void 0:r.overflows)||[];if(u&&P.push(S[y]),d){let B=XXe(o,s,x);P.push(S[B[0]],S[B[1]])}if(A=[...A,{placement:o,overflows:P}],!P.every(B=>B<=0)){var O,D;let B=(((O=i.flip)==null?void 0:O.index)||0)+1,W=T[B];if(W&&(!(d==="alignment"?w!==gh(W):!1)||A.every(V=>gh(V.placement)===w?V.overflows[0]>0:!0)))return{data:{index:B,overflows:A},reset:{placement:W}};let F=(D=A.filter(Z=>Z.overflows[0]<=0).sort((Z,V)=>Z.overflows[1]-V.overflows[1])[0])==null?void 0:D.placement;if(!F)switch(p){case"bestFit":{var $;let Z=($=A.filter(V=>{if(_){let H=gh(V.placement);return H===w||H==="y"}return!0}).map(V=>[V.placement,V.overflows.filter(H=>H>0).reduce((H,te)=>H+te,0)]).sort((V,H)=>V[1]-H[1])[0])==null?void 0:$[0];Z&&(F=Z);break}case"initialPlacement":F=a;break}if(o!==F)return{reset:{placement:F}}}return{}}}};function nQe(t,e){return{top:t.top-e.height,right:t.right-e.width,bottom:t.bottom-e.height,left:t.left-e.width}}function rQe(t){return JXe.some(e=>t[e]>=0)}var aQe=function(t){return t===void 0&&(t={}),{name:"hide",options:t,async fn(e){let{rects:n}=e,{strategy:r="referenceHidden",...o}=wy(t,e);switch(r){case"referenceHidden":{let i=await jR(e,{...o,elementContext:"reference"}),s=nQe(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:rQe(s)}}}case"escaped":{let i=await jR(e,{...o,altBoundary:!0}),s=nQe(i,n.floating);return{data:{escapedOffsets:s,escaped:rQe(s)}}}default:return{}}}}};var lQe=new Set(["left","top"]);async function t3t(t,e){let{placement:n,platform:r,elements:o}=t,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=vy(n),a=CP(n),l=gh(n)==="y",c=lQe.has(s)?-1:1,u=i&&l?-1:1,d=wy(e,t),{mainAxis:f,crossAxis:p,alignmentAxis:m}=typeof d=="number"?{mainAxis:d,crossAxis:0,alignmentAxis:null}:{mainAxis:d.mainAxis||0,crossAxis:d.crossAxis||0,alignmentAxis:d.alignmentAxis};return a&&typeof m=="number"&&(p=a==="end"?m*-1:m),l?{x:p*u,y:f*c}:{x:f*c,y:p*u}}var cQe=function(t){return t===void 0&&(t=0),{name:"offset",options:t,async fn(e){var n,r;let{x:o,y:i,placement:s,middlewareData:a}=e,l=await t3t(e,t);return s===((n=a.offset)==null?void 0:n.placement)&&(r=a.arrow)!=null&&r.alignmentOffset?{}:{x:o+l.x,y:i+l.y,data:{...l,placement:s}}}}},uQe=function(t){return t===void 0&&(t={}),{name:"shift",options:t,async fn(e){let{x:n,y:r,placement:o}=e,{mainAxis:i=!0,crossAxis:s=!1,limiter:a={fn:g=>{let{x:y,y:w}=g;return{x:y,y:w}}},...l}=wy(t,e),c={x:n,y:r},u=await jR(e,l),d=gh(vy(o)),f=gY(d),p=c[f],m=c[d];if(i){let g=f==="y"?"top":"left",y=f==="y"?"bottom":"right",w=p+u[g],v=p-u[y];p=hY(w,p,v)}if(s){let g=d==="y"?"top":"left",y=d==="y"?"bottom":"right",w=m+u[g],v=m-u[y];m=hY(w,m,v)}let h=a.fn({...e,[f]:p,[d]:m});return{...h,data:{x:h.x-n,y:h.y-r,enabled:{[f]:i,[d]:s}}}}}},dQe=function(t){return t===void 0&&(t={}),{options:t,fn(e){let{x:n,y:r,placement:o,rects:i,middlewareData:s}=e,{offset:a=0,mainAxis:l=!0,crossAxis:c=!0}=wy(t,e),u={x:n,y:r},d=gh(o),f=gY(d),p=u[f],m=u[d],h=wy(a,e),g=typeof h=="number"?{mainAxis:h,crossAxis:0}:{mainAxis:0,crossAxis:0,...h};if(l){let v=f==="y"?"height":"width",x=i.reference[f]-i.floating[v]+g.mainAxis,b=i.reference[f]+i.reference[v]-g.mainAxis;p<x?p=x:p>b&&(p=b)}if(c){var y,w;let v=f==="y"?"width":"height",x=lQe.has(vy(o)),b=i.reference[d]-i.floating[v]+(x&&((y=s.offset)==null?void 0:y[d])||0)+(x?0:g.crossAxis),_=i.reference[d]+i.reference[v]+(x?0:((w=s.offset)==null?void 0:w[d])||0)-(x?g.crossAxis:0);m<b?m=b:m>_&&(m=_)}return{[f]:p,[d]:m}}}},fQe=function(t){return t===void 0&&(t={}),{name:"size",options:t,async fn(e){var n,r;let{placement:o,rects:i,platform:s,elements:a}=e,{apply:l=()=>{},...c}=wy(t,e),u=await jR(e,c),d=vy(o),f=CP(o),p=gh(o)==="y",{width:m,height:h}=i.floating,g,y;d==="top"||d==="bottom"?(g=d,y=f===(await(s.isRTL==null?void 0:s.isRTL(a.floating))?"start":"end")?"left":"right"):(y=d,g=f==="end"?"top":"bottom");let w=h-u.top-u.bottom,v=m-u.left-u.right,x=yy(h-u[g],w),b=yy(m-u[y],v),_=!e.middlewareData.shift,T=x,S=b;if((n=e.middlewareData.shift)!=null&&n.enabled.x&&(S=v),(r=e.middlewareData.shift)!=null&&r.enabled.y&&(T=w),_&&!f){let A=au(u.left,0),O=au(u.right,0),D=au(u.top,0),$=au(u.bottom,0);p?S=m-2*(A!==0||O!==0?A+O:au(u.left,u.right)):T=h-2*(D!==0||$!==0?D+$:au(u.top,u.bottom))}await l({...e,availableWidth:S,availableHeight:T});let P=await s.getDimensions(a.floating);return m!==P.width||h!==P.height?{reset:{rects:!0}}:{}}}};function vY(){return typeof window<"u"}function TP(t){return mQe(t)?(t.nodeName||"").toLowerCase():"#document"}function nd(t){var e;return(t==null||(e=t.ownerDocument)==null?void 0:e.defaultView)||window}function yh(t){var e;return(e=(mQe(t)?t.ownerDocument:t.document)||window.document)==null?void 0:e.documentElement}function mQe(t){return vY()?t instanceof Node||t instanceof nd(t).Node:!1}function zp(t){return vY()?t instanceof Element||t instanceof nd(t).Element:!1}function wh(t){return vY()?t instanceof HTMLElement||t instanceof nd(t).HTMLElement:!1}function pQe(t){return!vY()||typeof ShadowRoot>"u"?!1:t instanceof ShadowRoot||t instanceof nd(t).ShadowRoot}var n3t=new Set(["inline","contents"]);function VR(t){let{overflow:e,overflowX:n,overflowY:r,display:o}=jp(t);return/auto|scroll|overlay|hidden|clip/.test(e+r+n)&&!n3t.has(o)}var r3t=new Set(["table","td","th"]);function hQe(t){return r3t.has(TP(t))}var o3t=[":popover-open",":modal"];function Rj(t){return o3t.some(e=>{try{return t.matches(e)}catch{return!1}})}var i3t=["transform","translate","scale","rotate","perspective"],s3t=["transform","translate","scale","rotate","perspective","filter"],a3t=["paint","layout","strict","content"];function xY(t){let e=bY(),n=zp(t)?jp(t):t;return i3t.some(r=>n[r]?n[r]!=="none":!1)||(n.containerType?n.containerType!=="normal":!1)||!e&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!e&&(n.filter?n.filter!=="none":!1)||s3t.some(r=>(n.willChange||"").includes(r))||a3t.some(r=>(n.contain||"").includes(r))}function gQe(t){let e=$v(t);for(;wh(e)&&!IP(e);){if(xY(e))return e;if(Rj(e))return null;e=$v(e)}return null}function bY(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}var l3t=new Set(["html","body","#document"]);function IP(t){return l3t.has(TP(t))}function jp(t){return nd(t).getComputedStyle(t)}function Lj(t){return zp(t)?{scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}:{scrollLeft:t.scrollX,scrollTop:t.scrollY}}function $v(t){if(TP(t)==="html")return t;let e=t.assignedSlot||t.parentNode||pQe(t)&&t.host||yh(t);return pQe(e)?e.host:e}function yQe(t){let e=$v(t);return IP(e)?t.ownerDocument?t.ownerDocument.body:t.body:wh(e)&&VR(e)?e:yQe(e)}function SP(t,e,n){var r;e===void 0&&(e=[]),n===void 0&&(n=!0);let o=yQe(t),i=o===((r=t.ownerDocument)==null?void 0:r.body),s=nd(o);if(i){let a=CY(s);return e.concat(s,s.visualViewport||[],VR(o)?o:[],a&&n?SP(a):[])}return e.concat(o,SP(o,[],n))}function CY(t){return t.parent&&Object.getPrototypeOf(t.parent)?t.frameElement:null}function bQe(t){let e=jp(t),n=parseFloat(e.width)||0,r=parseFloat(e.height)||0,o=wh(t),i=o?t.offsetWidth:n,s=o?t.offsetHeight:r,a=Nj(n)!==i||Nj(r)!==s;return a&&(n=i,r=s),{width:n,height:r,$:a}}function Nbe(t){return zp(t)?t:t.contextElement}function WR(t){let e=Nbe(t);if(!wh(e))return hh(1);let n=e.getBoundingClientRect(),{width:r,height:o,$:i}=bQe(e),s=(i?Nj(n.width):n.width)/r,a=(i?Nj(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!a||!Number.isFinite(a))&&(a=1),{x:s,y:a}}var c3t=hh(0);function CQe(t){let e=nd(t);return!bY()||!e.visualViewport?c3t:{x:e.visualViewport.offsetLeft,y:e.visualViewport.offsetTop}}function u3t(t,e,n){return e===void 0&&(e=!1),!n||e&&n!==nd(t)?!1:e}function PP(t,e,n,r){e===void 0&&(e=!1),n===void 0&&(n=!1);let o=t.getBoundingClientRect(),i=Nbe(t),s=hh(1);e&&(r?zp(r)&&(s=WR(r)):s=WR(t));let a=u3t(i,n,r)?CQe(i):hh(0),l=(o.left+a.x)/s.x,c=(o.top+a.y)/s.y,u=o.width/s.x,d=o.height/s.y;if(i){let f=nd(i),p=r&&zp(r)?nd(r):r,m=f,h=CY(m);for(;h&&r&&p!==m;){let g=WR(h),y=h.getBoundingClientRect(),w=jp(h),v=y.left+(h.clientLeft+parseFloat(w.paddingLeft))*g.x,x=y.top+(h.clientTop+parseFloat(w.paddingTop))*g.y;l*=g.x,c*=g.y,u*=g.x,d*=g.y,l+=v,c+=x,m=nd(h),h=CY(m)}}return _P({width:u,height:d,x:l,y:c})}function _Y(t,e){let n=Lj(t).scrollLeft;return e?e.left+n:PP(yh(t)).left+n}function _Qe(t,e){let n=t.getBoundingClientRect(),r=n.left+e.scrollLeft-_Y(t,n),o=n.top+e.scrollTop;return{x:r,y:o}}function d3t(t){let{elements:e,rect:n,offsetParent:r,strategy:o}=t,i=o==="fixed",s=yh(r),a=e?Rj(e.floating):!1;if(r===s||a&&i)return n;let l={scrollLeft:0,scrollTop:0},c=hh(1),u=hh(0),d=wh(r);if((d||!d&&!i)&&((TP(r)!=="body"||VR(s))&&(l=Lj(r)),wh(r))){let p=PP(r);c=WR(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}let f=s&&!d&&!i?_Qe(s,l):hh(0);return{width:n.width*c.x,height:n.height*c.y,x:n.x*c.x-l.scrollLeft*c.x+u.x+f.x,y:n.y*c.y-l.scrollTop*c.y+u.y+f.y}}function f3t(t){return Array.from(t.getClientRects())}function p3t(t){let e=yh(t),n=Lj(t),r=t.ownerDocument.body,o=au(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),i=au(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight),s=-n.scrollLeft+_Y(t),a=-n.scrollTop;return jp(r).direction==="rtl"&&(s+=au(e.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:a}}var wQe=25;function m3t(t,e){let n=nd(t),r=yh(t),o=n.visualViewport,i=r.clientWidth,s=r.clientHeight,a=0,l=0;if(o){i=o.width,s=o.height;let u=bY();(!u||u&&e==="fixed")&&(a=o.offsetLeft,l=o.offsetTop)}let c=_Y(r);if(c<=0){let u=r.ownerDocument,d=u.body,f=getComputedStyle(d),p=u.compatMode==="CSS1Compat"&&parseFloat(f.marginLeft)+parseFloat(f.marginRight)||0,m=Math.abs(r.clientWidth-d.clientWidth-p);m<=wQe&&(i-=m)}else c<=wQe&&(i+=c);return{width:i,height:s,x:a,y:l}}var h3t=new Set(["absolute","fixed"]);function g3t(t,e){let n=PP(t,!0,e==="fixed"),r=n.top+t.clientTop,o=n.left+t.clientLeft,i=wh(t)?WR(t):hh(1),s=t.clientWidth*i.x,a=t.clientHeight*i.y,l=o*i.x,c=r*i.y;return{width:s,height:a,x:l,y:c}}function vQe(t,e,n){let r;if(e==="viewport")r=m3t(t,n);else if(e==="document")r=p3t(yh(t));else if(zp(e))r=g3t(e,n);else{let o=CQe(t);r={x:e.x-o.x,y:e.y-o.y,width:e.width,height:e.height}}return _P(r)}function SQe(t,e){let n=$v(t);return n===e||!zp(n)||IP(n)?!1:jp(n).position==="fixed"||SQe(n,e)}function y3t(t,e){let n=e.get(t);if(n)return n;let r=SP(t,[],!1).filter(a=>zp(a)&&TP(a)!=="body"),o=null,i=jp(t).position==="fixed",s=i?$v(t):t;for(;zp(s)&&!IP(s);){let a=jp(s),l=xY(s);!l&&a.position==="fixed"&&(o=null),(i?!l&&!o:!l&&a.position==="static"&&!!o&&h3t.has(o.position)||VR(s)&&!l&&SQe(t,s))?r=r.filter(u=>u!==s):o=a,s=$v(s)}return e.set(t,r),r}function w3t(t){let{element:e,boundary:n,rootBoundary:r,strategy:o}=t,s=[...n==="clippingAncestors"?Rj(e)?[]:y3t(e,this._c):[].concat(n),r],a=s[0],l=s.reduce((c,u)=>{let d=vQe(e,u,o);return c.top=au(d.top,c.top),c.right=yy(d.right,c.right),c.bottom=yy(d.bottom,c.bottom),c.left=au(d.left,c.left),c},vQe(e,a,o));return{width:l.right-l.left,height:l.bottom-l.top,x:l.left,y:l.top}}function v3t(t){let{width:e,height:n}=bQe(t);return{width:e,height:n}}function x3t(t,e,n){let r=wh(e),o=yh(e),i=n==="fixed",s=PP(t,!0,i,e),a={scrollLeft:0,scrollTop:0},l=hh(0);function c(){l.x=_Y(o)}if(r||!r&&!i)if((TP(e)!=="body"||VR(o))&&(a=Lj(e)),r){let p=PP(e,!0,i,e);l.x=p.x+e.clientLeft,l.y=p.y+e.clientTop}else o&&c();i&&!r&&o&&c();let u=o&&!r&&!i?_Qe(o,a):hh(0),d=s.left+a.scrollLeft-l.x-u.x,f=s.top+a.scrollTop-l.y-u.y;return{x:d,y:f,width:s.width,height:s.height}}function Mbe(t){return jp(t).position==="static"}function xQe(t,e){if(!wh(t)||jp(t).position==="fixed")return null;if(e)return e(t);let n=t.offsetParent;return yh(t)===n&&(n=n.ownerDocument.body),n}function TQe(t,e){let n=nd(t);if(Rj(t))return n;if(!wh(t)){let o=$v(t);for(;o&&!IP(o);){if(zp(o)&&!Mbe(o))return o;o=$v(o)}return n}let r=xQe(t,e);for(;r&&hQe(r)&&Mbe(r);)r=xQe(r,e);return r&&IP(r)&&Mbe(r)&&!xY(r)?n:r||gQe(t)||n}var b3t=async function(t){let e=this.getOffsetParent||TQe,n=this.getDimensions,r=await n(t.floating);return{reference:x3t(t.reference,await e(t.floating),t.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function C3t(t){return jp(t).direction==="rtl"}var IQe={convertOffsetParentRelativeRectToViewportRelativeRect:d3t,getDocumentElement:yh,getClippingRect:w3t,getOffsetParent:TQe,getElementRects:b3t,getClientRects:f3t,getDimensions:v3t,getScale:WR,isElement:zp,isRTL:C3t};function PQe(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height}function _3t(t,e){let n=null,r,o=yh(t);function i(){var a;clearTimeout(r),(a=n)==null||a.disconnect(),n=null}function s(a,l){a===void 0&&(a=!1),l===void 0&&(l=1),i();let c=t.getBoundingClientRect(),{left:u,top:d,width:f,height:p}=c;if(a||e(),!f||!p)return;let m=Oj(d),h=Oj(o.clientWidth-(u+f)),g=Oj(o.clientHeight-(d+p)),y=Oj(u),v={rootMargin:-m+"px "+-h+"px "+-g+"px "+-y+"px",threshold:au(0,yy(1,l))||1},x=!0;function b(_){let T=_[0].intersectionRatio;if(T!==l){if(!x)return s();T?s(!1,T):r=setTimeout(()=>{s(!1,1e-7)},1e3)}T===1&&!PQe(c,t.getBoundingClientRect())&&s(),x=!1}try{n=new IntersectionObserver(b,{...v,root:o.ownerDocument})}catch{n=new IntersectionObserver(b,v)}n.observe(t)}return s(!0),i}function Obe(t,e,n,r){r===void 0&&(r={});let{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:a=typeof IntersectionObserver=="function",animationFrame:l=!1}=r,c=Nbe(t),u=o||i?[...c?SP(c):[],...SP(e)]:[];u.forEach(y=>{o&&y.addEventListener("scroll",n,{passive:!0}),i&&y.addEventListener("resize",n)});let d=c&&a?_3t(c,n):null,f=-1,p=null;s&&(p=new ResizeObserver(y=>{let[w]=y;w&&w.target===c&&p&&(p.unobserve(e),cancelAnimationFrame(f),f=requestAnimationFrame(()=>{var v;(v=p)==null||v.observe(e)})),n()}),c&&!l&&p.observe(c),p.observe(e));let m,h=l?PP(t):null;l&&g();function g(){let y=PP(t);h&&!PQe(h,y)&&n(),h=y,m=requestAnimationFrame(g)}return n(),()=>{var y;u.forEach(w=>{o&&w.removeEventListener("scroll",n),i&&w.removeEventListener("resize",n)}),d?.(),(y=p)==null||y.disconnect(),p=null,l&&cancelAnimationFrame(m)}}var EQe=cQe;var AQe=uQe,kQe=sQe,MQe=fQe,NQe=aQe,Rbe=iQe;var OQe=dQe,Lbe=(t,e,n)=>{let r=new Map,o={platform:IQe,...n},i={...o.platform,_c:r};return oQe(t,e,{...o,platform:i})};var Es=N(U(),1),LQe=N(U(),1),DQe=N(yo(),1),S3t=typeof document<"u",T3t=function(){},SY=S3t?LQe.useLayoutEffect:T3t;function TY(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(typeof t=="function"&&t.toString()===e.toString())return!0;let n,r,o;if(t&&e&&typeof t=="object"){if(Array.isArray(t)){if(n=t.length,n!==e.length)return!1;for(r=n;r--!==0;)if(!TY(t[r],e[r]))return!1;return!0}if(o=Object.keys(t),n=o.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(e,o[r]))return!1;for(r=n;r--!==0;){let i=o[r];if(!(i==="_owner"&&t.$$typeof)&&!TY(t[i],e[i]))return!1}return!0}return t!==t&&e!==e}function $Qe(t){return typeof window>"u"?1:(t.ownerDocument.defaultView||window).devicePixelRatio||1}function RQe(t,e){let n=$Qe(t);return Math.round(e*n)/n}function Dbe(t){let e=Es.useRef(t);return SY(()=>{e.current=t}),e}function FQe(t){t===void 0&&(t={});let{placement:e="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:a=!0,whileElementsMounted:l,open:c}=t,[u,d]=Es.useState({x:0,y:0,strategy:n,placement:e,middlewareData:{},isPositioned:!1}),[f,p]=Es.useState(r);TY(f,r)||p(r);let[m,h]=Es.useState(null),[g,y]=Es.useState(null),w=Es.useCallback(V=>{V!==_.current&&(_.current=V,h(V))},[]),v=Es.useCallback(V=>{V!==T.current&&(T.current=V,y(V))},[]),x=i||m,b=s||g,_=Es.useRef(null),T=Es.useRef(null),S=Es.useRef(u),P=l!=null,A=Dbe(l),O=Dbe(o),D=Dbe(c),$=Es.useCallback(()=>{if(!_.current||!T.current)return;let V={placement:e,strategy:n,middleware:f};O.current&&(V.platform=O.current),Lbe(_.current,T.current,V).then(H=>{let te={...H,isPositioned:D.current!==!1};B.current&&!TY(S.current,te)&&(S.current=te,DQe.flushSync(()=>{d(te)}))})},[f,e,n,O,D]);SY(()=>{c===!1&&S.current.isPositioned&&(S.current.isPositioned=!1,d(V=>({...V,isPositioned:!1})))},[c]);let B=Es.useRef(!1);SY(()=>(B.current=!0,()=>{B.current=!1}),[]),SY(()=>{if(x&&(_.current=x),b&&(T.current=b),x&&b){if(A.current)return A.current(x,b,$);$()}},[x,b,$,A,P]);let W=Es.useMemo(()=>({reference:_,floating:T,setReference:w,setFloating:v}),[w,v]),F=Es.useMemo(()=>({reference:x,floating:b}),[x,b]),Z=Es.useMemo(()=>{let V={position:n,left:0,top:0};if(!F.floating)return V;let H=RQe(F.floating,u.x),te=RQe(F.floating,u.y);return a?{...V,transform:"translate("+H+"px, "+te+"px)",...$Qe(F.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:H,top:te}},[n,a,F.floating,u.x,u.y]);return Es.useMemo(()=>({...u,update:$,refs:W,elements:F,floatingStyles:Z}),[u,$,W,F,Z])}var I3t=t=>{function e(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:t,fn(n){let{element:r,padding:o}=typeof t=="function"?t(n):t;return r&&e(r)?r.current!=null?Rbe({element:r.current,padding:o}).fn(n):{}:r?Rbe({element:r,padding:o}).fn(n):{}}}},UQe=(t,e)=>({...EQe(t),options:[t,e]}),BQe=(t,e)=>({...AQe(t),options:[t,e]}),zQe=(t,e)=>({...OQe(t),options:[t,e]}),jQe=(t,e)=>({...kQe(t),options:[t,e]}),VQe=(t,e)=>({...MQe(t),options:[t,e]});var WQe=(t,e)=>({...NQe(t),options:[t,e]});var HQe=(t,e)=>({...I3t(t),options:[t,e]});var XQe=N(U(),1);var YQe=N(U(),1),O3t=N(yo(),1);var ra=N(U(),1);var P3t=N(U(),1);function KQe(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function qQe(...t){return e=>{let n=!1,r=t.map(o=>{let i=KQe(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():KQe(t[o],null)}}}}var IY=N(Ve(),1);function GQe(t){let e=E3t(t),n=ra.forwardRef((r,o)=>{let{children:i,...s}=r,a=ra.Children.toArray(i),l=a.find(k3t);if(l){let c=l.props.children,u=a.map(d=>d===l?ra.Children.count(c)>1?ra.Children.only(null):ra.isValidElement(c)?c.props.children:null:d);return(0,IY.jsx)(e,{...s,ref:o,children:ra.isValidElement(c)?ra.cloneElement(c,void 0,u):null})}return(0,IY.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function E3t(t){let e=ra.forwardRef((n,r)=>{let{children:o,...i}=n;if(ra.isValidElement(o)){let s=N3t(o),a=M3t(i,o.props);return o.type!==ra.Fragment&&(a.ref=r?qQe(r,s):s),ra.cloneElement(o,a)}return ra.Children.count(o)>1?ra.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var A3t=Symbol("radix.slottable");function k3t(t){return ra.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===A3t}function M3t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function N3t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var ZQe=N(Ve(),1),R3t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],JQe=R3t.reduce((t,e)=>{let n=GQe(`Primitive.${e}`),r=YQe.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,ZQe.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var $be=N(Ve(),1),L3t="Arrow",QQe=XQe.forwardRef((t,e)=>{let{children:n,width:r=10,height:o=5,...i}=t;return(0,$be.jsx)(JQe.svg,{...i,ref:e,width:r,height:o,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:t.asChild?n:(0,$be.jsx)("polygon",{points:"0,0 30,0 15,10"})})});QQe.displayName=L3t;var eet=QQe;var net=N(U(),1);function tet(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Fbe(...t){return e=>{let n=!1,r=t.map(o=>{let i=tet(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():tet(t[o],null)}}}}function Ube(...t){return net.useCallback(Fbe(...t),t)}var Fv=N(U(),1),ret=N(Ve(),1);function oet(t,e=[]){let n=[];function r(i,s){let a=Fv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Fv.useMemo(()=>m,Object.values(m));return(0,ret.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Fv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Fv.createContext(s));return function(a){let l=a?.[t]||i;return Fv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,$3t(o,...e)]}function $3t(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Fv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var set=N(U(),1),V3t=N(yo(),1);var oa=N(U(),1);var PY=N(Ve(),1);function iet(t){let e=F3t(t),n=oa.forwardRef((r,o)=>{let{children:i,...s}=r,a=oa.Children.toArray(i),l=a.find(B3t);if(l){let c=l.props.children,u=a.map(d=>d===l?oa.Children.count(c)>1?oa.Children.only(null):oa.isValidElement(c)?c.props.children:null:d);return(0,PY.jsx)(e,{...s,ref:o,children:oa.isValidElement(c)?oa.cloneElement(c,void 0,u):null})}return(0,PY.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function F3t(t){let e=oa.forwardRef((n,r)=>{let{children:o,...i}=n;if(oa.isValidElement(o)){let s=j3t(o),a=z3t(i,o.props);return o.type!==oa.Fragment&&(a.ref=r?Fbe(r,s):s),oa.cloneElement(o,a)}return oa.Children.count(o)>1?oa.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var U3t=Symbol("radix.slottable");function B3t(t){return oa.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===U3t}function z3t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function j3t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var aet=N(Ve(),1),W3t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Bbe=W3t.reduce((t,e)=>{let n=iet(`Primitive.${e}`),r=set.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,aet.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var HR=N(U(),1);function cet(t){let e=HR.useRef(t);return HR.useEffect(()=>{e.current=t}),HR.useMemo(()=>(...n)=>e.current?.(...n),[])}var uet=N(U(),1),Dj=globalThis?.document?uet.useLayoutEffect:()=>{};var det=N(U(),1);function fet(t){let[e,n]=det.useState(void 0);return Dj(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});let r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;let i=o[0],s,a;if("borderBoxSize"in i){let l=i.borderBoxSize,c=Array.isArray(l)?l[0]:l;s=c.inlineSize,a=c.blockSize}else s=t.offsetWidth,a=t.offsetHeight;n({width:s,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var C_=N(Ve(),1);var zbe="Popper",[pet,Vp]=oet(zbe),[H3t,met]=pet(zbe),het=t=>{let{__scopePopper:e,children:n}=t,[r,o]=rd.useState(null);return(0,C_.jsx)(H3t,{scope:e,anchor:r,onAnchorChange:o,children:n})};het.displayName=zbe;var get="PopperAnchor",yet=rd.forwardRef((t,e)=>{let{__scopePopper:n,virtualRef:r,...o}=t,i=met(get,n),s=rd.useRef(null),a=Ube(e,s),l=rd.useRef(null);return rd.useEffect(()=>{let c=l.current;l.current=r?.current||s.current,c!==l.current&&i.onAnchorChange(l.current)}),r?null:(0,C_.jsx)(Bbe.div,{...o,ref:a})});yet.displayName=get;var jbe="PopperContent",[K3t,q3t]=pet(jbe),wet=rd.forwardRef((t,e)=>{let{__scopePopper:n,side:r="bottom",sideOffset:o=0,align:i="center",alignOffset:s=0,arrowPadding:a=0,avoidCollisions:l=!0,collisionBoundary:c=[],collisionPadding:u=0,sticky:d="partial",hideWhenDetached:f=!1,updatePositionStrategy:p="optimized",onPlaced:m,...h}=t,g=met(jbe,n),[y,w]=rd.useState(null),v=Ube(e,E=>w(E)),[x,b]=rd.useState(null),_=fet(x),T=_?.width??0,S=_?.height??0,P=r+(i!=="center"?"-"+i:""),A=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},O=Array.isArray(c)?c:[c],D=O.length>0,$={padding:A,boundary:O.filter(Y3t),altBoundary:D},{refs:B,floatingStyles:W,placement:F,isPositioned:Z,middlewareData:V}=FQe({strategy:"fixed",placement:P,whileElementsMounted:(...E)=>Obe(...E,{animationFrame:p==="always"}),elements:{reference:g.anchor},middleware:[UQe({mainAxis:o+S,alignmentAxis:s}),l&&BQe({mainAxis:!0,crossAxis:!1,limiter:d==="partial"?zQe():void 0,...$}),l&&jQe({...$}),VQe({...$,apply:({elements:E,rects:R,availableWidth:L,availableHeight:K})=>{let{width:Y,height:re}=R.reference,ae=E.floating.style;ae.setProperty("--radix-popper-available-width",`${L}px`),ae.setProperty("--radix-popper-available-height",`${K}px`),ae.setProperty("--radix-popper-anchor-width",`${Y}px`),ae.setProperty("--radix-popper-anchor-height",`${re}px`)}}),x&&HQe({element:x,padding:a}),Z3t({arrowWidth:T,arrowHeight:S}),f&&WQe({strategy:"referenceHidden",...$})]}),[H,te]=bet(F),fe=cet(m);Dj(()=>{Z&&fe?.()},[Z,fe]);let me=V.arrow?.x,j=V.arrow?.y,G=V.arrow?.centerOffset!==0,[J,M]=rd.useState();return Dj(()=>{y&&M(window.getComputedStyle(y).zIndex)},[y]),(0,C_.jsx)("div",{ref:B.setFloating,"data-radix-popper-content-wrapper":"",style:{...W,transform:Z?W.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:J,"--radix-popper-transform-origin":[V.transformOrigin?.x,V.transformOrigin?.y].join(" "),...V.hide?.referenceHidden&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:(0,C_.jsx)(K3t,{scope:n,placedSide:H,onArrowChange:b,arrowX:me,arrowY:j,shouldHideArrow:G,children:(0,C_.jsx)(Bbe.div,{"data-side":H,"data-align":te,...h,ref:v,style:{...h.style,animation:Z?void 0:"none"}})})})});wet.displayName=jbe;var vet="PopperArrow",G3t={top:"bottom",right:"left",bottom:"top",left:"right"},xet=rd.forwardRef(function(e,n){let{__scopePopper:r,...o}=e,i=q3t(vet,r),s=G3t[i.placedSide];return(0,C_.jsx)("span",{ref:i.onArrowChange,style:{position:"absolute",left:i.arrowX,top:i.arrowY,[s]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[i.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[i.placedSide],visibility:i.shouldHideArrow?"hidden":void 0},children:(0,C_.jsx)(eet,{...o,ref:n,style:{...o.style,display:"block"}})})});xet.displayName=vet;function Y3t(t){return t!==null}var Z3t=t=>({name:"transformOrigin",options:t,fn(e){let{placement:n,rects:r,middlewareData:o}=e,s=o.arrow?.centerOffset!==0,a=s?0:t.arrowWidth,l=s?0:t.arrowHeight,[c,u]=bet(n),d={start:"0%",center:"50%",end:"100%"}[u],f=(o.arrow?.x??0)+a/2,p=(o.arrow?.y??0)+l/2,m="",h="";return c==="bottom"?(m=s?d:`${f}px`,h=`${-l}px`):c==="top"?(m=s?d:`${f}px`,h=`${r.floating.height+l}px`):c==="right"?(m=`${-l}px`,h=s?d:`${p}px`):c==="left"&&(m=`${r.floating.width+l}px`,h=s?d:`${p}px`),{data:{x:m,y:h}}}});function bet(t){let[e,n="center"]=t.split("-");return[e,n]}var Uv=het,Bv=yet,__=wet,S_=xet;var kY=N(U(),1),Met=N(yo(),1);var Iet=N(U(),1),rKt=N(yo(),1);var ia=N(U(),1);var J3t=N(U(),1);function Cet(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function _et(...t){return e=>{let n=!1,r=t.map(o=>{let i=Cet(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():Cet(t[o],null)}}}}var AY=N(Ve(),1);function Tet(t){let e=X3t(t),n=ia.forwardRef((r,o)=>{let{children:i,...s}=r,a=ia.Children.toArray(i),l=a.find(eKt);if(l){let c=l.props.children,u=a.map(d=>d===l?ia.Children.count(c)>1?ia.Children.only(null):ia.isValidElement(c)?c.props.children:null:d);return(0,AY.jsx)(e,{...s,ref:o,children:ia.isValidElement(c)?ia.cloneElement(c,void 0,u):null})}return(0,AY.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function X3t(t){let e=ia.forwardRef((n,r)=>{let{children:o,...i}=n;if(ia.isValidElement(o)){let s=nKt(o),a=tKt(i,o.props);return o.type!==ia.Fragment&&(a.ref=r?_et(r,s):s),ia.cloneElement(o,a)}return ia.Children.count(o)>1?ia.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var Q3t=Symbol("radix.slottable");function eKt(t){return ia.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Q3t}function tKt(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function nKt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Pet=N(Ve(),1),oKt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Eet=oKt.reduce((t,e)=>{let n=Tet(`Primitive.${e}`),r=Iet.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,Pet.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var Aet=N(U(),1),ket=globalThis?.document?Aet.useLayoutEffect:()=>{};var Net=N(Ve(),1),iKt="Portal",vh=kY.forwardRef((t,e)=>{let{container:n,...r}=t,[o,i]=kY.useState(!1);ket(()=>i(!0),[]);let s=n||o&&globalThis?.document?.body;return s?Met.default.createPortal((0,Net.jsx)(Eet.div,{...r,ref:e}),s):null});vh.displayName=iKt;var od=N(U(),1);var Oet=N(U(),1);function sKt(t,e){return Oet.useReducer((n,r)=>e[n][r]??n,t)}var KR=t=>{let{present:e,children:n}=t,r=aKt(e),o=typeof n=="function"?n({present:r.isPresent}):od.Children.only(n),i=v_(r.ref,lKt(o));return typeof n=="function"||r.isPresent?od.cloneElement(o,{ref:i}):null};KR.displayName="Presence";function aKt(t){let[e,n]=od.useState(),r=od.useRef(null),o=od.useRef(t),i=od.useRef("none"),s=t?"mounted":"unmounted",[a,l]=sKt(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return od.useEffect(()=>{let c=MY(r.current);i.current=a==="mounted"?c:"none"},[a]),kj(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=MY(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),kj(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=MY(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=MY(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:od.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function MY(t){return t?.animationName||"none"}function lKt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Ret=N(U(),1),Let=N(yo(),1);var sa=N(U(),1);var NY=N(Ve(),1);function OY(t){let e=cKt(t),n=sa.forwardRef((r,o)=>{let{children:i,...s}=r,a=sa.Children.toArray(i),l=a.find(dKt);if(l){let c=l.props.children,u=a.map(d=>d===l?sa.Children.count(c)>1?sa.Children.only(null):sa.isValidElement(c)?c.props.children:null:d);return(0,NY.jsx)(e,{...s,ref:o,children:sa.isValidElement(c)?sa.cloneElement(c,void 0,u):null})}return(0,NY.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function cKt(t){let e=sa.forwardRef((n,r)=>{let{children:o,...i}=n;if(sa.isValidElement(o)){let s=pKt(o),a=fKt(i,o.props);return o.type!==sa.Fragment&&(a.ref=r?Aj(r,s):s),sa.cloneElement(o,a)}return sa.Children.count(o)>1?sa.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var uKt=Symbol("radix.slottable");function dKt(t){return sa.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===uKt}function fKt(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function pKt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Det=N(Ve(),1),mKt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],qR=mKt.reduce((t,e)=>{let n=OY(`Primitive.${e}`),r=Ret.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,Det.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});function $et(t,e){t&&Let.flushSync(()=>t.dispatchEvent(e))}var qa=N(U(),1);var L0r=!!(typeof window<"u"&&window.document&&window.document.createElement);function EP(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var Uet=N(U(),1);function Fet(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Vbe(...t){return e=>{let n=!1,r=t.map(o=>{let i=Fet(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():Fet(t[o],null)}}}}function Bet(...t){return Uet.useCallback(Vbe(...t),t)}var zv=N(U(),1),zet=N(Ve(),1);function jet(t,e=[]){let n=[];function r(i,s){let a=zv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=zv.useMemo(()=>m,Object.values(m));return(0,zet.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=zv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>zv.createContext(s));return function(a){let l=a?.[t]||i;return zv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,hKt(o,...e)]}function hKt(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return zv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var Wbe=N(U(),1);var Vet=N(U(),1),RY=globalThis?.document?Vet.useLayoutEffect:()=>{};var gKt=Wbe[" useId ".trim().toString()]||(()=>{}),yKt=0;function Wet(t){let[e,n]=Wbe.useState(gKt());return RY(()=>{t||n(r=>r??String(yKt++))},[t]),t||(e?`radix-${e}`:"")}var Ket=N(U(),1),_Kt=N(yo(),1);var aa=N(U(),1);var LY=N(Ve(),1);function Het(t){let e=wKt(t),n=aa.forwardRef((r,o)=>{let{children:i,...s}=r,a=aa.Children.toArray(i),l=a.find(xKt);if(l){let c=l.props.children,u=a.map(d=>d===l?aa.Children.count(c)>1?aa.Children.only(null):aa.isValidElement(c)?c.props.children:null:d);return(0,LY.jsx)(e,{...s,ref:o,children:aa.isValidElement(c)?aa.cloneElement(c,void 0,u):null})}return(0,LY.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function wKt(t){let e=aa.forwardRef((n,r)=>{let{children:o,...i}=n;if(aa.isValidElement(o)){let s=CKt(o),a=bKt(i,o.props);return o.type!==aa.Fragment&&(a.ref=r?Vbe(r,s):s),aa.cloneElement(o,a)}return aa.Children.count(o)>1?aa.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var vKt=Symbol("radix.slottable");function xKt(t){return aa.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===vKt}function bKt(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function CKt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var qet=N(Ve(),1),SKt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Hbe=SKt.reduce((t,e)=>{let n=Het(`Primitive.${e}`),r=Ket.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,qet.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var GR=N(U(),1);function Get(t){let e=GR.useRef(t);return GR.useEffect(()=>{e.current=t}),GR.useMemo(()=>(...n)=>e.current?.(...n),[])}var Wp=N(U(),1);var DY=N(U(),1);var TKt=Wp[" useInsertionEffect ".trim().toString()]||RY;function Yet({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=IKt({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=Wp.useRef(t!==void 0);Wp.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=Wp.useCallback(u=>{if(a){let d=PKt(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function IKt({defaultProp:t,onChange:e}){let[n,r]=Wp.useState(t),o=Wp.useRef(n),i=Wp.useRef(e);return TKt(()=>{i.current=e},[e]),Wp.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function PKt(t){return typeof t=="function"}var G0r=Symbol("RADIX:SYNC_STATE");var $Y=N(U(),1),EKt=N(Ve(),1),AKt=$Y.createContext(void 0);function Zet(t){let e=$Y.useContext(AKt);return t||e||"ltr"}var T_=N(Ve(),1),Kbe="rovingFocusGroup.onEntryFocus",kKt={bubbles:!1,cancelable:!0},$j="RovingFocusGroup",[qbe,Jet,MKt]=w_($j),[NKt,Gbe]=jet($j,[MKt]),[OKt,RKt]=NKt($j),Xet=qa.forwardRef((t,e)=>(0,T_.jsx)(qbe.Provider,{scope:t.__scopeRovingFocusGroup,children:(0,T_.jsx)(qbe.Slot,{scope:t.__scopeRovingFocusGroup,children:(0,T_.jsx)(LKt,{...t,ref:e})})}));Xet.displayName=$j;var LKt=qa.forwardRef((t,e)=>{let{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:a,onCurrentTabStopIdChange:l,onEntryFocus:c,preventScrollOnEntryFocus:u=!1,...d}=t,f=qa.useRef(null),p=Bet(e,f),m=Zet(i),[h,g]=Yet({prop:s,defaultProp:a??null,onChange:l,caller:$j}),[y,w]=qa.useState(!1),v=Get(c),x=Jet(n),b=qa.useRef(!1),[_,T]=qa.useState(0);return qa.useEffect(()=>{let S=f.current;if(S)return S.addEventListener(Kbe,v),()=>S.removeEventListener(Kbe,v)},[v]),(0,T_.jsx)(OKt,{scope:n,orientation:r,dir:m,loop:o,currentTabStopId:h,onItemFocus:qa.useCallback(S=>g(S),[g]),onItemShiftTab:qa.useCallback(()=>w(!0),[]),onFocusableItemAdd:qa.useCallback(()=>T(S=>S+1),[]),onFocusableItemRemove:qa.useCallback(()=>T(S=>S-1),[]),children:(0,T_.jsx)(Hbe.div,{tabIndex:y||_===0?-1:0,"data-orientation":r,...d,ref:p,style:{outline:"none",...t.style},onMouseDown:EP(t.onMouseDown,()=>{b.current=!0}),onFocus:EP(t.onFocus,S=>{let P=!b.current;if(S.target===S.currentTarget&&P&&!y){let A=new CustomEvent(Kbe,kKt);if(S.currentTarget.dispatchEvent(A),!A.defaultPrevented){let O=x().filter(F=>F.focusable),D=O.find(F=>F.active),$=O.find(F=>F.id===h),W=[D,$,...O].filter(Boolean).map(F=>F.ref.current);ttt(W,u)}}b.current=!1}),onBlur:EP(t.onBlur,()=>w(!1))})})}),Qet="RovingFocusGroupItem",ett=qa.forwardRef((t,e)=>{let{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,children:s,...a}=t,l=Wet(),c=i||l,u=RKt(Qet,n),d=u.currentTabStopId===c,f=Jet(n),{onFocusableItemAdd:p,onFocusableItemRemove:m,currentTabStopId:h}=u;return qa.useEffect(()=>{if(r)return p(),()=>m()},[r,p,m]),(0,T_.jsx)(qbe.ItemSlot,{scope:n,id:c,focusable:r,active:o,children:(0,T_.jsx)(Hbe.span,{tabIndex:d?0:-1,"data-orientation":u.orientation,...a,ref:e,onMouseDown:EP(t.onMouseDown,g=>{r?u.onItemFocus(c):g.preventDefault()}),onFocus:EP(t.onFocus,()=>u.onItemFocus(c)),onKeyDown:EP(t.onKeyDown,g=>{if(g.key==="Tab"&&g.shiftKey){u.onItemShiftTab();return}if(g.target!==g.currentTarget)return;let y=FKt(g,u.orientation,u.dir);if(y!==void 0){if(g.metaKey||g.ctrlKey||g.altKey||g.shiftKey)return;g.preventDefault();let v=f().filter(x=>x.focusable).map(x=>x.ref.current);if(y==="last")v.reverse();else if(y==="prev"||y==="next"){y==="prev"&&v.reverse();let x=v.indexOf(g.currentTarget);v=u.loop?UKt(v,x+1):v.slice(x+1)}setTimeout(()=>ttt(v))}}),children:typeof s=="function"?s({isCurrentTabStop:d,hasTabStop:h!=null}):s})})});ett.displayName=Qet;var DKt={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function $Kt(t,e){return e!=="rtl"?t:t==="ArrowLeft"?"ArrowRight":t==="ArrowRight"?"ArrowLeft":t}function FKt(t,e,n){let r=$Kt(t.key,n);if(!(e==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(e==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return DKt[r]}function ttt(t,e=!1){let n=document.activeElement;for(let r of t)if(r===n||(r.focus({preventScroll:e}),document.activeElement!==n))return}function UKt(t,e){return t.map((n,r)=>t[(e+r)%t.length])}var ntt=Xet,rtt=ett;var YR=N(U(),1);function FY(t){let e=YR.useRef(t);return YR.useEffect(()=>{e.current=t}),YR.useMemo(()=>(...n)=>e.current?.(...n),[])}var zKt=function(t){if(typeof document>"u")return null;var e=Array.isArray(t)?t[0]:t;return e.ownerDocument.body},ZR=new WeakMap,UY=new WeakMap,BY={},Ybe=0,ott=function(t){return t&&(t.host||ott(t.parentNode))},jKt=function(t,e){return e.map(function(n){if(t.contains(n))return n;var r=ott(n);return r&&t.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",t,". Doing nothing"),null)}).filter(function(n){return!!n})},VKt=function(t,e,n,r){var o=jKt(e,Array.isArray(t)?t:[t]);BY[n]||(BY[n]=new WeakMap);var i=BY[n],s=[],a=new Set,l=new Set(o),c=function(d){!d||a.has(d)||(a.add(d),c(d.parentNode))};o.forEach(c);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(f){if(a.has(f))u(f);else try{var p=f.getAttribute(r),m=p!==null&&p!=="false",h=(ZR.get(f)||0)+1,g=(i.get(f)||0)+1;ZR.set(f,h),i.set(f,g),s.push(f),h===1&&m&&UY.set(f,!0),g===1&&f.setAttribute(n,"true"),m||f.setAttribute(r,"true")}catch(y){console.error("aria-hidden: cannot operate on ",f,y)}})};return u(e),a.clear(),Ybe++,function(){s.forEach(function(d){var f=ZR.get(d)-1,p=i.get(d)-1;ZR.set(d,f),i.set(d,p),f||(UY.has(d)||d.removeAttribute(r),UY.delete(d)),p||d.removeAttribute(n)}),Ybe--,Ybe||(ZR=new WeakMap,ZR=new WeakMap,UY=new WeakMap,BY={})}},I_=function(t,e,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(t)?t:[t]),o=e||zKt(t);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),VKt(r,o,n,"aria-hidden")):function(){return null}};var id=function(){return id=Object.assign||function(e){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},id.apply(this,arguments)};function zY(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(t);o<r.length;o++)e.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(t,r[o])&&(n[r[o]]=t[r[o]]);return n}function itt(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}var KY=N(U());var gc=N(U());var AP="right-scroll-bar-position",kP="width-before-scroll-bar",Zbe="with-scroll-bars-hidden",Jbe="--removed-body-scroll-bar-size";function jY(t,e){return typeof t=="function"?t(e):t&&(t.current=e),t}var stt=N(U());function att(t,e){var n=(0,stt.useState)(function(){return{value:t,callback:e,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=e,n.facade}var VY=N(U());var WKt=typeof window<"u"?VY.useLayoutEffect:VY.useEffect,ltt=new WeakMap;function Xbe(t,e){var n=att(e||null,function(r){return t.forEach(function(o){return jY(o,r)})});return WKt(function(){var r=ltt.get(n);if(r){var o=new Set(r),i=new Set(t),s=n.current;o.forEach(function(a){i.has(a)||jY(a,null)}),i.forEach(function(a){o.has(a)||jY(a,s)})}ltt.set(n,t)},[t]),n}function HKt(t){return t}function KKt(t,e){e===void 0&&(e=HKt);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:t},useMedium:function(i){var s=e(i,r);return n.push(s),function(){n=n.filter(function(a){return a!==s})}},assignSyncMedium:function(i){for(r=!0;n.length;){var s=n;n=[],s.forEach(i)}n={push:function(a){return i(a)},filter:function(){return n}}},assignMedium:function(i){r=!0;var s=[];if(n.length){var a=n;n=[],a.forEach(i),s=n}var l=function(){var u=s;s=[],u.forEach(i)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(u){s.push(u),c()},filter:function(u){return s=s.filter(u),n}}}};return o}function Qbe(t){t===void 0&&(t={});var e=KKt(null);return e.options=id({async:!0,ssr:!1},t),e}var ctt=N(U()),utt=function(t){var e=t.sideCar,n=zY(t,["sideCar"]);if(!e)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=e.read();if(!r)throw new Error("Sidecar medium not found");return ctt.createElement(r,id({},n))};utt.isSideCarExport=!0;function eCe(t,e){return t.useMedium(e),utt}var WY=Qbe();var tCe=function(){},Fj=gc.forwardRef(function(t,e){var n=gc.useRef(null),r=gc.useState({onScrollCapture:tCe,onWheelCapture:tCe,onTouchMoveCapture:tCe}),o=r[0],i=r[1],s=t.forwardProps,a=t.children,l=t.className,c=t.removeScrollBar,u=t.enabled,d=t.shards,f=t.sideCar,p=t.noRelative,m=t.noIsolation,h=t.inert,g=t.allowPinchZoom,y=t.as,w=y===void 0?"div":y,v=t.gapMode,x=zY(t,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),b=f,_=Xbe([n,e]),T=id(id({},x),o);return gc.createElement(gc.Fragment,null,u&&gc.createElement(b,{sideCar:WY,removeScrollBar:c,shards:d,noRelative:p,noIsolation:m,inert:h,setCallbacks:i,allowPinchZoom:!!g,lockRef:n,gapMode:v}),s?gc.cloneElement(gc.Children.only(a),id(id({},T),{ref:_})):gc.createElement(w,id({},T,{className:l,ref:_}),a))});Fj.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1};Fj.classNames={fullWidth:kP,zeroRight:AP};var oi=N(U());var XR=N(U());var ptt=N(U());var dtt;var ftt=function(){if(dtt)return dtt;if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function qKt(){if(!document)return null;var t=document.createElement("style");t.type="text/css";var e=ftt();return e&&t.setAttribute("nonce",e),t}function GKt(t,e){t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}function YKt(t){var e=document.head||document.getElementsByTagName("head")[0];e.appendChild(t)}var nCe=function(){var t=0,e=null;return{add:function(n){t==0&&(e=qKt())&&(GKt(e,n),YKt(e)),t++},remove:function(){t--,!t&&e&&(e.parentNode&&e.parentNode.removeChild(e),e=null)}}};var rCe=function(){var t=nCe();return function(e,n){ptt.useEffect(function(){return t.add(e),function(){t.remove()}},[e&&n])}};var Uj=function(){var t=rCe(),e=function(n){var r=n.styles,o=n.dynamic;return t(r,o),null};return e};var ZKt={left:0,top:0,right:0,gap:0},oCe=function(t){return parseInt(t||"",10)||0},JKt=function(t){var e=window.getComputedStyle(document.body),n=e[t==="padding"?"paddingLeft":"marginLeft"],r=e[t==="padding"?"paddingTop":"marginTop"],o=e[t==="padding"?"paddingRight":"marginRight"];return[oCe(n),oCe(r),oCe(o)]},iCe=function(t){if(t===void 0&&(t="margin"),typeof window>"u")return ZKt;var e=JKt(t),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:e[0],top:e[1],right:e[2],gap:Math.max(0,r-n+e[2]-e[0])}};var XKt=Uj(),JR="data-scroll-locked",QKt=function(t,e,n,r){var o=t.left,i=t.top,s=t.right,a=t.gap;return n===void 0&&(n="margin"),`
  .`.concat(Zbe,` {
   overflow: hidden `).concat(r,`;
   padding-right: `).concat(a,"px ").concat(r,`;
  }
  body[`).concat(JR,`] {
    overflow: hidden `).concat(r,`;
    overscroll-behavior: contain;
    `).concat([e&&"position: relative ".concat(r,";"),n==="margin"&&`
    padding-left: `.concat(o,`px;
    padding-top: `).concat(i,`px;
    padding-right: `).concat(s,`px;
    margin-left:0;
    margin-top:0;
    margin-right: `).concat(a,"px ").concat(r,`;
    `),n==="padding"&&"padding-right: ".concat(a,"px ").concat(r,";")].filter(Boolean).join(""),`
  }
  
  .`).concat(AP,` {
    right: `).concat(a,"px ").concat(r,`;
  }
  
  .`).concat(kP,` {
    margin-right: `).concat(a,"px ").concat(r,`;
  }
  
  .`).concat(AP," .").concat(AP,` {
    right: 0 `).concat(r,`;
  }
  
  .`).concat(kP," .").concat(kP,` {
    margin-right: 0 `).concat(r,`;
  }
  
  body[`).concat(JR,`] {
    `).concat(Jbe,": ").concat(a,`px;
  }
`)},mtt=function(){var t=parseInt(document.body.getAttribute(JR)||"0",10);return isFinite(t)?t:0},e5t=function(){XR.useEffect(function(){return document.body.setAttribute(JR,(mtt()+1).toString()),function(){var t=mtt()-1;t<=0?document.body.removeAttribute(JR):document.body.setAttribute(JR,t.toString())}},[])},sCe=function(t){var e=t.noRelative,n=t.noImportant,r=t.gapMode,o=r===void 0?"margin":r;e5t();var i=XR.useMemo(function(){return iCe(o)},[o]);return XR.createElement(XKt,{styles:QKt(i,!e,o,n?"":"!important")})};var aCe=!1;if(typeof window<"u")try{Bj=Object.defineProperty({},"passive",{get:function(){return aCe=!0,!0}}),window.addEventListener("test",Bj,Bj),window.removeEventListener("test",Bj,Bj)}catch{aCe=!1}var Bj,MP=aCe?{passive:!1}:!1;var t5t=function(t){return t.tagName==="TEXTAREA"},htt=function(t,e){if(!(t instanceof Element))return!1;var n=window.getComputedStyle(t);return n[e]!=="hidden"&&!(n.overflowY===n.overflowX&&!t5t(t)&&n[e]==="visible")},n5t=function(t){return htt(t,"overflowY")},r5t=function(t){return htt(t,"overflowX")},lCe=function(t,e){var n=e.ownerDocument,r=e;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var o=gtt(t,r);if(o){var i=ytt(t,r),s=i[1],a=i[2];if(s>a)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},o5t=function(t){var e=t.scrollTop,n=t.scrollHeight,r=t.clientHeight;return[e,n,r]},i5t=function(t){var e=t.scrollLeft,n=t.scrollWidth,r=t.clientWidth;return[e,n,r]},gtt=function(t,e){return t==="v"?n5t(e):r5t(e)},ytt=function(t,e){return t==="v"?o5t(e):i5t(e)},s5t=function(t,e){return t==="h"&&e==="rtl"?-1:1},wtt=function(t,e,n,r,o){var i=s5t(t,window.getComputedStyle(e).direction),s=i*r,a=n.target,l=e.contains(a),c=!1,u=s>0,d=0,f=0;do{if(!a)break;var p=ytt(t,a),m=p[0],h=p[1],g=p[2],y=h-g-i*m;(m||y)&&gtt(t,a)&&(d+=y,f+=m);var w=a.parentNode;a=w&&w.nodeType===Node.DOCUMENT_FRAGMENT_NODE?w.host:w}while(!l&&a!==document.body||l&&(e.contains(a)||e===a));return(u&&(o&&Math.abs(d)<1||!o&&s>d)||!u&&(o&&Math.abs(f)<1||!o&&-s>f))&&(c=!0),c};var HY=function(t){return"changedTouches"in t?[t.changedTouches[0].clientX,t.changedTouches[0].clientY]:[0,0]},vtt=function(t){return[t.deltaX,t.deltaY]},xtt=function(t){return t&&"current"in t?t.current:t},a5t=function(t,e){return t[0]===e[0]&&t[1]===e[1]},l5t=function(t){return`
  .block-interactivity-`.concat(t,` {pointer-events: none;}
  .allow-interactivity-`).concat(t,` {pointer-events: all;}
`)},c5t=0,QR=[];function btt(t){var e=oi.useRef([]),n=oi.useRef([0,0]),r=oi.useRef(),o=oi.useState(c5t++)[0],i=oi.useState(Uj)[0],s=oi.useRef(t);oi.useEffect(function(){s.current=t},[t]),oi.useEffect(function(){if(t.inert){document.body.classList.add("block-interactivity-".concat(o));var h=itt([t.lockRef.current],(t.shards||[]).map(xtt),!0).filter(Boolean);return h.forEach(function(g){return g.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),h.forEach(function(g){return g.classList.remove("allow-interactivity-".concat(o))})}}},[t.inert,t.lockRef.current,t.shards]);var a=oi.useCallback(function(h,g){if("touches"in h&&h.touches.length===2||h.type==="wheel"&&h.ctrlKey)return!s.current.allowPinchZoom;var y=HY(h),w=n.current,v="deltaX"in h?h.deltaX:w[0]-y[0],x="deltaY"in h?h.deltaY:w[1]-y[1],b,_=h.target,T=Math.abs(v)>Math.abs(x)?"h":"v";if("touches"in h&&T==="h"&&_.type==="range")return!1;var S=lCe(T,_);if(!S)return!0;if(S?b=T:(b=T==="v"?"h":"v",S=lCe(T,_)),!S)return!1;if(!r.current&&"changedTouches"in h&&(v||x)&&(r.current=b),!b)return!0;var P=r.current||b;return wtt(P,g,h,P==="h"?v:x,!0)},[]),l=oi.useCallback(function(h){var g=h;if(!(!QR.length||QR[QR.length-1]!==i)){var y="deltaY"in g?vtt(g):HY(g),w=e.current.filter(function(b){return b.name===g.type&&(b.target===g.target||g.target===b.shadowParent)&&a5t(b.delta,y)})[0];if(w&&w.should){g.cancelable&&g.preventDefault();return}if(!w){var v=(s.current.shards||[]).map(xtt).filter(Boolean).filter(function(b){return b.contains(g.target)}),x=v.length>0?a(g,v[0]):!s.current.noIsolation;x&&g.cancelable&&g.preventDefault()}}},[]),c=oi.useCallback(function(h,g,y,w){var v={name:h,delta:g,target:y,should:w,shadowParent:u5t(y)};e.current.push(v),setTimeout(function(){e.current=e.current.filter(function(x){return x!==v})},1)},[]),u=oi.useCallback(function(h){n.current=HY(h),r.current=void 0},[]),d=oi.useCallback(function(h){c(h.type,vtt(h),h.target,a(h,t.lockRef.current))},[]),f=oi.useCallback(function(h){c(h.type,HY(h),h.target,a(h,t.lockRef.current))},[]);oi.useEffect(function(){return QR.push(i),t.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener("wheel",l,MP),document.addEventListener("touchmove",l,MP),document.addEventListener("touchstart",u,MP),function(){QR=QR.filter(function(h){return h!==i}),document.removeEventListener("wheel",l,MP),document.removeEventListener("touchmove",l,MP),document.removeEventListener("touchstart",u,MP)}},[]);var p=t.removeScrollBar,m=t.inert;return oi.createElement(oi.Fragment,null,m?oi.createElement(i,{styles:l5t(o)}):null,p?oi.createElement(sCe,{noRelative:t.noRelative,gapMode:t.gapMode}):null)}function u5t(t){for(var e=null;t!==null;)t instanceof ShadowRoot&&(e=t.host,t=t.host),t=t.parentNode;return e}var Ctt=eCe(WY,btt);var _tt=KY.forwardRef(function(t,e){return KY.createElement(Fj,id({},t,{ref:e,sideCar:Ctt}))});_tt.classNames=Fj.classNames;var jv=_tt;var Vn=N(Ve(),1),cCe=["Enter"," "],d5t=["ArrowDown","PageUp","Home"],Ttt=["ArrowUp","PageDown","End"],f5t=[...d5t,...Ttt],p5t={ltr:[...cCe,"ArrowRight"],rtl:[...cCe,"ArrowLeft"]},m5t={ltr:["ArrowLeft"],rtl:["ArrowRight"]},Wj="Menu",[jj,h5t,g5t]=w_(Wj),[NP,uCe]=yXe(Wj,[g5t,Vp,Gbe]),Hj=Vp(),Itt=Gbe(),[Ptt,P_]=NP(Wj),[y5t,Kj]=NP(Wj),Ett=t=>{let{__scopeMenu:e,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=t,a=Hj(e),[l,c]=Gt.useState(null),u=Gt.useRef(!1),d=FY(i),f=wXe(o);return Gt.useEffect(()=>{let p=()=>{u.current=!0,document.addEventListener("pointerdown",m,{capture:!0,once:!0}),document.addEventListener("pointermove",m,{capture:!0,once:!0})},m=()=>u.current=!1;return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",m,{capture:!0}),document.removeEventListener("pointermove",m,{capture:!0})}},[]),(0,Vn.jsx)(Uv,{...a,children:(0,Vn.jsx)(Ptt,{scope:e,open:n,onOpenChange:d,content:l,onContentChange:c,children:(0,Vn.jsx)(y5t,{scope:e,onClose:Gt.useCallback(()=>d(!1),[d]),isUsingKeyboardRef:u,dir:f,modal:s,children:r})})})};Ett.displayName=Wj;var w5t="MenuAnchor",dCe=Gt.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t,o=Hj(n);return(0,Vn.jsx)(Bv,{...o,...r,ref:e})});dCe.displayName=w5t;var fCe="MenuPortal",[v5t,Att]=NP(fCe,{forceMount:void 0}),ktt=t=>{let{__scopeMenu:e,forceMount:n,children:r,container:o}=t,i=P_(fCe,e);return(0,Vn.jsx)(v5t,{scope:e,forceMount:n,children:(0,Vn.jsx)(KR,{present:n||i.open,children:(0,Vn.jsx)(vh,{asChild:!0,container:o,children:r})})})};ktt.displayName=fCe;var Hp="MenuContent",[x5t,pCe]=NP(Hp),Mtt=Gt.forwardRef((t,e)=>{let n=Att(Hp,t.__scopeMenu),{forceMount:r=n.forceMount,...o}=t,i=P_(Hp,t.__scopeMenu),s=Kj(Hp,t.__scopeMenu);return(0,Vn.jsx)(jj.Provider,{scope:t.__scopeMenu,children:(0,Vn.jsx)(KR,{present:r||i.open,children:(0,Vn.jsx)(jj.Slot,{scope:t.__scopeMenu,children:s.modal?(0,Vn.jsx)(b5t,{...o,ref:e}):(0,Vn.jsx)(C5t,{...o,ref:e})})})})}),b5t=Gt.forwardRef((t,e)=>{let n=P_(Hp,t.__scopeMenu),r=Gt.useRef(null),o=v_(e,r);return Gt.useEffect(()=>{let i=r.current;if(i)return I_(i)},[]),(0,Vn.jsx)(mCe,{...t,ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:qi(t.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),C5t=Gt.forwardRef((t,e)=>{let n=P_(Hp,t.__scopeMenu);return(0,Vn.jsx)(mCe,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),_5t=OY("MenuContent.ScrollLock"),mCe=Gt.forwardRef((t,e)=>{let{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:a,onEntryFocus:l,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,disableOutsideScroll:m,...h}=t,g=P_(Hp,n),y=Kj(Hp,n),w=Hj(n),v=Itt(n),x=h5t(n),[b,_]=Gt.useState(null),T=Gt.useRef(null),S=v_(e,T,g.onContentChange),P=Gt.useRef(0),A=Gt.useRef(""),O=Gt.useRef(0),D=Gt.useRef(null),$=Gt.useRef("right"),B=Gt.useRef(0),W=m?jv:Gt.Fragment,F=m?{as:_5t,allowPinchZoom:!0}:void 0,Z=H=>{let te=A.current+H,fe=x().filter(E=>!E.disabled),me=document.activeElement,j=fe.find(E=>E.ref.current===me)?.textValue,G=fe.map(E=>E.textValue),J=D5t(G,te,j),M=fe.find(E=>E.textValue===J)?.ref.current;(function E(R){A.current=R,window.clearTimeout(P.current),R!==""&&(P.current=window.setTimeout(()=>E(""),1e3))})(te),M&&setTimeout(()=>M.focus())};Gt.useEffect(()=>()=>window.clearTimeout(P.current),[]),x_();let V=Gt.useCallback(H=>$.current===D.current?.side&&F5t(H,D.current?.area),[]);return(0,Vn.jsx)(x5t,{scope:n,searchRef:A,onItemEnter:Gt.useCallback(H=>{V(H)&&H.preventDefault()},[V]),onItemLeave:Gt.useCallback(H=>{V(H)||(T.current?.focus(),_(null))},[V]),onTriggerLeave:Gt.useCallback(H=>{V(H)&&H.preventDefault()},[V]),pointerGraceTimerRef:O,onPointerGraceIntentChange:Gt.useCallback(H=>{D.current=H},[]),children:(0,Vn.jsx)(W,{...F,children:(0,Vn.jsx)(Dv,{asChild:!0,trapped:o,onMountAutoFocus:qi(i,H=>{H.preventDefault(),T.current?.focus({preventScroll:!0})}),onUnmountAutoFocus:s,children:(0,Vn.jsx)(mh,{asChild:!0,disableOutsidePointerEvents:a,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,onDismiss:p,children:(0,Vn.jsx)(ntt,{asChild:!0,...v,dir:y.dir,orientation:"vertical",loop:r,currentTabStopId:b,onCurrentTabStopIdChange:_,onEntryFocus:qi(l,H=>{y.isUsingKeyboardRef.current||H.preventDefault()}),preventScrollOnEntryFocus:!0,children:(0,Vn.jsx)(__,{role:"menu","aria-orientation":"vertical","data-state":qtt(g.open),"data-radix-menu-content":"",dir:y.dir,...w,...h,ref:S,style:{outline:"none",...h.style},onKeyDown:qi(h.onKeyDown,H=>{let fe=H.target.closest("[data-radix-menu-content]")===H.currentTarget,me=H.ctrlKey||H.altKey||H.metaKey,j=H.key.length===1;fe&&(H.key==="Tab"&&H.preventDefault(),!me&&j&&Z(H.key));let G=T.current;if(H.target!==G||!f5t.includes(H.key))return;H.preventDefault();let M=x().filter(E=>!E.disabled).map(E=>E.ref.current);Ttt.includes(H.key)&&M.reverse(),R5t(M)}),onBlur:qi(t.onBlur,H=>{H.currentTarget.contains(H.target)||(window.clearTimeout(P.current),A.current="")}),onPointerMove:qi(t.onPointerMove,Vj(H=>{let te=H.target,fe=B.current!==H.clientX;if(H.currentTarget.contains(te)&&fe){let me=H.clientX>B.current?"right":"left";$.current=me,B.current=H.clientX}}))})})})})})})});Mtt.displayName=Hp;var S5t="MenuGroup",hCe=Gt.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t;return(0,Vn.jsx)(qR.div,{role:"group",...r,ref:e})});hCe.displayName=S5t;var T5t="MenuLabel",Ntt=Gt.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t;return(0,Vn.jsx)(qR.div,{...r,ref:e})});Ntt.displayName=T5t;var qY="MenuItem",Stt="menu.itemSelect",YY=Gt.forwardRef((t,e)=>{let{disabled:n=!1,onSelect:r,...o}=t,i=Gt.useRef(null),s=Kj(qY,t.__scopeMenu),a=pCe(qY,t.__scopeMenu),l=v_(e,i),c=Gt.useRef(!1),u=()=>{let d=i.current;if(!n&&d){let f=new CustomEvent(Stt,{bubbles:!0,cancelable:!0});d.addEventListener(Stt,p=>r?.(p),{once:!0}),$et(d,f),f.defaultPrevented?c.current=!1:s.onClose()}};return(0,Vn.jsx)(Ott,{...o,ref:l,disabled:n,onClick:qi(t.onClick,u),onPointerDown:d=>{t.onPointerDown?.(d),c.current=!0},onPointerUp:qi(t.onPointerUp,d=>{c.current||d.currentTarget?.click()}),onKeyDown:qi(t.onKeyDown,d=>{let f=a.searchRef.current!=="";n||f&&d.key===" "||cCe.includes(d.key)&&(d.currentTarget.click(),d.preventDefault())})})});YY.displayName=qY;var Ott=Gt.forwardRef((t,e)=>{let{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=t,s=pCe(qY,n),a=Itt(n),l=Gt.useRef(null),c=v_(e,l),[u,d]=Gt.useState(!1),[f,p]=Gt.useState("");return Gt.useEffect(()=>{let m=l.current;m&&p((m.textContent??"").trim())},[i.children]),(0,Vn.jsx)(jj.ItemSlot,{scope:n,disabled:r,textValue:o??f,children:(0,Vn.jsx)(rtt,{asChild:!0,...a,focusable:!r,children:(0,Vn.jsx)(qR.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:c,onPointerMove:qi(t.onPointerMove,Vj(m=>{r?s.onItemLeave(m):(s.onItemEnter(m),m.defaultPrevented||m.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:qi(t.onPointerLeave,Vj(m=>s.onItemLeave(m))),onFocus:qi(t.onFocus,()=>d(!0)),onBlur:qi(t.onBlur,()=>d(!1))})})})}),I5t="MenuCheckboxItem",Rtt=Gt.forwardRef((t,e)=>{let{checked:n=!1,onCheckedChange:r,...o}=t;return(0,Vn.jsx)(Utt,{scope:t.__scopeMenu,checked:n,children:(0,Vn.jsx)(YY,{role:"menuitemcheckbox","aria-checked":GY(n)?"mixed":n,...o,ref:e,"data-state":wCe(n),onSelect:qi(o.onSelect,()=>r?.(GY(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Rtt.displayName=I5t;var Ltt="MenuRadioGroup",[P5t,E5t]=NP(Ltt,{value:void 0,onValueChange:()=>{}}),Dtt=Gt.forwardRef((t,e)=>{let{value:n,onValueChange:r,...o}=t,i=FY(r);return(0,Vn.jsx)(P5t,{scope:t.__scopeMenu,value:n,onValueChange:i,children:(0,Vn.jsx)(hCe,{...o,ref:e})})});Dtt.displayName=Ltt;var $tt="MenuRadioItem",Ftt=Gt.forwardRef((t,e)=>{let{value:n,...r}=t,o=E5t($tt,t.__scopeMenu),i=n===o.value;return(0,Vn.jsx)(Utt,{scope:t.__scopeMenu,checked:i,children:(0,Vn.jsx)(YY,{role:"menuitemradio","aria-checked":i,...r,ref:e,"data-state":wCe(i),onSelect:qi(r.onSelect,()=>o.onValueChange?.(n),{checkForDefaultPrevented:!1})})})});Ftt.displayName=$tt;var gCe="MenuItemIndicator",[Utt,A5t]=NP(gCe,{checked:!1}),Btt=Gt.forwardRef((t,e)=>{let{__scopeMenu:n,forceMount:r,...o}=t,i=A5t(gCe,n);return(0,Vn.jsx)(KR,{present:r||GY(i.checked)||i.checked===!0,children:(0,Vn.jsx)(qR.span,{...o,ref:e,"data-state":wCe(i.checked)})})});Btt.displayName=gCe;var k5t="MenuSeparator",ztt=Gt.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t;return(0,Vn.jsx)(qR.div,{role:"separator","aria-orientation":"horizontal",...r,ref:e})});ztt.displayName=k5t;var M5t="MenuArrow",jtt=Gt.forwardRef((t,e)=>{let{__scopeMenu:n,...r}=t,o=Hj(n);return(0,Vn.jsx)(S_,{...o,...r,ref:e})});jtt.displayName=M5t;var yCe="MenuSub",[N5t,Vtt]=NP(yCe),O5t=t=>{let{__scopeMenu:e,children:n,open:r=!1,onOpenChange:o}=t,i=P_(yCe,e),s=Hj(e),[a,l]=Gt.useState(null),[c,u]=Gt.useState(null),d=FY(o);return Gt.useEffect(()=>(i.open===!1&&d(!1),()=>d(!1)),[i.open,d]),(0,Vn.jsx)(Uv,{...s,children:(0,Vn.jsx)(Ptt,{scope:e,open:r,onOpenChange:d,content:c,onContentChange:u,children:(0,Vn.jsx)(N5t,{scope:e,contentId:Abe(),triggerId:Abe(),trigger:a,onTriggerChange:l,children:n})})})};O5t.displayName=yCe;var zj="MenuSubTrigger",Wtt=Gt.forwardRef((t,e)=>{let n=P_(zj,t.__scopeMenu),r=Kj(zj,t.__scopeMenu),o=Vtt(zj,t.__scopeMenu),i=pCe(zj,t.__scopeMenu),s=Gt.useRef(null),{pointerGraceTimerRef:a,onPointerGraceIntentChange:l}=i,c={__scopeMenu:t.__scopeMenu},u=Gt.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return Gt.useEffect(()=>u,[u]),Gt.useEffect(()=>{let d=a.current;return()=>{window.clearTimeout(d),l(null)}},[a,l]),(0,Vn.jsx)(dCe,{asChild:!0,...c,children:(0,Vn.jsx)(Ott,{id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":qtt(n.open),...t,ref:Aj(e,o.onTriggerChange),onClick:d=>{t.onClick?.(d),!(t.disabled||d.defaultPrevented)&&(d.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:qi(t.onPointerMove,Vj(d=>{i.onItemEnter(d),!d.defaultPrevented&&!t.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:qi(t.onPointerLeave,Vj(d=>{u();let f=n.content?.getBoundingClientRect();if(f){let p=n.content?.dataset.side,m=p==="right",h=m?-5:5,g=f[m?"left":"right"],y=f[m?"right":"left"];i.onPointerGraceIntentChange({area:[{x:d.clientX+h,y:d.clientY},{x:g,y:f.top},{x:y,y:f.top},{x:y,y:f.bottom},{x:g,y:f.bottom}],side:p}),window.clearTimeout(a.current),a.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(d),d.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:qi(t.onKeyDown,d=>{let f=i.searchRef.current!=="";t.disabled||f&&d.key===" "||p5t[r.dir].includes(d.key)&&(n.onOpenChange(!0),n.content?.focus(),d.preventDefault())})})})});Wtt.displayName=zj;var Htt="MenuSubContent",Ktt=Gt.forwardRef((t,e)=>{let n=Att(Hp,t.__scopeMenu),{forceMount:r=n.forceMount,...o}=t,i=P_(Hp,t.__scopeMenu),s=Kj(Hp,t.__scopeMenu),a=Vtt(Htt,t.__scopeMenu),l=Gt.useRef(null),c=v_(e,l);return(0,Vn.jsx)(jj.Provider,{scope:t.__scopeMenu,children:(0,Vn.jsx)(KR,{present:r||i.open,children:(0,Vn.jsx)(jj.Slot,{scope:t.__scopeMenu,children:(0,Vn.jsx)(mCe,{id:a.contentId,"aria-labelledby":a.triggerId,...o,ref:c,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{s.isUsingKeyboardRef.current&&l.current?.focus(),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:qi(t.onFocusOutside,u=>{u.target!==a.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:qi(t.onEscapeKeyDown,u=>{s.onClose(),u.preventDefault()}),onKeyDown:qi(t.onKeyDown,u=>{let d=u.currentTarget.contains(u.target),f=m5t[s.dir].includes(u.key);d&&f&&(i.onOpenChange(!1),a.trigger?.focus(),u.preventDefault())})})})})})});Ktt.displayName=Htt;function qtt(t){return t?"open":"closed"}function GY(t){return t==="indeterminate"}function wCe(t){return GY(t)?"indeterminate":t?"checked":"unchecked"}function R5t(t){let e=document.activeElement;for(let n of t)if(n===e||(n.focus(),document.activeElement!==e))return}function L5t(t,e){return t.map((n,r)=>t[(e+r)%t.length])}function D5t(t,e,n){let o=e.length>1&&Array.from(e).every(c=>c===e[0])?e[0]:e,i=n?t.indexOf(n):-1,s=L5t(t,Math.max(i,0));o.length===1&&(s=s.filter(c=>c!==n));let l=s.find(c=>c.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function $5t(t,e){let{x:n,y:r}=t,o=!1;for(let i=0,s=e.length-1;i<e.length;s=i++){let a=e[i],l=e[s],c=a.x,u=a.y,d=l.x,f=l.y;u>r!=f>r&&n<(d-c)*(r-u)/(f-u)+c&&(o=!o)}return o}function F5t(t,e){if(!e)return!1;let n={x:t.clientX,y:t.clientY};return $5t(n,e)}function Vj(t){return e=>e.pointerType==="mouse"?t(e):void 0}var Gtt=Ett,Ytt=dCe,Ztt=ktt,Jtt=Mtt,Xtt=hCe,Qtt=Ntt,ent=YY,tnt=Rtt,nnt=Dtt,rnt=Ftt,ont=Btt,int=ztt,snt=jtt;var ant=Wtt,lnt=Ktt;var vCe=N(U(),1);var B5t=vCe[" useId ".trim().toString()]||(()=>{}),z5t=0;function xCe(t){let[e,n]=vCe.useState(B5t());return iY(()=>{t||n(r=>r??String(z5t++))},[t]),t||(e?`radix-${e}`:"")}var Ga=N(Ve(),1),ZY="DropdownMenu",[j5t,WEr]=rXe(ZY,[uCe]),lu=uCe(),[V5t,cnt]=j5t(ZY),qj=t=>{let{__scopeDropdownMenu:e,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:a=!0}=t,l=lu(e),c=la.useRef(null),[u,d]=iXe({prop:o,defaultProp:i??!1,onChange:s,caller:ZY});return(0,Ga.jsx)(V5t,{scope:e,triggerId:xCe(),triggerRef:c,contentId:xCe(),open:u,onOpenChange:d,onOpenToggle:la.useCallback(()=>d(f=>!f),[d]),modal:a,children:(0,Ga.jsx)(Gtt,{...l,open:u,onOpenChange:d,dir:r,modal:a,children:n})})};qj.displayName=ZY;var unt="DropdownMenuTrigger",Gj=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,disabled:r=!1,...o}=t,i=cnt(unt,n),s=lu(n);return(0,Ga.jsx)(Ytt,{asChild:!0,...s,children:(0,Ga.jsx)(cXe.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...o,ref:oY(e,i.triggerRef),onPointerDown:Ej(t.onPointerDown,a=>{!r&&a.button===0&&a.ctrlKey===!1&&(i.onOpenToggle(),i.open||a.preventDefault())}),onKeyDown:Ej(t.onKeyDown,a=>{r||(["Enter"," "].includes(a.key)&&i.onOpenToggle(),a.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(a.key)&&a.preventDefault())})})})});Gj.displayName=unt;var W5t="DropdownMenuPortal",dnt=t=>{let{__scopeDropdownMenu:e,...n}=t,r=lu(e);return(0,Ga.jsx)(Ztt,{...r,...n})};dnt.displayName=W5t;var fnt="DropdownMenuContent",pnt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=cnt(fnt,n),i=lu(n),s=la.useRef(!1);return(0,Ga.jsx)(Jtt,{id:o.contentId,"aria-labelledby":o.triggerId,...i,...r,ref:e,onCloseAutoFocus:Ej(t.onCloseAutoFocus,a=>{s.current||o.triggerRef.current?.focus(),s.current=!1,a.preventDefault()}),onInteractOutside:Ej(t.onInteractOutside,a=>{let l=a.detail.originalEvent,c=l.button===0&&l.ctrlKey===!0,u=l.button===2||c;(!o.modal||u)&&(s.current=!0)}),style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});pnt.displayName=fnt;var H5t="DropdownMenuGroup",K5t=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(Xtt,{...o,...r,ref:e})});K5t.displayName=H5t;var q5t="DropdownMenuLabel",mnt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(Qtt,{...o,...r,ref:e})});mnt.displayName=q5t;var G5t="DropdownMenuItem",hnt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(ent,{...o,...r,ref:e})});hnt.displayName=G5t;var Y5t="DropdownMenuCheckboxItem",gnt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(tnt,{...o,...r,ref:e})});gnt.displayName=Y5t;var Z5t="DropdownMenuRadioGroup",J5t=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(nnt,{...o,...r,ref:e})});J5t.displayName=Z5t;var X5t="DropdownMenuRadioItem",ynt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(rnt,{...o,...r,ref:e})});ynt.displayName=X5t;var Q5t="DropdownMenuItemIndicator",wnt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(ont,{...o,...r,ref:e})});wnt.displayName=Q5t;var eqt="DropdownMenuSeparator",vnt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(int,{...o,...r,ref:e})});vnt.displayName=eqt;var tqt="DropdownMenuArrow",nqt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(snt,{...o,...r,ref:e})});nqt.displayName=tqt;var rqt="DropdownMenuSubTrigger",xnt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(ant,{...o,...r,ref:e})});xnt.displayName=rqt;var oqt="DropdownMenuSubContent",bnt=la.forwardRef((t,e)=>{let{__scopeDropdownMenu:n,...r}=t,o=lu(n);return(0,Ga.jsx)(lnt,{...o,...r,ref:e,style:{...t.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});bnt.displayName=oqt;var Cnt=qj,_nt=Gj,Snt=dnt,bCe=pnt;var CCe=mnt,_Ce=hnt,SCe=gnt;var TCe=ynt,ICe=wnt,PCe=vnt;var ECe=xnt,ACe=bnt;vt();var Tnt=require("obsidian");Kt();var xy=Cnt,by=_nt;var sqt=Io.forwardRef(({className:t,inset:e,children:n,...r},o)=>Io.createElement(ECe,{ref:o,className:oe("tw-flex tw-cursor-default tw-select-none tw-items-center tw-gap-2 tw-rounded-sm tw-px-2 tw-py-1.5 tw-text-sm tw-outline-none focus:tw-bg-modifier-hover data-[state=open]:tw-bg-modifier-hover [&_svg]:tw-pointer-events-none [&_svg]:tw-size-4 [&_svg]:tw-shrink-0",e&&"tw-pl-8",t),...r},n,Io.createElement(Di,{className:"tw-ml-auto"})));sqt.displayName=ECe.displayName;var aqt=Io.forwardRef(({className:t,...e},n)=>Io.createElement(ACe,{ref:n,className:oe("tw-z-[50] tw-min-w-32 tw-overflow-hidden tw-rounded-md tw-border tw-bg-primary tw-p-1 tw-text-normal tw-shadow-lg data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[side=bottom]:tw-slide-in-from-top-2 data-[side=left]:tw-slide-in-from-right-2 data-[side=right]:tw-slide-in-from-left-2 data-[side=top]:tw-slide-in-from-bottom-2",t),...e}));aqt.displayName=ACe.displayName;var sd=Io.forwardRef(({className:t,sideOffset:e=4,container:n,...r},o)=>Io.createElement(Snt,{container:n??activeDocument.body},Io.createElement(bCe,{ref:o,sideOffset:e,hideWhenDetached:Tnt.Platform.isMobile,className:oe("tw-z-[50] tw-min-w-32 tw-overflow-hidden tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-1 tw-text-normal tw-shadow-md","data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[side=bottom]:tw-slide-in-from-top-2 data-[side=left]:tw-slide-in-from-right-2 data-[side=right]:tw-slide-in-from-left-2 data-[side=top]:tw-slide-in-from-bottom-2",t),...r})));sd.displayName=bCe.displayName;var wr=Io.forwardRef(({className:t,inset:e,...n},r)=>Io.createElement(_Ce,{ref:r,className:oe("tw-relative tw-flex tw-cursor-default tw-select-none tw-items-center tw-gap-2 tw-rounded-sm tw-px-2 tw-py-1.5 tw-text-sm tw-outline-none tw-transition-colors focus:tw-bg-modifier-hover focus:tw-text-normal data-[disabled]:tw-pointer-events-none data-[disabled]:tw-opacity-50 [&>svg]:tw-size-4 [&>svg]:tw-shrink-0",e&&"tw-pl-8",t),...n}));wr.displayName=_Ce.displayName;var lqt=Io.forwardRef(({className:t,children:e,checked:n,...r},o)=>Io.createElement(SCe,{ref:o,className:oe("tw-relative tw-flex tw-cursor-default tw-select-none tw-items-center tw-rounded-sm tw-py-1.5 tw-pl-8 tw-pr-2 tw-text-sm tw-outline-none tw-transition-colors focus:tw-bg-modifier-hover focus:tw-text-normal data-[disabled]:tw-pointer-events-none data-[disabled]:tw-opacity-50",t),checked:n,...r},Io.createElement("span",{className:"tw-absolute tw-left-2 tw-flex tw-size-3.5 tw-items-center tw-justify-center"},Io.createElement(ICe,null,Io.createElement(Ro,{className:"tw-size-4"}))),e));lqt.displayName=SCe.displayName;var cqt=Io.forwardRef(({className:t,children:e,...n},r)=>Io.createElement(TCe,{ref:r,className:oe("tw-relative tw-flex tw-cursor-default tw-select-none tw-items-center tw-rounded-sm tw-py-1.5 tw-pl-8 tw-pr-2 tw-text-sm tw-outline-none tw-transition-colors focus:tw-bg-modifier-hover focus:tw-text-normal data-[disabled]:tw-pointer-events-none data-[disabled]:tw-opacity-50",t),...n},Io.createElement("span",{className:"tw-absolute tw-left-2 tw-flex tw-size-3.5 tw-items-center tw-justify-center"},Io.createElement(ICe,null,Io.createElement(u$,{className:"tw-size-2 tw-fill-current"}))),e));cqt.displayName=TCe.displayName;var uqt=Io.forwardRef(({className:t,inset:e,...n},r)=>Io.createElement(CCe,{ref:r,className:oe("tw-px-2 tw-py-1.5 tw-text-sm tw-font-semibold",e&&"tw-pl-8",t),...n}));uqt.displayName=CCe.displayName;var dqt=Io.forwardRef(({className:t,...e},n)=>Io.createElement(PCe,{ref:n,className:oe("-tw-mx-1 tw-my-1 tw-h-px",t),...e}));dqt.displayName=PCe.displayName;var fqt=({className:t,...e})=>Io.createElement("span",{className:oe("tw-ml-auto tw-text-xs tw-tracking-widest tw-opacity-60",t),...e});fqt.displayName="DropdownMenuShortcut";Se();qe();vt();Kt();function eL({disabled:t=!1,size:e="fit",variant:n="ghost2",className:r,value:o,onChange:i}){let[s,a]=(0,cu.useState)(null),l=Ht(),c=l.activeModels.find(d=>d.enabled&&ln(d)===o),u=l.activeModels;return cu.default.createElement(xy,null,cu.default.createElement(by,{asChild:!0},cu.default.createElement(X,{variant:n,size:e,disabled:t,className:oe("tw-min-w-0 tw-justify-start tw-text-muted",r)},cu.default.createElement("div",{className:"tw-min-w-0 tw-flex-1 tw-truncate"},s?cu.default.createElement("span",{className:"tw-truncate tw-text-error"},"Model Load Failed"):c?cu.default.createElement(lbe,{model:c,iconSize:8}):cu.default.createElement("span",{className:"tw-truncate"},"Select Model")),!t&&cu.default.createElement(hr,{className:"tw-mt-0.5 tw-size-5 tw-shrink-0"}))),cu.default.createElement(sd,{align:"start",className:"tw-max-h-64 tw-overflow-y-auto"},u.filter(d=>d.enabled).map(d=>{let{hasApiKey:f}=kA(d,l);return cu.default.createElement(wr,{key:ln(d),disabled:!f,onSelect:async p=>{if(!f){p.preventDefault();return}try{a(null),i(ln(d))}catch(m){let h="Model switch failed: "+Xt(m);a(h);let g=u.find(y=>y.enabled&&ln(y)===o);g&&i(ln(g))}},className:f?"":"tw-cursor-not-allowed tw-opacity-50"},cu.default.createElement(lbe,{model:d,iconSize:12}),!f&&cu.default.createElement("span",{className:"tw-ml-auto tw-text-smallest tw-text-faint"},"Needs API key"))})))}rn();var Xj=N(U());var Qn=N(U(),1);var iAr=!!(typeof window<"u"&&window.document&&window.document.createElement);function OP(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var Pnt=N(U(),1);function Int(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function kCe(...t){return e=>{let n=!1,r=t.map(o=>{let i=Int(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():Int(t[o],null)}}}}function Yj(...t){return Pnt.useCallback(kCe(...t),t)}var Vv=N(U(),1),Ent=N(Ve(),1);function Ant(t,e=[]){let n=[];function r(i,s){let a=Vv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Vv.useMemo(()=>m,Object.values(m));return(0,Ent.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Vv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Vv.createContext(s));return function(a){let l=a?.[t]||i;return Vv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,pqt(o,...e)]}function pqt(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Vv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var MCe=N(U(),1);var knt=N(U(),1),RP=globalThis?.document?knt.useLayoutEffect:()=>{};var mqt=MCe[" useId ".trim().toString()]||(()=>{}),hqt=0;function Mnt(t){let[e,n]=MCe.useState(mqt());return RP(()=>{t||n(r=>r??String(hqt++))},[t]),t||(e?`radix-${e}`:"")}var ad=N(U(),1);var Nnt=N(U(),1);function gqt(t,e){return Nnt.useReducer((n,r)=>e[n][r]??n,t)}var XY=t=>{let{present:e,children:n}=t,r=yqt(e),o=typeof n=="function"?n({present:r.isPresent}):ad.Children.only(n),i=Yj(r.ref,wqt(o));return typeof n=="function"||r.isPresent?ad.cloneElement(o,{ref:i}):null};XY.displayName="Presence";function yqt(t){let[e,n]=ad.useState(),r=ad.useRef(null),o=ad.useRef(t),i=ad.useRef("none"),s=t?"mounted":"unmounted",[a,l]=gqt(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return ad.useEffect(()=>{let c=JY(r.current);i.current=a==="mounted"?c:"none"},[a]),RP(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=JY(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),RP(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=JY(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=JY(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:ad.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function JY(t){return t?.animationName||"none"}function wqt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Dnt=N(U(),1),_qt=N(yo(),1);var ca=N(U(),1);var tL=N(Ve(),1);function Ont(t){let e=vqt(t),n=ca.forwardRef((r,o)=>{let{children:i,...s}=r,a=ca.Children.toArray(i),l=a.find(xqt);if(l){let c=l.props.children,u=a.map(d=>d===l?ca.Children.count(c)>1?ca.Children.only(null):ca.isValidElement(c)?c.props.children:null:d);return(0,tL.jsx)(e,{...s,ref:o,children:ca.isValidElement(c)?ca.cloneElement(c,void 0,u):null})}return(0,tL.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function vqt(t){let e=ca.forwardRef((n,r)=>{let{children:o,...i}=n;if(ca.isValidElement(o)){let s=Cqt(o),a=bqt(i,o.props);return o.type!==ca.Fragment&&(a.ref=r?kCe(r,s):s),ca.cloneElement(o,a)}return ca.Children.count(o)>1?ca.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var Rnt=Symbol("radix.slottable");function Lnt(t){let e=({children:n})=>(0,tL.jsx)(tL.Fragment,{children:n});return e.displayName=`${t}.Slottable`,e.__radixId=Rnt,e}function xqt(t){return ca.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===Rnt}function bqt(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function Cqt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var $nt=N(Ve(),1),Sqt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Fnt=Sqt.reduce((t,e)=>{let n=Ont(`Primitive.${e}`),r=Dnt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,$nt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var Kp=N(U(),1);var QY=N(U(),1);var Tqt=Kp[" useInsertionEffect ".trim().toString()]||RP;function Unt({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=Iqt({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=Kp.useRef(t!==void 0);Kp.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=Kp.useCallback(u=>{if(a){let d=Pqt(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function Iqt({defaultProp:t,onChange:e}){let[n,r]=Kp.useState(t),o=Kp.useRef(n),i=Kp.useRef(e);return Tqt(()=>{i.current=e},[e]),Kp.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function Pqt(t){return typeof t=="function"}var xAr=Symbol("RADIX:SYNC_STATE");var Knt=N(U(),1);var Vnt=N(U(),1),Rqt=N(yo(),1);var ua=N(U(),1);var Eqt=N(U(),1);function Bnt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function znt(...t){return e=>{let n=!1,r=t.map(o=>{let i=Bnt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():Bnt(t[o],null)}}}}var eZ=N(Ve(),1);function jnt(t){let e=Aqt(t),n=ua.forwardRef((r,o)=>{let{children:i,...s}=r,a=ua.Children.toArray(i),l=a.find(Mqt);if(l){let c=l.props.children,u=a.map(d=>d===l?ua.Children.count(c)>1?ua.Children.only(null):ua.isValidElement(c)?c.props.children:null:d);return(0,eZ.jsx)(e,{...s,ref:o,children:ua.isValidElement(c)?ua.cloneElement(c,void 0,u):null})}return(0,eZ.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function Aqt(t){let e=ua.forwardRef((n,r)=>{let{children:o,...i}=n;if(ua.isValidElement(o)){let s=Oqt(o),a=Nqt(i,o.props);return o.type!==ua.Fragment&&(a.ref=r?znt(r,s):s),ua.cloneElement(o,a)}return ua.Children.count(o)>1?ua.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var kqt=Symbol("radix.slottable");function Mqt(t){return ua.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===kqt}function Nqt(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function Oqt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Wnt=N(Ve(),1),Lqt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Hnt=Lqt.reduce((t,e)=>{let n=jnt(`Primitive.${e}`),r=Vnt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,Wnt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var qnt=N(Ve(),1),NCe=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),Dqt="VisuallyHidden",Gnt=Knt.forwardRef((t,e)=>(0,qnt.jsx)(Hnt.span,{...t,ref:e,style:{...NCe,...t.style}}));Gnt.displayName=Dqt;var Ynt=Gnt;var As=N(Ve(),1),[tZ,UAr]=Ant("Tooltip",[Vp]),nZ=Vp(),Znt="TooltipProvider",Fqt=700,OCe="tooltip.open",[Uqt,LCe]=tZ(Znt),Jnt=t=>{let{__scopeTooltip:e,delayDuration:n=Fqt,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=t,s=Qn.useRef(!0),a=Qn.useRef(!1),l=Qn.useRef(0);return Qn.useEffect(()=>{let c=l.current;return()=>window.clearTimeout(c)},[]),(0,As.jsx)(Uqt,{scope:e,isOpenDelayedRef:s,delayDuration:n,onOpen:Qn.useCallback(()=>{window.clearTimeout(l.current),s.current=!1},[]),onClose:Qn.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.current=!0,r)},[r]),isPointerInTransitRef:a,onPointerInTransitChange:Qn.useCallback(c=>{a.current=c},[]),disableHoverableContent:o,children:i})};Jnt.displayName=Znt;var Zj="Tooltip",[Bqt,Jj]=tZ(Zj),Xnt=t=>{let{__scopeTooltip:e,children:n,open:r,defaultOpen:o,onOpenChange:i,disableHoverableContent:s,delayDuration:a}=t,l=LCe(Zj,t.__scopeTooltip),c=nZ(e),[u,d]=Qn.useState(null),f=Mnt(),p=Qn.useRef(0),m=s??l.disableHoverableContent,h=a??l.delayDuration,g=Qn.useRef(!1),[y,w]=Unt({prop:r,defaultProp:o??!1,onChange:T=>{T?(l.onOpen(),document.dispatchEvent(new CustomEvent(OCe))):l.onClose(),i?.(T)},caller:Zj}),v=Qn.useMemo(()=>y?g.current?"delayed-open":"instant-open":"closed",[y]),x=Qn.useCallback(()=>{window.clearTimeout(p.current),p.current=0,g.current=!1,w(!0)},[w]),b=Qn.useCallback(()=>{window.clearTimeout(p.current),p.current=0,w(!1)},[w]),_=Qn.useCallback(()=>{window.clearTimeout(p.current),p.current=window.setTimeout(()=>{g.current=!0,w(!0),p.current=0},h)},[h,w]);return Qn.useEffect(()=>()=>{p.current&&(window.clearTimeout(p.current),p.current=0)},[]),(0,As.jsx)(Uv,{...c,children:(0,As.jsx)(Bqt,{scope:e,contentId:f,open:y,stateAttribute:v,trigger:u,onTriggerChange:d,onTriggerEnter:Qn.useCallback(()=>{l.isOpenDelayedRef.current?_():x()},[l.isOpenDelayedRef,_,x]),onTriggerLeave:Qn.useCallback(()=>{m?b():(window.clearTimeout(p.current),p.current=0)},[b,m]),onOpen:x,onClose:b,disableHoverableContent:m,children:n})})};Xnt.displayName=Zj;var RCe="TooltipTrigger",Qnt=Qn.forwardRef((t,e)=>{let{__scopeTooltip:n,...r}=t,o=Jj(RCe,n),i=LCe(RCe,n),s=nZ(n),a=Qn.useRef(null),l=Yj(e,a,o.onTriggerChange),c=Qn.useRef(!1),u=Qn.useRef(!1),d=Qn.useCallback(()=>c.current=!1,[]);return Qn.useEffect(()=>()=>document.removeEventListener("pointerup",d),[d]),(0,As.jsx)(Bv,{asChild:!0,...s,children:(0,As.jsx)(Fnt.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:l,onPointerMove:OP(t.onPointerMove,f=>{f.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),u.current=!0)}),onPointerLeave:OP(t.onPointerLeave,()=>{o.onTriggerLeave(),u.current=!1}),onPointerDown:OP(t.onPointerDown,()=>{o.open&&o.onClose(),c.current=!0,document.addEventListener("pointerup",d,{once:!0})}),onFocus:OP(t.onFocus,()=>{c.current||o.onOpen()}),onBlur:OP(t.onBlur,o.onClose),onClick:OP(t.onClick,o.onClose)})})});Qnt.displayName=RCe;var DCe="TooltipPortal",[zqt,jqt]=tZ(DCe,{forceMount:void 0}),ert=t=>{let{__scopeTooltip:e,forceMount:n,children:r,container:o}=t,i=Jj(DCe,e);return(0,As.jsx)(zqt,{scope:e,forceMount:n,children:(0,As.jsx)(XY,{present:n||i.open,children:(0,As.jsx)(vh,{asChild:!0,container:o,children:r})})})};ert.displayName=DCe;var nL="TooltipContent",trt=Qn.forwardRef((t,e)=>{let n=jqt(nL,t.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=t,s=Jj(nL,t.__scopeTooltip);return(0,As.jsx)(XY,{present:r||s.open,children:s.disableHoverableContent?(0,As.jsx)(nrt,{side:o,...i,ref:e}):(0,As.jsx)(Vqt,{side:o,...i,ref:e})})}),Vqt=Qn.forwardRef((t,e)=>{let n=Jj(nL,t.__scopeTooltip),r=LCe(nL,t.__scopeTooltip),o=Qn.useRef(null),i=Yj(e,o),[s,a]=Qn.useState(null),{trigger:l,onClose:c}=n,u=o.current,{onPointerInTransitChange:d}=r,f=Qn.useCallback(()=>{a(null),d(!1)},[d]),p=Qn.useCallback((m,h)=>{let g=m.currentTarget,y={x:m.clientX,y:m.clientY},w=Gqt(y,g.getBoundingClientRect()),v=Yqt(y,w),x=Zqt(h.getBoundingClientRect()),b=Xqt([...v,...x]);a(b),d(!0)},[d]);return Qn.useEffect(()=>()=>f(),[f]),Qn.useEffect(()=>{if(l&&u){let m=g=>p(g,u),h=g=>p(g,l);return l.addEventListener("pointerleave",m),u.addEventListener("pointerleave",h),()=>{l.removeEventListener("pointerleave",m),u.removeEventListener("pointerleave",h)}}},[l,u,p,f]),Qn.useEffect(()=>{if(s){let m=h=>{let g=h.target,y={x:h.clientX,y:h.clientY},w=l?.contains(g)||u?.contains(g),v=!Jqt(y,s);w?f():v&&(f(),c())};return document.addEventListener("pointermove",m),()=>document.removeEventListener("pointermove",m)}},[l,u,s,c,f]),(0,As.jsx)(nrt,{...t,ref:i})}),[Wqt,Hqt]=tZ(Zj,{isInside:!1}),Kqt=Lnt("TooltipContent"),nrt=Qn.forwardRef((t,e)=>{let{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...a}=t,l=Jj(nL,n),c=nZ(n),{onClose:u}=l;return Qn.useEffect(()=>(document.addEventListener(OCe,u),()=>document.removeEventListener(OCe,u)),[u]),Qn.useEffect(()=>{if(l.trigger){let d=f=>{f.target?.contains(l.trigger)&&u()};return window.addEventListener("scroll",d,{capture:!0}),()=>window.removeEventListener("scroll",d,{capture:!0})}},[l.trigger,u]),(0,As.jsx)(mh,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:d=>d.preventDefault(),onDismiss:u,children:(0,As.jsxs)(__,{"data-state":l.stateAttribute,...c,...a,ref:e,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[(0,As.jsx)(Kqt,{children:r}),(0,As.jsx)(Wqt,{scope:n,isInside:!0,children:(0,As.jsx)(Ynt,{id:l.contentId,role:"tooltip",children:o||r})})]})})});trt.displayName=nL;var rrt="TooltipArrow",qqt=Qn.forwardRef((t,e)=>{let{__scopeTooltip:n,...r}=t,o=nZ(n);return Hqt(rrt,n).isInside?null:(0,As.jsx)(S_,{...o,...r,ref:e})});qqt.displayName=rrt;function Gqt(t,e){let n=Math.abs(e.top-t.y),r=Math.abs(e.bottom-t.y),o=Math.abs(e.right-t.x),i=Math.abs(e.left-t.x);switch(Math.min(n,r,o,i)){case i:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Yqt(t,e,n=5){let r=[];switch(e){case"top":r.push({x:t.x-n,y:t.y+n},{x:t.x+n,y:t.y+n});break;case"bottom":r.push({x:t.x-n,y:t.y-n},{x:t.x+n,y:t.y-n});break;case"left":r.push({x:t.x+n,y:t.y-n},{x:t.x+n,y:t.y+n});break;case"right":r.push({x:t.x-n,y:t.y-n},{x:t.x-n,y:t.y+n});break}return r}function Zqt(t){let{top:e,right:n,bottom:r,left:o}=t;return[{x:o,y:e},{x:n,y:e},{x:n,y:r},{x:o,y:r}]}function Jqt(t,e){let{x:n,y:r}=t,o=!1;for(let i=0,s=e.length-1;i<e.length;s=i++){let a=e[i],l=e[s],c=a.x,u=a.y,d=l.x,f=l.y;u>r!=f>r&&n<(d-c)*(r-u)/(f-u)+c&&(o=!o)}return o}function Xqt(t){let e=t.slice();return e.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),Qqt(e)}function Qqt(t){if(t.length<=1)return t.slice();let e=[];for(let r=0;r<t.length;r++){let o=t[r];for(;e.length>=2;){let i=e[e.length-1],s=e[e.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))e.pop();else break}e.push(o)}e.pop();let n=[];for(let r=t.length-1;r>=0;r--){let o=t[r];for(;n.length>=2;){let i=n[n.length-1],s=n[n.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))n.pop();else break}n.push(o)}return n.pop(),e.length===1&&n.length===1&&e[0].x===n[0].x&&e[0].y===n[0].y?e:e.concat(n)}var rZ=Jnt,ort=Xnt,irt=Qnt,srt=ert,$Ce=trt;Kt();var uu=rZ,cn=ort,un=irt,on=Xj.forwardRef(({className:t,sideOffset:e=4,...n},r)=>Xj.createElement(srt,{container:activeDocument.body},Xj.createElement($Ce,{ref:r,sideOffset:e,className:oe("tw-z-[50] tw-overflow-hidden tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-secondary tw-px-3 tw-py-1.5 tw-text-xs tw-text-normal tw-animate-in tw-fade-in-0 tw-zoom-in-95 data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=closed]:tw-zoom-out-95 data-[side=bottom]:tw-slide-in-from-top-2 data-[side=left]:tw-slide-in-from-right-2 data-[side=right]:tw-slide-in-from-left-2 data-[side=top]:tw-slide-in-from-bottom-2",t),...n})));on.displayName=$Ce.displayName;vt();var xh=N(U()),lrt=require("obsidian"),Nn=({content:t,children:e,side:n="bottom",delayDuration:r=0,contentClassName:o,buttonClassName:i})=>{let s=lrt.Platform.isMobile,[a,l]=(0,xh.useState)(!1),c=xh.default.useRef(!1),u=()=>{s&&(c.current=!0)},d=()=>{s&&(l(!a),window.setTimeout(()=>{c.current=!1},100))};return xh.default.createElement(uu,{delayDuration:r},xh.default.createElement(cn,{open:a,onOpenChange:f=>{s&&c.current||l(f)}},xh.default.createElement(un,{asChild:!0},e?xh.default.createElement("div",{onClick:d,onTouchStart:u,className:"tw-cursor-pointer"},e):xh.default.createElement(X,{variant:"ghost",size:"sm",onClick:d,onTouchStart:u,className:`tw-inline-flex tw-size-6 tw-items-center tw-justify-center tw-p-0 hover:tw-bg-transparent hover:tw-text-normal ${i||""}`},xh.default.createElement(Uf,{className:"tw-size-4"}))),xh.default.createElement(on,{side:n,className:o},t)))};var Po=N(U()),Qj=require("obsidian");vt();Kt();rn();var E_="tw-size-3",eGt=()=>Qj.Platform.isMacOS?Po.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center tw-gap-0.5 tw-opacity-80"},Po.createElement(Qx,{className:E_}),Po.createElement(ag,{className:E_})):Po.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center tw-gap-0.5 tw-text-xs tw-opacity-80"},"Ctrl",Po.createElement(ag,{className:E_})),tGt=()=>Qj.Platform.isMacOS?Po.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center tw-gap-0.5 tw-opacity-80"},Po.createElement(Qx,{className:E_}),Po.createElement(BA,{className:E_}),Po.createElement(ag,{className:E_})):Po.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center tw-gap-0.5 tw-text-xs tw-opacity-80"},"Ctrl",Po.createElement(BA,{className:E_}),Po.createElement(ag,{className:E_}));function crt({state:t,onStop:e,onCopy:n,onInsert:r,onReplace:o,onSubmit:i,onCancel:s,showInsertReplace:a=!0,showSubmitCancel:l=!1,className:c}){return Po.createElement("div",{className:oe("tw-flex tw-items-center tw-gap-2",c)},t==="loading"&&Po.createElement(X,{variant:"secondary",size:"sm",onClick:e},"Stop"),t==="result"&&a&&Po.createElement(Po.Fragment,null,n&&Po.createElement(X,{size:"sm",variant:"secondary",onClick:n,title:"Copy to clipboard"},"Copy"),Po.createElement(X,{size:"sm",variant:"secondary",onClick:r,title:`Insert below selection (${Qj.Platform.isMacOS?"\u2318":"Ctrl"}+Shift+Enter)`},"Insert",Po.createElement(tGt,null)),Po.createElement(X,{size:"sm",onClick:o,title:`Replace selection (${Qj.Platform.isMacOS?"\u2318":"Ctrl"}+Enter)`},"Replace",Po.createElement(eGt,null))),l&&t!=="loading"&&Po.createElement(Po.Fragment,null,Po.createElement(X,{variant:"secondary",size:"sm",onClick:s},"Cancel"),Po.createElement(X,{size:"sm",onClick:i},"Submit")))}rn();function BCe({open:t,onClose:e,commandIcon:n,commandLabel:r,contentState:o,editableContent:i,onEditableContentChange:s,followUpValue:a,onFollowUpChange:l,onFollowUpSubmit:c,selectedModel:u,onSelectModel:d,onStop:f,onCopy:p,onInsert:m,onReplace:h,initialPosition:g,anchorBottom:y,resizable:w=!1,hideContentAreaOnIdle:v=!1,includeNoteContext:x,onIncludeNoteContextChange:b,renderMarkdown:_}){let T=o.type==="loading"||o.type==="result"&&o.isStreaming?"loading":o.type==="result"?"result":"idle",S=o.type==="loading"||o.type==="result"&&!!o.isStreaming,P=o.type==="result"&&!o.isStreaming&&!!s,A=$=>{if(T!=="result"||$.nativeEvent.isComposing)return;let B=urt.Platform.isMacOS?$.metaKey:$.ctrlKey;$.key!=="Enter"||!B||($.preventDefault(),$.stopPropagation(),$.shiftKey?m?.():h?.())},O=v?o.type!=="idle":!0;return Ml.createElement(ZJe,{open:t,onClose:e,initialPosition:g,anchorBottom:y,resizable:w,minHeight:w?O?400:180:void 0,width:"min(620px, 92vw)",closeOnEscapeFromOutside:!0},Ml.createElement("div",{onKeyDown:A,className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col"},Ml.createElement(JJe,{icon:n,label:r,className:"tw-border-b tw-border-border"}),O&&Ml.createElement(QJe,{state:o,editable:P,value:i,onChange:s,disableAutoGrow:w,minHeight:w?"0px":void 0,renderMarkdown:_}),Ml.createElement(eXe,{value:a,onChange:l,onSubmit:()=>{S||c()},onClear:()=>l(""),placeholder:"Enter follow-up instructions...",className:O?void 0:"tw-mt-auto",hint:S?"Generating...":void 0,autoFocus:!0}),Ml.createElement("div",{className:"tw-flex tw-flex-none tw-items-center tw-justify-between tw-border-t tw-border-border tw-px-4 tw-py-3"},Ml.createElement("div",{className:"tw-flex tw-items-center tw-gap-3"},Ml.createElement(eL,{size:"sm",variant:"ghost",value:u,onChange:d,disabled:S}),b&&Ml.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Ml.createElement(To,{id:"menuCommandIncludeContext",checked:x,onCheckedChange:$=>b(!!$),className:"tw-size-3.5",disabled:S}),Ml.createElement("label",{htmlFor:"menuCommandIncludeContext",className:"tw-cursor-pointer tw-text-xs tw-text-muted"},"Note"),Ml.createElement(Nn,{content:"Include the active note's content as context",side:"top"}))),Ml.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},v&&T==="idle"&&Ml.createElement(X,{variant:"default",size:"sm",onClick:c,disabled:!a.trim()||S,title:"Send message"},Ml.createElement(JS,{className:"tw-mr-1 tw-size-4"}),"Send"),Ml.createElement(crt,{state:T,onStop:f,onCopy:p,onInsert:m,onReplace:h})))))}ye();var e4=require("@codemirror/state"),LP=require("@codemirror/view");function oZ(t){let e=e4.StateEffect.define(),n=LP.Decoration.mark({class:t});function r(f,p,m){let h=Math.max(0,Math.min(p,f)),g=Math.max(0,Math.min(m,f));return h===g?null:{from:Math.min(h,g),to:Math.max(h,g)}}let o=e4.StateField.define({create:()=>null,update(f,p){let m=f;if(m&&!p.changes.empty){let h=p.changes.mapPos(m.from,1),g=p.changes.mapPos(m.to,-1);m=r(p.state.doc.length,h,g)}for(let h of p.effects)h.is(e)&&(m=h.value?r(p.state.doc.length,h.value.from,h.value.to):null);return m},provide:f=>LP.EditorView.decorations.from(f,p=>p?LP.Decoration.set([n.range(p.from,p.to)]):LP.Decoration.none)}),i=LP.EditorView.baseTheme({[`.${t}`]:{backgroundColor:"var(--text-selection)",borderRadius:"2px"}}),s=[o,i];function a(f){return f.state.field(o,!1)!==void 0}function l(f,p){let m=[];if(!p)return a(f)&&m.push(e.of(null)),m;let h=r(f.state.doc.length,p.from,p.to);return h?(a(f)||m.push(e4.StateEffect.appendConfig.of(s)),m.push(e.of(h)),m):(a(f)&&m.push(e.of(null)),m)}function c(f,p,m){let h=l(f,{from:p,to:m});h.length>0&&f.dispatch({effects:h})}function u(f){let p=l(f,null);p.length>0&&f.dispatch({effects:p})}function d(f){return f.state.field(o,!1)??null}return{field:o,effect:e,extension:s,show:c,hide:u,buildEffects:l,getRange:d}}var iZ=oZ("copilot-selection-highlight");function drt(t,e){try{t.dispatch(e)}catch(n){z("SelectionHighlight dispatch failed:",n)}}function nGt(t,e){return iZ.buildEffects(t,e)}function frt(t,e,n){let r=iZ.buildEffects(t,{from:e,to:n});r.length>0&&drt(t,{effects:r})}function rGt(t,e,n){frt(t,e,n)}function oGt(t){let e=iZ.buildEffects(t,null);e.length>0&&drt(t,{effects:e})}function iGt(t){return iZ.getRange(t)}var ld={show:frt,update:rGt,hide:oGt,getRange:iGt,buildEffects:nGt};ye();function rL(t){switch(t){case"no_range":return"No selection range available.";case"range_out_of_bounds":return"Selection range is out of bounds.";case"content_changed":return"Selection content has changed. Please reselect and try again.";case"file_changed":return"File has changed. Please reselect in the original file.";case"editor_changed":return"Editor has changed. Please reselect and try again.";case"leaf_changed":return"Editor pane has changed. Please reselect and try again.";case"target_unavailable":return"Editor is no longer available.";default:return"Cannot replace. Please reselect and try again."}}function prt(t,e,n){let r=t.state.toText(n);t.dispatch({changes:{from:e.from,to:e.to,insert:r},selection:{anchor:e.from,head:e.from+r.length}}),t.focus()}function mrt(t){let{editorView:e,leafSnapshot:n,filePathSnapshot:r,selectedTextSnapshot:o,initialRange:i,getLeafState:s}=t,a={...i},l=!0,c=null,u=null,d=h=>{let g=h.mapPos(a.from,1),y=h.mapPos(a.to,-1);a={from:Math.min(g,y),to:Math.max(g,y)},l=!0},f=()=>({...a}),p=()=>{let h=s(),g=!c||h.leaf!==c.leaf||h.editorView!==c.editorView||h.filePath!==c.filePath||!e.dom.isConnected;if(!l&&!g&&u)return u;l=!1,c=h;let y=(x,b)=>({ok:!1,reason:x,range:b,message:rL(x)});if(!h.leaf||h.leaf!==n)return u=y("leaf_changed",null),u;if(!h.editorView||h.editorView!==e)return u=y("editor_changed",null),u;if(h.filePath!==r)return u=y("file_changed",null),u;if(!e.dom.isConnected)return u=y("target_unavailable",null),u;let w=e.state.doc;return a.from<0||a.to>w.length||a.from>=a.to?(u=y("range_out_of_bounds",null),u):w.sliceString(a.from,a.to)!==o?(u=y("content_changed",{...a}),u):(u={ok:!0,reason:null,range:{...a}},u)};return{getRange:f,validate:p,onDocChanged:d,replace:h=>{let g=p();if(!g.ok||!g.range)return g;try{return prt(e,g.range,h),{ok:!0,reason:null,range:g.range}}catch(y){return z("MapPosReplaceGuard replace failed:",y),{ok:!1,reason:"target_unavailable",range:null,message:rL("target_unavailable")}}}}}function hrt(t){let{editorView:e,filePathSnapshot:n,selectedTextSnapshot:r,getCurrentContext:o}=t,i=()=>{let l=ld.getRange(e);return l?{from:l.from,to:l.to}:null},s=()=>{let l=o(),c=(p,m)=>({ok:!1,reason:p,range:m,message:rL(p)});if(!l.editorView)return c("target_unavailable",null);if(l.editorView!==e)return c("editor_changed",null);if(l.filePath!==n)return c("file_changed",null);let u=i();if(!u)return c("no_range",null);let d=e.state.doc;return u.from<0||u.to>d.length||u.from>=u.to?c("range_out_of_bounds",null):d.sliceString(u.from,u.to)!==r?c("content_changed",u):{ok:!0,reason:null,range:u}};return{getRange:i,validate:s,replace:l=>{let c=s();if(!c.ok||!c.range)return c;try{return prt(e,c.range,l),{ok:!0,reason:null,range:c.range}}catch(u){return z("HighlightReplaceGuard replace failed:",u),{ok:!1,reason:"target_unavailable",range:null,message:rL("target_unavailable")}}}}}ye();qe();function grt(t){let{scrollRect:e,visibleBottom:n,visibleTop:r,panelHeight:o,margin:i,gap:s,viewportHeight:a}=t,l=(e.top+e.bottom)/2-o/2,c=o+i,u,d;if(n&&r){let f=e.bottom-n.bottom-s,p=r.top-e.top-s;f>=c?u=n.bottom+s:p>=c?(d=r.top-s,u=d-o):u=l}else n?e.bottom-n.bottom-s>=c?u=n.bottom+s:u=l:r&&r.top-e.top-s>=c?(d=r.top-s,u=d-o):u=l;return u=Math.max(i,Math.min(u,a-i-o)),d!==void 0?{top:u,anchorBottomY:d}:{top:u}}function sZ(t,e){let n=t.from,r=t.to,o=t.head;return!t.empty&&r>0&&e.lineAt(r).from===r&&(r=r-1),!t.empty&&o>0&&o===t.to&&e.lineAt(o).from===o&&(o=o-1),{bottomPos:r,topPos:n,focusPos:o}}vt();var Ya=require("obsidian"),kr=N(U());function sGt(t){return t.split(/(```[\s\S]*?```|`[^`]*`)/g).map((n,r)=>r%2===1?n:n.replace(/\\\[\s*/g,"$$").replace(/\s*\\\]/g,"$$").replace(/\\\(\s*/g,"$").replace(/\s*\\\)/g,"$")).join("")}function aGt(t){return t=t.replace(/```dataview(\s*(?:\n|$))/g,"```text$1"),t=t.replace(/```dataviewjs(\s*(?:\n|$))/g,"```javascript$1"),t}function lGt(t){return t.replace(/```tasks(\s*(?:\n|$))/g,"```text$1")}function oL(t){let e=aGt(t),n=lGt(e);return sGt(n)}ws();Se();var to=N(U());jm();ph();eP();function zCe(){return new R9({returnMessages:!0,memoryKey:"history"})}async function yrt(t,e,n){let r=await Np.getInstance().createModelInstance(t),i=ou.fromMessages([fh.fromTemplate(e||"You are a helpful assistant. You'll help the user with their content editing needs."),new Pv("history"),ff.fromTemplate("{input}")]);return Kc.from([{input:s=>s.input,memory:()=>n.loadMemoryVariables({})},{input:s=>s.input,history:s=>s.memory.history},i,r])}It();ye();var Wv=N(U());function wrt(t){let e=(0,Wv.useRef)(t),n=(0,Wv.useRef)(null),r=(0,Wv.useRef)(null);return(0,Wv.useEffect)(()=>{e.current=t},[t]),(0,Wv.useEffect)(()=>()=>{n.current!==null&&(cancelAnimationFrame(n.current),n.current=null)},[]),(0,Wv.useCallback)((...o)=>{r.current=o,n.current===null&&(n.current=window.requestAnimationFrame(()=>{n.current=null;let i=r.current;i&&e.current(...i)}))},[])}function cGt(t){return`${t.name}|${t.provider}`}function uGt(t){if(!t.aborted)return!1;let e=t.reason;if(typeof e!="string")return!0;let n=e;return n==="new-chat"||n==="component-unmount"}function aZ(t){let{model:e,systemPrompt:n,excludeThinking:r=!0,onNoModel:o,onNonAbortError:i}=t,[s,a]=(0,to.useState)(!1),[l,c]=(0,to.useState)(""),u=(0,to.useRef)(!0),d=(0,to.useRef)(!1),f=(0,to.useRef)(null),p=(0,to.useRef)(""),m=(0,to.useRef)(!1),h=(0,to.useRef)(0),g=(0,to.useRef)(o),y=(0,to.useRef)(i);(0,to.useEffect)(()=>{g.current=o,y.current=i},[o,i]);let w=(0,to.useRef)(null),v=(0,to.useRef)(null),x=(0,to.useRef)(null),b=(0,to.useRef)(null),_=(0,to.useMemo)(()=>e?cGt(e):null,[e]),T=wrt(F=>{u.current&&c(F)}),S=(0,to.useCallback)(F=>{u.current&&(p.current=F,T(F))},[T]),P=(0,to.useCallback)(async F=>{if(!e||!_)return g.current?.(),null;if(!v.current||x.current!==_||b.current!==n){w.current||(w.current=zCe());let V=await yrt(e,n,w.current);if(F.aborted)return null;v.current=V,x.current=_,b.current=n}return!v.current||!w.current?null:{chain:v.current,memory:w.current}},[e,_,n]);(0,to.useEffect)(()=>(u.current=!0,()=>{u.current=!1,f.current?.abort("component-unmount"),f.current=null}),[]),(0,to.useEffect)(()=>{d.current&&f.current?.abort("new-chat"),v.current=null,x.current=null,b.current=null},[_,n]);let A=(0,to.useCallback)(()=>!m.current,[]),O=(0,to.useCallback)(()=>w.current,[]),D=(0,to.useCallback)(()=>p.current,[]),$=(0,to.useCallback)((F="user-stopped")=>{f.current?.abort(F)},[]),B=(0,to.useCallback)(()=>{f.current?.abort("new-chat"),f.current=null,v.current=null,x.current=null,b.current=null,w.current=zCe(),m.current=!1,h.current+=1,p.current="",d.current=!1,u.current&&(c(""),T(""),a(!1))},[T]),W=(0,to.useCallback)(async F=>{if(d.current)return null;d.current=!0,u.current&&a(!0);let Z=++h.current,V=new AbortController;f.current=V,p.current="",u.current&&(c(""),T(""));let H=J=>{h.current===Z&&S(J)},te=new of(H,r),fe=!1,me=null,j="",G=null;try{let J=!m.current;if(!e)return g.current?.(),null;if(j=await F({signal:V.signal,isFirstTurn:J}),V.signal.aborted||!j.trim())return null;let M=await P(V.signal);if(!M)return null;me=M.memory;let R=await M.chain.withConfig({signal:V.signal}).stream({input:j});for await(let L of R)if(te.processChunk(L),V.signal.aborted)break}catch(J){J instanceof Error&&J.name==="AbortError"||V.signal.aborted||(fe=!0,y.current?.(J))}finally{let J=te.close().content.trim(),M=uGt(V.signal),E=h.current!==Z;if(!fe&&J&&!M&&!E&&(G=J,me))try{let R=PR(J);await me.saveContext({input:j},{output:typeof R=="string"?R:J}),m.current=!0}catch(R){z("Error saving chat context:",R)}E||(p.current="",d.current=!1),f.current===V&&(f.current=null),u.current&&!E&&(c(""),T(""),a(!1))}return G},[r,P,S,e,T]);return{isStreaming:s,streamingText:l,getIsFirstTurn:A,runTurn:W,stop:$,reset:B,getMemory:O,getLatestStreamingText:D}}It();function dGt(t,e){return{...{autoExecuteOnOpen:!0,hideContentAreaOnIdle:!1,commandLabel:t.title,commandIcon:kr.default.createElement(Bf,{className:"tw-size-4 tw-text-muted"})},...e}}function fGt({originalText:t,command:e,onInsert:n,onReplace:r,onClose:o,systemPrompt:i,initialPosition:s,anchorBottom:a,behaviorConfig:l}){let c=(0,kr.useMemo)(()=>dGt(e,l),[e,l]),u=(0,kr.useRef)(!1),d=(0,kr.useRef)(!0);(0,kr.useEffect)(()=>(d.current=!0,()=>{d.current=!1}),[]);let f=(0,kr.useRef)(null);if(!f.current){let Te=new Ya.Component;Te.load(),f.current=Te}(0,kr.useEffect)(()=>()=>{f.current?.unload(),f.current=null},[]);let p=(0,kr.useRef)(app.workspace.getActiveFile()?.path??""),m=(0,kr.useCallback)(async(Te,Ee)=>{let nt=f.current;if(!nt)return;let rt=oL(Te);await Ya.MarkdownRenderer.renderMarkdown(rt,Ee,p.current,nt)},[]),[h,g]=(0,kr.useState)(""),[y,w]=(0,kr.useState)(""),[v,x]=(0,kr.useState)(c.autoExecuteOnOpen),[b,_]=(0,kr.useState)(""),[T]=qx(),S=Ht(),P=c.modelSelectionScope??"custom-command",A=(0,kr.useMemo)(()=>P==="quick-command"?S.quickCommandModelKey??T:e.modelKey||T,[P,S.quickCommandModelKey,e.modelKey,T]),[O,D]=(0,kr.useState)(A),$=(0,kr.useCallback)(Te=>{D(Te),P==="quick-command"&&pe("quickCommandModelKey",Te)},[P]),[B,W]=(0,kr.useState)(()=>S.quickCommandIncludeNoteContext),F=(0,kr.useCallback)(Te=>{W(Te),pe("quickCommandIncludeNoteContext",Te)},[]),Z=(0,kr.useMemo)(()=>{try{let Te=$f(O,S.activeModels);if(!Te.enabled)throw new Error(`Selected model is disabled: ${O}`);return Te}catch{return S.activeModels.find(Te=>Te.enabled)??null}},[O,S.activeModels]),H=(0,kr.useMemo)(()=>Z?`${Z.name}|${Z.provider}`:null,[Z])??O,{isStreaming:te,streamingText:fe,runTurn:me,stop:j,getLatestStreamingText:G}=aZ({model:Z,systemPrompt:i||"",excludeThinking:!0,onNoModel:()=>{new Ya.Notice("No active model is configured. Please configure a model in Copilot settings."),x(!1)},onNonAbortError:Te=>{z("Error generating response:",Te),new Ya.Notice("Error generating response. Please try again."),x(!1)}}),J=(0,kr.useRef)(""),[M,E]=(0,kr.useState)(h);M!==h&&(E(h),h&&w(h));let R=(0,kr.useMemo)(()=>v&&!te&&!fe&&!h?{type:"loading"}:te||fe?{type:"result",text:fe||h,isStreaming:te}:h?{type:"result",text:h,isStreaming:!1}:{type:"idle"},[v,te,fe,h]),L=(0,kr.useRef)(!1);(0,kr.useEffect)(()=>{if(!c.autoExecuteOnOpen||L.current)return;L.current=!0;let Te=!1;async function Ee(){try{let nt=await me(async rt=>{if(rt.signal.aborted)return"";let Jt=await Tj(e.content,t);return J.current=Jt,Jt});!Te&&nt&&(g(nt),J.current="")}catch(nt){z("Error in initial response:",nt)}finally{Te||x(!1)}}return Ee(),()=>{Te=!0,j("component-unmount")}},[c.autoExecuteOnOpen,e.content,t,me,j]);let K=async()=>{if(!b.trim()||u.current||v||te)return;u.current=!0;let Te=b;_(""),g(""),w("");try{x(!0);let Ee=await me(async nt=>{if(nt.signal.aborted)return"";let rt=nt.isFirstTurn,Jt=Te;rt&&c.firstSubmitTransform&&(Jt=c.firstSubmitTransform(Jt,B));let ke=await Tj(Jt,t,!rt);return J.current=ke,ke});if(!d.current)return;Ee&&(g(Ee),J.current="")}catch(Ee){Ee instanceof Error&&Ee.name==="AbortError"||(z("Error in follow-up submit:",Ee),d.current&&new Ya.Notice("Failed to send message. Please try again."))}finally{d.current&&x(!1),u.current=!1}},Y=(0,kr.useCallback)(()=>{let Te=G().trim();j("user-stopped"),Te&&g(Te),J.current=""},[j,G]),re=(0,kr.useCallback)(async()=>{let Te=y||h||fe;if(!Te)return;let Ee=ng(Te);try{await navigator.clipboard.writeText(Ee),new Ya.Notice("Copied to clipboard")}catch{new Ya.Notice("Failed to copy to clipboard")}},[y,h,fe]),ae=()=>{let Te=y||h||fe;Te&&n(Te)},ve=()=>{let Te=y||h||fe;Te&&r(Te)};return kr.default.createElement(BCe,{open:!0,onClose:o,commandIcon:c.commandIcon,commandLabel:c.commandLabel,contentState:R,editableContent:y,onEditableContentChange:w,followUpValue:b,onFollowUpChange:_,onFollowUpSubmit:K,selectedModel:H,onSelectModel:$,onStop:Y,onCopy:re,onInsert:ae,onReplace:ve,initialPosition:s,anchorBottom:a,resizable:!0,hideContentAreaOnIdle:c.hideContentAreaOnIdle,includeNoteContext:c.showIncludeNoteContext?B:void 0,onIncludeNoteContextChange:c.showIncludeNoteContext?F:void 0,renderMarkdown:m})}var A_=class{constructor(e,n){this.app=e;this.configs=n;this.root=null;this.container=null;this.highlightView=null;this.replaceGuard=null;this.scope=null}resolveWindow(e){return e?.containerEl?.win??window}resolveDocument(e){return e?.containerEl?.doc??activeDocument}getInitialPosition(e){let n=this.resolveWindow(e),r=Math.min(500,n.innerWidth*.9),i=this.configs.behaviorConfig?.hideContentAreaOnIdle??!1?180:400,s=12,a=6,l={x:Math.max(s,(n.innerWidth-r)/2),y:Math.max(s,(n.innerHeight-i)/2)};if(!e?.editor?.cm)return l;let c=e.editor.cm,u=c.state.selection.main,d=u.empty,f=sZ(u,c.state.doc),p=c.coordsAtPos(f.focusPos),m=c.coordsAtPos(f.bottomPos),h=c.coordsAtPos(f.topPos);if(!p&&!m&&!h)return l;let g=c.scrollDOM.getBoundingClientRect(),y=O=>O.bottom>=g.top&&O.top<=g.bottom&&O.right>=g.left&&O.left<=g.right,w=p&&y(p)?p:null,v=m&&y(m)?m:null,x=h&&y(h)?h:null;if(!w&&!v&&!x)return l;let b=Math.min((h?.bottom??0)-(h?.top??0),(m?.bottom??0)-(m?.top??0)),_=!d&&h&&m&&Math.abs(h.top-m.top)>Math.max(b/2,2),{top:T,anchorBottomY:S}=grt({scrollRect:g,visibleBottom:v,visibleTop:x,panelHeight:i,margin:s,gap:a,viewportHeight:n.innerHeight}),P=T,A;if(d)A=(w??v??x).left;else if(_)A=(g.left+g.right)/2-r/2;else{let O=c.coordsAtPos(f.topPos),D=c.coordsAtPos(f.bottomPos);O&&D?A=(O.left+D.right)/2-r/2:A=(g.left+g.right)/2-r/2}return A=Math.max(g.left,Math.min(A,g.right-r)),A=Math.max(s,Math.min(A,n.innerWidth-s-r)),{x:A,y:P,anchorBottom:S}}open(){this.scope=new Ya.Scope,this.scope.register(["Mod"],"Enter",()=>!0),this.scope.register(["Mod","Shift"],"Enter",()=>!0),this.app.keymap.pushScope(this.scope);let e=this.app.workspace.getActiveViewOfType(Ya.MarkdownView),n=this.resolveDocument(e);this.container=n.createElement("div"),this.container.className="copilot-menu-command-modal-container",n.body.appendChild(this.container),this.root=sr(this.container,this.app);let{selectedText:r,command:o,systemPrompt:i,behaviorConfig:s}=this.configs,a=r;if(e?.editor?.cm){let p=e.editor.cm,m=p.state.selection.main,h=e.file?.path??null;a=p.state.doc.sliceString(m.from,m.to),ld.show(p,m.from,m.to),this.highlightView=p,this.replaceGuard=hrt({editorView:p,filePathSnapshot:h,selectedTextSnapshot:a,getCurrentContext:()=>{let g=this.app.workspace.getActiveViewOfType(Ya.MarkdownView);return{editorView:g?.editor?.cm??null,filePath:g?.file?.path??null}}})}let{anchorBottom:l,...c}=this.getInitialPosition(e),u=p=>{EA(p),this.close()},d=p=>{if(!this.replaceGuard){new Ya.Notice("No selection to replace.");return}let m=ng(p),h=this.replaceGuard.replace(m);if(!h.ok){new Ya.Notice(h.message??"Cannot replace.");return}new Ya.Notice("Message replaced in the active note."),this.close()},f=()=>{this.close()};this.root.render(kr.default.createElement(fGt,{originalText:a,command:o,onInsert:u,onReplace:d,onClose:f,systemPrompt:i,initialPosition:c,anchorBottom:l,behaviorConfig:s}))}close(){this.scope&&(this.app.keymap.popScope(this.scope),this.scope=null),this.highlightView&&(ld.hide(this.highlightView),this.highlightView=null),this.replaceGuard=null,this.root?.unmount(),this.root=null,this.container?.remove(),this.container=null}};var cZ=require("obsidian");var lZ=class extends cZ.FuzzySuggestModal{constructor(e){super(e),this.setPlaceholder("Select a custom command to apply...");let n=td();this.commands=J9(n)}onOpen(){super.onOpen(),this.commands.length===0&&this.setInstructions([{command:"",purpose:"No custom commands found. Create some custom commands first in the settings."}])}getItems(){return this.commands}getItemText(e){return e.title}onChooseItem(e,n){let r=this.app.workspace.getActiveViewOfType(cZ.MarkdownView);if(!r||!r.editor){this.openCommandModal(e,"");return}let o=r.editor.getSelection();this.openCommandModal(e,o)}openCommandModal(e,n){Xs.getInstance().recordUsage(e),new A_(this.app,{selectedText:n,command:e}).open()}};Zg();rn();ye();qe();ws();var iL=require("obsidian"),Eo=N(U());function pGt({onClose:t}){let[e,n]=Eo.useState("input"),[r,o]=Eo.useState(""),[i,s]=Eo.useState(!1),[a,l]=Eo.useState(""),[c,u]=Eo.useState(!1),[d,f]=Eo.useState(null),p=(x,b=!0)=>{if(!x.trim())return b&&(l(""),u(!1)),{isValid:!1};let _=Fte(x);return _.isValid?(b&&(l(""),u(!0)),{isValid:!0,videoId:_.videoId}):(b&&(l(_.error||"Invalid URL"),u(!1)),{isValid:!1})},m=x=>{o(x),p(x,!0)},h=async()=>{if(i)return;let x=p(r);if(x.isValid){s(!0),l("");try{let b=await di.getInstance().youtube4llm(r);if(!b.response.transcript)throw new Error("Transcript not available. Only English videos with auto transcript enabled are supported.");let _={videoId:x.videoId,transcript:b.response.transcript,url:LAe(x.videoId)};f(_),n("display")}catch(b){z("Error downloading YouTube transcript:",b);let _=b instanceof Error?b.message:"An error occurred while downloading the transcript";l(_)}finally{s(!1)}}},g=async()=>{if(d)try{let x=`# YouTube Video Transcript

Source: ${d.url}

${d.transcript}`;await navigator.clipboard.writeText(x),new iL.Notice("Transcript copied to clipboard!")}catch(x){z("Failed to copy to clipboard:",x),new iL.Notice("Failed to copy to clipboard")}},y=async()=>{if(d)try{let x=`# YouTube Video Transcript

Source: ${d.url}

${d.transcript}`;await EA(x,!1),t()}catch(x){z("Failed to insert to note:",x),new iL.Notice("Failed to insert to note")}},w=()=>{n("input"),o(""),l(""),f(null)},v=x=>{x.key==="Enter"&&!i&&c&&h()};return e==="display"&&d?Eo.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Eo.createElement("div",{className:"tw-rounded tw-bg-secondary tw-p-3"},Eo.createElement("a",{href:d.url,className:"tw-text-sm tw-text-muted hover:tw-text-normal",target:"_blank",rel:"noopener noreferrer"},d.url)),Eo.createElement("div",{className:"tw-max-h-96 tw-overflow-y-auto tw-rounded tw-border tw-border-border tw-bg-primary tw-p-4"},Eo.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-sm tw-leading-relaxed"},d.transcript)),Eo.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Eo.createElement(X,{variant:"ghost",onClick:w},"Download Another"),Eo.createElement(X,{variant:"default",onClick:()=>void g()},"Copy to Clipboard"),Eo.createElement(X,{variant:"default",onClick:()=>void y()},"Insert at Cursor"),Eo.createElement(X,{variant:"secondary",onClick:t},"Close"))):Eo.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Eo.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Eo.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enter a valid YouTube video URL"),Eo.createElement(Xn,{placeholder:"https://www.youtube.com/watch?v=...",value:r,onChange:x=>m(x.target.value),onKeyDown:v,disabled:i}),a&&Eo.createElement("div",{className:"tw-text-sm tw-text-error"},a)),Eo.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Eo.createElement(X,{variant:"secondary",onClick:t,disabled:i},"Cancel"),Eo.createElement(X,{variant:"default",onClick:()=>void h(),disabled:i||!c},i?"Downloading...":"Download Transcript")))}var uZ=class extends iL.Modal{constructor(e){super(e),this.setTitle("Download YouTube Script (plus)")}onOpen(){let{contentEl:e}=this;this.root=sr(e,this.app);let n=()=>{this.close()};this.root.render(Eo.createElement(pGt,{onClose:n}))}onClose(){this.root.unmount()}};ns();yp();fc();qe();var vn=require("obsidian");qh();It();Ir();function Za(t,e,n){t.addCommand({id:e,name:nW[e],icon:rW[e],callback:()=>{let r=n();r instanceof Promise&&r.catch(o=>z(`Command ${e} failed`,o))}})}function eot(t,e,n){t.addCommand({id:e,name:nW[e],icon:rW[e],editorCallback:r=>{let o=n(r);o instanceof Promise&&o.catch(i=>z(`Editor command ${e} failed`,i))}})}function tot(t,e,n){t.addCommand({id:e,name:nW[e],icon:rW[e],checkCallback:n})}function n_e(t,e,n){eot(t,bt.COUNT_WORD_AND_TOKENS_SELECTION,async r=>{let o=r.getSelection(),i=o.split(" ").length,s=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(o);new vn.Notice(`Selected text contains ${i} words and ${s} tokens.`)}),Za(t,bt.COUNT_TOTAL_VAULT_TOKENS,async()=>{try{let r=await Vge(t.app),o=await t.projectManager.getCurrentChainManager().chatModelManager.countTokens(r);new vn.Notice(`Total tokens in your vault: ${o}`)}catch(r){z("Error counting tokens: ",r),new vn.Notice("An error occurred while counting tokens.")}}),Za(t,bt.TOGGLE_COPILOT_CHAT_WINDOW,()=>{t.toggleView()}),Za(t,bt.OPEN_COPILOT_CHAT_WINDOW,async()=>{await t.activateView()}),Za(t,bt.NEW_CHAT,async()=>{sO(),await t.newChat()}),tot(t,bt.TRIGGER_QUICK_COMMAND,r=>{let o=t.app.workspace.getActiveViewOfType(vn.MarkdownView);if(r)return!!(!t$()&&o&&o.editor);if(t$())return new vn.Notice("Quick command is not available in source mode."),!1;if(!o||!o.editor)return new vn.Notice("No active editor found."),!1;let s=o.editor.getSelection();if(!s.trim())return new vn.Notice("Please select some text first. Selected text is required for quick commands."),!1;let a={title:"Quick Command",content:"",showInContextMenu:!1,showInSlashMenu:!1,order:0,modelKey:"",lastUsedMs:Date.now()};return new A_(t.app,{selectedText:s,command:a,systemPrompt:Q9,behaviorConfig:{autoExecuteOnOpen:!1,hideContentAreaOnIdle:!0,commandLabel:"Quick Command",commandIcon:null,showIncludeNoteContext:!0,modelSelectionScope:"quick-command",firstSubmitTransform:(c,u)=>eY(c,u)}}).open(),!0}),Za(t,bt.CLEAR_LOCAL_COPILOT_INDEX,async()=>{let{getSettings:r}=await Promise.resolve().then(()=>(Se(),qy)),o=r();if(Fa(o)){new vn.Notice("Miyo folders are managed in Miyo. Remove the folder there if you want to clear it.");return}let s=`This will permanently delete all document indexes in Copilot. This action cannot be undone.

Are you sure you want to proceed?`;if(await new Promise(l=>{new Cr(t.app,()=>l(!0),s,"Clear Semantic Index","Clear Index","Cancel",()=>l(!1)).open()}))try{await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().clearIndex(),new vn.Notice("Cleared local Copilot semantic index.")}catch(l){z("Error clearing semantic index:",l),new vn.Notice("Failed to clear semantic index.")}}),Za(t,bt.GARBAGE_COLLECT_COPILOT_INDEX,async()=>{try{let{getSettings:r}=await Promise.resolve().then(()=>(Se(),qy));if(Fa(r())){new vn.Notice("Miyo manages file cleanup automatically. Run Index (refresh) vault to trigger a scan if needed.");return}let i=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().garbageCollectVectorStore();new vn.Notice(`Garbage collection completed. Removed ${i} stale documents.`)}catch(r){z("Error during garbage collection:",r),new vn.Notice("Failed to garbage collect semantic index.")}}),Za(t,bt.INDEX_VAULT_TO_COPILOT_INDEX,async()=>{try{let{getSettings:r}=await Promise.resolve().then(()=>(Se(),qy)),o=r();if(o.enableSemanticSearchV3){let s=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0});Fa(o)?new vn.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new vn.Notice(`Semantic search index refreshed with ${s} documents.`)}else new vn.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(r){z("Error building index:",r),new vn.Notice("An error occurred while building the index.")}}),Za(t,bt.FORCE_REINDEX_VAULT_TO_COPILOT_INDEX,async()=>{if(await new Promise(o=>{new Cr(t.app,()=>o(!0),"This will delete and rebuild your entire vault index from scratch. This operation cannot be undone. Are you sure you want to proceed?","Force Reindex Vault","Continue","Cancel",()=>o(!1)).open()}))try{let{getSettings:o}=await Promise.resolve().then(()=>(Se(),qy)),i=o();if(i.enableSemanticSearchV3){let a=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!0,{userInitiated:!0});Fa(i)?new vn.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new vn.Notice(`Semantic search index rebuilt with ${a} documents.`)}else new vn.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(o){z("Error rebuilding index:",o),new vn.Notice("An error occurred while rebuilding the index.")}}),Za(t,bt.LOAD_COPILOT_CHAT_CONVERSATION,async()=>{await t.loadCopilotChatHistory()}),Za(t,bt.LIST_INDEXED_FILES,async()=>{try{let o=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().getIndexedFiles(),{getMatchingPatterns:i,shouldIndexFile:s}=await Promise.resolve().then(()=>(fc(),g5e)),{inclusions:a,exclusions:l}=i(),c=t.app.vault.getMarkdownFiles(),u=new Set,d=new Set,f=new Set,p=new Set(o);for(let x of c){if(!s(x,a,l)){f.add(x.path);continue}let b=await t.app.vault.cachedRead(x);!b||b.trim().length===0?u.add(x.path):p.has(x.path)||d.add(x.path)}let m=["# Copilot Files Status",`- Indexed files: ${p.size}`,`- Unindexed files: ${d.size}`,`- Empty files: ${u.size}`,`- Excluded files: ${f.size}`,"","## Indexed Files",...p.size>0?Array.from(p).sort().map(x=>`- [[${x}]]`):["No indexed files found."],"","## Unindexed Files",...d.size>0?Array.from(d).sort().map(x=>`- [[${x}]]`):["No unindexed files found."],"","## Empty Files",...u.size>0?Array.from(u).sort().map(x=>`- [[${x}]]`):["No empty files found."],"","## Excluded Files (based on settings)",...f.size>0?Array.from(f).sort().map(x=>`- [[${x}]]`):["No excluded files."]].join(`
`),h=`Copilot-Indexed-Files-${new Date().toLocaleDateString().replace(/\//g,"-")}.md`,g="copilot",y=`${g}/${h}`;await Fr(g);let w=t.app.vault.getAbstractFileByPath(y);w instanceof vn.TFile?await t.app.vault.modify(w,m):await t.app.vault.create(y,m);let v=t.app.vault.getAbstractFileByPath(y);v instanceof vn.TFile&&(await t.app.workspace.getLeaf().openFile(v),new vn.Notice(`Listed ${p.size} indexed files`))}catch(r){z("Error listing indexed files:",r),new vn.Notice("Failed to list indexed files.")}}),Za(t,bt.INSPECT_COPILOT_INDEX_BY_NOTE_PATHS,async()=>{try{let r=t.app.workspace.getActiveFile();if(!r){new vn.Notice("No active file. Please open a note first.");return}let o=(await Promise.resolve().then(()=>(ei(),ji))).default,{DBOperations:i}=await Promise.resolve().then(()=>(aG(),w5e)),s=await o.getInstance().getDb(),a=await i.getDocsByPath(s,r.path);if(!a||a.length===0){new vn.Notice(`No embedding data found for: ${r.path}`);return}let l=a.map(h=>h.document),c=[`# Embedding Debug: ${r.basename}`,"",`**Path:** ${r.path}`,`**Chunks:** ${l.length}`,`**Embedding Model:** ${l[0]?.embeddingModel||"unknown"}`,"",...l.flatMap((h,g)=>{let y=h.embedding||[],w=y.slice(0,10).map(v=>v.toFixed(6)).join(", ");return[`## Chunk ${g+1}`,`- **ID:** ${h.id}`,`- **Content Preview:** "${(h.content||"").substring(0,200)}..."`,`- **Vector Length:** ${y.length}`,`- **Vector Preview:** [${w}${y.length>10?", ...":""}]`,`- **Tags:** ${(h.tags||[]).join(", ")||"none"}`,`- **Characters:** ${h.nchars||0}`,""]})].join(`
`),u=`Copilot-Embedding-Debug-${r.basename.replace(/[\\/:*?"<>|]/g,"_")}.md`,d="copilot",f=`${d}/${u}`;await Fr(d);let p=t.app.vault.getAbstractFileByPath(f);p instanceof vn.TFile?await t.app.vault.modify(p,c):await t.app.vault.create(f,c);let m=t.app.vault.getAbstractFileByPath(f);m instanceof vn.TFile&&(await t.app.workspace.getLeaf().openFile(m),new vn.Notice(`Embedding debug info for ${l.length} chunk(s)`))}catch(r){z("Error inspecting embeddings:",r),new vn.Notice("Failed to inspect embeddings. Is the index loaded?")}}),Za(t,bt.CLEAR_COPILOT_CACHE,async()=>{try{await t.fileParserManager.clearPDFCache(),await ti.getInstance().clearAllCache(),await JN.getInstance().clear(),new vn.Notice("All Copilot caches cleared successfully")}catch(r){z("Error clearing Copilot caches:",r),new vn.Notice("Failed to clear Copilot caches")}}),Za(t,bt.OPEN_LOG_FILE,async()=>{try{await TG(),await Ds.openLogFile()}catch(r){z("Error creating Copilot log file:",r),new vn.Notice("Failed to create Copilot log file.")}}),Za(t,bt.CLEAR_LOG_FILE,async()=>{try{await Ds.clear(),new vn.Notice("Copilot log cleared.")}catch(r){z("Error clearing Copilot log file:",r),new vn.Notice("Failed to clear Copilot log file.")}}),eot(t,bt.ADD_SELECTION_TO_CHAT_CONTEXT,async r=>{let o=r.getSelection();if(!o){new vn.Notice("No text selected");return}let i=t.app.workspace.getActiveFile();if(!i){new vn.Notice("No active file");return}let s=r.listSelections()[0];if(!s){new vn.Notice("Could not determine selection range");return}let a=s.anchor.line+1,l=s.head.line+1,c={id:si(),content:o,sourceType:"note",noteTitle:i.basename,notePath:i.path,startLine:Math.min(a,l),endLine:Math.max(a,l)};og([c]),await t.activateView()}),Za(t,bt.ADD_WEB_SELECTION_TO_CHAT_CONTEXT,async()=>{let{Platform:r}=await import("obsidian");if(!r.isDesktopApp){new vn.Notice("Web selection is only available on desktop");return}let{getWebViewerService:o}=await Promise.resolve().then(()=>(FP(),Qrt));try{let i=o(t.app),s=i.getActiveLeaf()??i.getLastActiveLeaf();if(!s){new vn.Notice("No active Web Tab found");return}let a=await i.getSelectedMarkdown(s);if(!a.trim()){new vn.Notice("No text selected in Web Tab");return}let l=i.getPageInfo(s),c={id:si(),content:a,sourceType:"web",title:l.title||"Untitled",url:l.url,faviconUrl:l.faviconUrl||void 0};og([c]),await t.activateView()}catch(i){z("Error adding web selection to context:",i),new vn.Notice("Failed to get web selection")}}),Za(t,bt.ADD_CUSTOM_COMMAND,async()=>{let r=td(),o={...hy};new g_(t.app,r,o,async s=>{await Xs.getInstance().createCommand(s)}).open()}),Za(t,bt.APPLY_CUSTOM_COMMAND,()=>{new lZ(t.app).open()}),Za(t,bt.DOWNLOAD_YOUTUBE_SCRIPT,async()=>{if(!await _p()){new vn.Notice("Download YouTube Script (plus) is a Copilot Plus feature");return}new uZ(t.app).open()}),tot(t,bt.TRIGGER_QUICK_ASK,r=>{let o=t.app.workspace.getActiveViewOfType(vn.MarkdownView);if(r)return!!(!t$()&&o&&o.editor);if(t$())return new vn.Notice("Quick Ask is not available in source mode."),!1;if(!o||!o.editor)return new vn.Notice("No active editor found."),!1;let i=o.editor.cm;return i?(t.quickAskController.show(o,i),!0):(new vn.Notice("Could not access CodeMirror editor."),!1)})}Ir();var mL={title:"",content:"",createdMs:0,modifiedMs:0,lastUsedMs:0},hL="copilot-system-prompt-created",gL="copilot-system-prompt-modified",yL="copilot-system-prompt-last-used",r_e="copilot-system-prompt-default";var N_=require("obsidian");Se();qe();ye();function n4(t,e,n){let r=t.trim();return r?t!==r?"Prompt name cannot have leading or trailing spaces":n&&t===n?null:/[#<>:"/\\|?*[\]^\x00-\x1F]/g.test(r)?'Prompt name contains invalid characters. Avoid using: < > : " / \\ | ? * [ ] ^':e.some(i=>i.title.toLowerCase()===r.toLowerCase())?"A prompt with this name already exists":null:"Prompt name cannot be empty"}function qp(){return(0,N_.normalizePath)(q().userSystemPromptsFolder)}function Gp(t){return(0,N_.normalizePath)(`${qp()}/${t}.md`)}function KGt(t,e){let n=e?(0,N_.normalizePath)(e):qp();return(0,N_.normalizePath)(`${n}/${t}.md`)}function wL(t){if(!(t instanceof N_.TFile)||t.extension!=="md")return!1;let e=qp();if(!t.path.startsWith(e+"/"))return!1;let n=t.path.slice(e.length+1);return!(n.startsWith("unsupported/")||n.includes("/"))}function o_e(t,e){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"){let n=Number(t);if(Number.isFinite(n))return n}return e}async function UP(t){let e=await app.vault.read(t),n=Qh(e),o=app.metadataCache.getFileCache(t)?.frontmatter,i=o_e(o?.[hL],mL.createdMs),s=o_e(o?.[gL],mL.modifiedMs),a=o_e(o?.[yL],mL.lastUsedMs);return{title:t.basename,content:n,createdMs:i,modifiedMs:s,lastUsedMs:a}}async function i_e(){let t=app.vault.getFiles().filter(e=>wL(e));return await Promise.all(t.map(UP))}async function vL(){let t=await i_e();return W8(t),t}async function BP(t,e){let n=vv(t.path),r=Date.now(),o=Number.isFinite(e.createdMs)&&e.createdMs>0?e.createdMs:r,i=Number.isFinite(e.modifiedMs)&&e.modifiedMs>0?e.modifiedMs:r,s=Number.isFinite(e.lastUsedMs)&&e.lastUsedMs>0?e.lastUsedMs:0;try{n||t_(t.path),await app.fileManager.processFrontMatter(t,a=>{a[hL]==null&&(a[hL]=o),a[gL]==null&&(a[gL]=i),a[yL]==null&&(a[yL]=s)})}finally{n||n_(t.path)}}function not(t,e){let r=`${t} (copy)`,o=1;for(;e.some(i=>i.title.toLowerCase()===r.toLowerCase());)o++,r=`${t} (copy ${o})`;return r}async function s_e(t,e,n){let r=KGt(t,n),o=app.vault.getAbstractFileByPath(r);if(!(o instanceof N_.TFile)){ee(`System prompt file not found for default flag update: ${r}`);return}let i=vv(o.path);try{i||t_(o.path),await app.fileManager.processFrontMatter(o,s=>{e?s[r_e]=!0:delete s[r_e]})}finally{i||n_(o.path)}}var r4=require("obsidian");ye();qe();av();Se();var zP=class t{constructor(e){this.vault=e}static getInstance(e){if(!t.instance){if(!e)throw new Error("Vault is required for first initialization");t.instance=new t(e)}return t.instance}async initialize(){k("Initializing SystemPromptManager"),await vL()}async createPrompt(e,n=!1){let r=iR(),o=n4(e.title,r);if(o)throw new Error(o);let i=Gp(e.title),s=qp();try{t_(i),await Fr(s),await this.vault.create(i,e.content);let a=this.vault.getAbstractFileByPath(i);a instanceof r4.TFile&&await BP(a,e),n||rP(e),k(`Created system prompt: ${e.title}`)}finally{n_(i)}}async updatePrompt(e,n,r=!1){let o=Gp(e),i=Gp(n.title),s=e!==n.title;if(s){let a=iR(),l=n4(n.title,a,e);if(l)throw new Error(l)}try{if(t_(i),s&&t_(o),s){let l=this.vault.getAbstractFileByPath(o);l instanceof r4.TFile&&await app.fileManager.renameFile(l,i)}let a=this.vault.getAbstractFileByPath(i);a instanceof r4.TFile&&(await this.vault.modify(a,n.content),await app.fileManager.processFrontMatter(a,l=>{l[hL]=n.createdMs,l[gL]=n.modifiedMs,l[yL]=n.lastUsedMs})),r||(s&&(sR(e),q().defaultSystemPromptTitle===e&&(pe("defaultSystemPromptTitle",n.title),k(`Updated defaultSystemPromptTitle: ${e} -> ${n.title}`))),rP(n)),k(`Updated system prompt: ${e} -> ${n.title}`)}finally{n_(i),s&&n_(o)}}async deletePrompt(e){let n=Gp(e);try{t_(n);let r=this.vault.getAbstractFileByPath(n);r instanceof r4.TFile&&await Qc(app,r),q().defaultSystemPromptTitle===e&&(pe("defaultSystemPromptTitle",""),k(`Cleared defaultSystemPromptTitle (deleted: ${e})`)),nP()===e&&(e_(""),k(`Cleared session selectedPromptTitle (deleted: ${e})`)),sR(e),k(`Deleted system prompt: ${e}`)}finally{n_(n)}}async duplicatePrompt(e){let n=iR(),r=not(e.title,n),o=Date.now(),i={title:r,content:e.content,createdMs:o,modifiedMs:o,lastUsedMs:0};return await this.createPrompt(i),k(`Duplicated system prompt: ${e.title} -> ${r}`),i}getPrompts(){return iR()}async reloadPrompts(){return await vL()}async fetchPrompts(){return await i_e()}};var xL=require("obsidian");Se();Hx();ye();var o4=class{constructor(e,n){this.folderChangeRequestId=0;this.handleSettingsChange=(e,n)=>{let r=e.userSystemPromptsFolder!==n.userSystemPromptsFolder;if(e.defaultSystemPromptTitle!==n.defaultSystemPromptTitle){let i=r?e.userSystemPromptsFolder:void 0;this.handleDefaultPromptChange(e.defaultSystemPromptTitle,n.defaultSystemPromptTitle,i)}r&&this.debouncedFolderChange(n.userSystemPromptsFolder)};this.debouncedFolderChange=Li(e=>{this.handleSystemPromptsFolderChange(e)},300,{leading:!1,trailing:!0});this.handleFileModify=Li(async e=>{if(!(!wL(e)||vv(e.path)))try{let n=await UP(e);rP(n)}catch(n){z(`Error processing system prompt modification: ${e.path}`,n)}},1e3,{leading:!1,trailing:!0});this.handleFileCreation=async e=>{if(!(!wL(e)||vv(e.path)))try{let n=await UP(e);await BP(e,n);let r=await UP(e);rP(r)}catch(n){z(`Error processing system prompt creation: ${e.path}`,n)}};this.handleFileDeletion=async e=>{if(!(!wL(e)||vv(e.path)))try{sR(e.basename),q().defaultSystemPromptTitle===e.basename&&pe("defaultSystemPromptTitle",""),nP()===e.basename&&(e_(""),new xL.Notice(`System prompt "${e.basename}" was deleted. Cleared current chat selection.`))}catch(n){z(`Error processing system prompt deletion: ${e.path}`,n)}};this.handleFileRename=async(e,n)=>{if(vv(e.path)||vv(n))return;let r=qp(),o=n.startsWith(r+"/")?n.slice(r.length+1):"",i=o!==""&&!o.includes("/")&&n.endsWith(".md"),s=wL(e)?e:null;if(!(!i&&!s))try{if(i){let a=n.split("/").pop()?.replace(/\.md$/i,"");if(a&&(sR(a),q().defaultSystemPromptTitle===a&&(s?pe("defaultSystemPromptTitle",s.basename):pe("defaultSystemPromptTitle","")),nP()===a)){let c=s?s.basename:"";e_(c),s?new xL.Notice(`System prompt "${a}" was renamed to "${s.basename}". Updated current chat selection.`):new xL.Notice(`System prompt "${a}" was moved out of the prompts folder. Cleared current chat selection.`)}}if(s){let a=await UP(s);await BP(s,a);let l=await UP(s);rP(l)}}catch(a){z(`Error processing system prompt rename: ${e.path}`,a)}};this.plugin=e,this.vault=n,this.manager=zP.getInstance(n),this.initializeEventListeners()}async initialize(){await this.manager.initialize(),K9e()}cleanup(){this.handleFileModify.cancel(),this.debouncedFolderChange.cancel(),this.settingsUnsubscriber?.(),this.vault.off("create",this.handleFileCreation),this.vault.off("delete",this.handleFileDeletion),this.vault.off("rename",this.handleFileRename),this.vault.off("modify",this.handleFileModify)}initializeEventListeners(){this.vault.on("create",this.handleFileCreation),this.vault.on("delete",this.handleFileDeletion),this.vault.on("rename",this.handleFileRename),this.vault.on("modify",this.handleFileModify),this.settingsUnsubscriber=Ho(this.handleSettingsChange)}async handleDefaultPromptChange(e,n,r){try{e&&await s_e(e,!1,r),n&&await s_e(n,!0),k(`Default system prompt changed: "${e}" -> "${n}"`)}catch(o){z("Error updating default system prompt frontmatter",o)}}async handleSystemPromptsFolderChange(e){let n=++this.folderChangeRequestId;try{k(`System prompts folder changed to: ${e}`);let r=await this.manager.fetchPrompts();if(n!==this.folderChangeRequestId){k(`Folder change request ${n} superseded by ${this.folderChangeRequestId}, discarding results`);return}W8(r);let o=new Set(r.map(i=>i.title));this.validatePromptReferences(o)}catch(r){n===this.folderChangeRequestId&&z(`Error reloading system prompts after folder change to: ${e}`,r)}}validatePromptReferences(e){let n=q(),r=nP();n.defaultSystemPromptTitle&&!e.has(n.defaultSystemPromptTitle)&&(pe("defaultSystemPromptTitle",""),k(`Cleared defaultSystemPromptTitle (not found in new folder): ${n.defaultSystemPromptTitle}`),new xL.Notice(`Default system prompt "${n.defaultSystemPromptTitle}" not found in new folder. Cleared default selection.`)),r&&!e.has(r)&&(e_(""),k(`Cleared selectedPromptTitle (not found in new folder): ${r}`),new xL.Notice(`Current system prompt "${r}" not found in new folder. Cleared chat selection.`))}};var Ni=N(U());rn();vt();var bL=require("obsidian");ws();Se();var bh=N(U());function CZ(){return bh.default.createElement("ul",{className:"tw-m-0 tw-px-4 tw-text-sm"},bh.default.createElement("li",null,bh.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{[[Note Title]]}")," includes a note's content. Note: bare ",bh.default.createElement("span",{className:"tw-font-medium"},"[[Note Title]]")," ","without curly braces will NOT include the note content."),bh.default.createElement("li",null,bh.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{activeNote}")," represents the active note."),bh.default.createElement("li",null,bh.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{#tag1, #tag2}")," represents ALL notes with ANY of the specified tags in their property (an OR operation)."),bh.default.createElement("li",null,bh.default.createElement("span",{className:"tw-font-medium tw-text-accent"},"{folder/path}")," represents notes from a specific folder path."))}ye();function qGt({prompts:t,onConfirm:e,onCancel:n,contentEl:r}){let o=Ht(),[i,s]=(0,Ni.useState)({...mL}),[a,l]=(0,Ni.useState)({}),c=(d,f)=>{s(p=>({...p,[d]:f})),l(p=>({...p,[d]:void 0}))},u=()=>{let d={},f=n4(i.title,t,"");if(f&&(d.title=f),i.content.trim()||(d.content="Content is required"),Object.keys(d).length>0){l(d);return}e(i)};return Ni.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4 tw-p-4"},Ni.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-4 tw-text-muted"},Ni.default.createElement(Cm,{className:"tw-size-5 tw-shrink-0"}),Ni.default.createElement("div",{className:"tw-flex-1"},"System prompts are automatically loaded from .md files in your system prompts folder"," ",Ni.default.createElement("strong",null,o.userSystemPromptsFolder),". Modifying the files will also update the system prompt settings.")),Ni.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ni.default.createElement(hi,{htmlFor:"title"},"Name"),Ni.default.createElement(Xn,{id:"title",placeholder:"Enter prompt name",value:i.title,onChange:d=>c("title",d.target.value)}),a.title&&Ni.default.createElement("div",{className:"tw-text-sm tw-text-error"},a.title)),Ni.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Ni.default.createElement(hi,{htmlFor:"content"},"Content"),Ni.default.createElement(CZ,null),Ni.default.createElement("div",{className:"tw-relative"},Ni.default.createElement(hf,{id:"content",placeholder:"Enter your system prompt here... Use {[[Note Name]]} to include note contents.",value:i.content,onChange:d=>c("content",d.target.value),rows:10,className:"tw-min-h-[180px] tw-w-full tw-pr-8"})),a.content&&Ni.default.createElement("div",{className:"tw-text-sm tw-text-error"},a.content)),Ni.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Ni.default.createElement(X,{variant:"secondary",onClick:n},"Cancel"),Ni.default.createElement(X,{variant:"default",onClick:u},"Save")))}var i4=class extends bL.Modal{constructor(n,r){super(n);this.prompts=r;this.setTitle("Add System Prompt")}onOpen(){let{contentEl:n,modalEl:r}=this;bL.Platform.isMobile&&r.addClass("tw-h-4/5"),this.root=sr(n,this.app);let o=async i=>{let s=Date.now(),a={...i,createdMs:s,modifiedMs:s,lastUsedMs:0};try{await zP.getInstance().createPrompt(a),this.close()}catch(l){let c=l instanceof Error?l.message:String(l);z("Failed to create system prompt:",l),new bL.Notice(`Failed to create prompt: ${c}`)}};this.root.render(Ni.default.createElement(qGt,{prompts:this.prompts,onConfirm:o,onCancel:()=>this.close(),contentEl:n}))}onClose(){this.root.unmount()}};var iot=require("obsidian");ye();Se();qe();var rot="Migrated Custom System Prompt";function GGt(t,e){let n=t,r=1;for(;e.getAbstractFileByPath(Gp(n));)r++,n=`${t} ${r}`;return n}function a_e(t){return t.replace(/\r\n/g,`
`).replace(/\r/g,`
`)}async function oot(t,e,n){let r=qp(),o=`${r}/unsupported`;await Fr(o);let i="Migrated System Prompt (Failed Verification)",s=i,a=1;for(;t.getAbstractFileByPath(`${o}/${s}.md`);)a++,s=`${i} ${a}`;let l=`${o}/${s}.md`,c=`> Migration failed: ${n}
>
> To fix: Review the content below, then move this file to ${r}

${e}`;return await t.create(l,c),l}async function YGt(t,e,n){try{let r=await t.read(e),o=Qh(r,{trimStart:!1}),i=a_e(o).replace(/^\n+/,""),s=a_e(n).replace(/^\n+/,"");return i!==s?(ee(`Migration verification failed: content mismatch. Expected ${s.length} chars, got ${i.length} chars`),!1):!0}catch(r){return z("Migration verification failed: unable to read back file",r),!1}}async function l_e(t){let n=q().userSystemPrompt;if(!n||n.trim().length===0){k("No legacy userSystemPrompt to migrate");return}try{k("Migrating legacy userSystemPrompt from settings to file system");let r=qp();await Fr(r);let o=GGt(rot,t),i=Gp(o);o!==rot&&k(`Default name already exists, using unique name: "${o}"`);let s=Date.now(),a=a_e(n),l={title:o,content:a,createdMs:s,modifiedMs:s,lastUsedMs:0};await t.create(i,a);let c=t.getAbstractFileByPath(i);if(!(c instanceof iot.TFile))throw new Error("File not found after creation");if(await BP(c,l),await YGt(t,c,n)){pe("defaultSystemPromptTitle",o);try{await vL()}catch(d){ee("Failed to reload prompts after migration:",d)}pe("userSystemPrompt",""),k("Cleared legacy userSystemPrompt field"),new Cr(app,()=>{},`We have upgraded your system prompt to the new file-based format. It is now stored as "${o}" in ${r}.

You can now:
\u2022 Edit your system prompt directly in the file
\u2022 Create multiple system prompts
\u2022 Manage prompts through the settings UI

Your migrated prompt has been set as the default system prompt.`,"\u{1F680} System Prompt Upgraded","OK","").open()}else{let d=await oot(t,n,"content verification mismatch");try{await vL()}catch(f){ee("Failed to reload prompts after failed migration:",f)}pe("userSystemPrompt",""),k("Cleared legacy userSystemPrompt field (saved to unsupported)"),new Cr(app,()=>{},`\u26A0\uFE0F System Prompt Migration Issue

Your system prompt was migrated but verification failed. Your data has been saved to:

${d}

To recover:
1. Open the file and review the content
2. Move it to ${r}
3. The prompt will be available immediately`,"Migration Verification Failed","OK","").open()}}catch(r){let o=r instanceof Error?r.message:String(r);z("Failed to migrate legacy userSystemPrompt:",r);try{let i=await oot(t,n,o);pe("userSystemPrompt",""),k("Cleared legacy userSystemPrompt field (saved to unsupported after error)"),new Cr(app,()=>{},`\u26A0\uFE0F System Prompt Migration Failed

An error occurred during migration. Your data has been saved to:

${i}

To recover:
1. Open the file and review the content
2. Move it to ${qp()}
3. The prompt will be available immediately`,"Migration Failed","OK","").open()}catch(i){z("Failed to save to unsupported folder:",i),ee("Preserving userSystemPrompt in settings for manual recovery"),new Cr(app,()=>{},`Failed to migrate system prompt: ${o}

Unable to save to file system. Your system prompt is still in settings and will continue to work.

Please check:
- Folder permissions for ${qp()}
- Available disk space
- Vault is accessible

You can retry by reloading the plugin.`,"Migration Failed - Data Preserved","OK","").open()}}}Qi();Qi();Ir();function _Z(){let[t]=kd(),[e]=KW(),[n]=Yx();return(()=>{if(t!=="project")return"initial";let{total:o,success:i,failed:s,processingFiles:a}=n;return e||a.length>0?"loading":s.length>0?"error":o.length>0&&i.length===o.length?"success":"initial"})()}ye();Ir();Qi();rn();It();ye();yp();ns();Se();bi();vt();var Nl=require("obsidian"),Pt=N(U());var Ot=N(U());vt();rn();var CL=N(U());rn();vt();var _L=({value:t,onChange:e,placeholder:n="Search..."})=>CL.default.createElement("div",{className:"tw-relative"},CL.default.createElement(Xn,{type:"text",placeholder:n,value:t,onChange:r=>e(r.target.value),className:"tw-pr-10"}),t&&CL.default.createElement(X,{variant:"secondary",onClick:()=>e(""),className:"tw-absolute tw-right-8 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-rounded-full tw-p-0 tw-transition-colors","aria-label":"Clear search"},CL.default.createElement(sg,{className:"tw-size-4 tw-text-muted/60 hover:tw-text-accent-hover"})),CL.default.createElement(ZS,{className:"tw-absolute tw-right-3 tw-top-1/2 tw-size-4 -tw-translate-y-1/2 tw-transform tw-text-muted"}));var l4=N(U());var gi=N(U(),1);var xOr=!!(typeof window<"u"&&window.document&&window.document.createElement);function SL(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var aot=N(U(),1);function sot(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function c_e(...t){return e=>{let n=!1,r=t.map(o=>{let i=sot(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():sot(t[o],null)}}}}function s4(...t){return aot.useCallback(c_e(...t),t)}var Hv=N(U(),1),lot=N(Ve(),1);function cot(t,e=[]){let n=[];function r(i,s){let a=Hv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Hv.useMemo(()=>m,Object.values(m));return(0,lot.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Hv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Hv.createContext(s));return function(a){let l=a?.[t]||i;return Hv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,ZGt(o,...e)]}function ZGt(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Hv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var u_e=N(U(),1);var uot=N(U(),1),jP=globalThis?.document?uot.useLayoutEffect:()=>{};var JGt=u_e[" useId ".trim().toString()]||(()=>{}),XGt=0;function dot(t){let[e,n]=u_e.useState(JGt());return jP(()=>{t||n(r=>r??String(XGt++))},[t]),t||(e?`radix-${e}`:"")}var cd=N(U(),1);var fot=N(U(),1);function QGt(t,e){return fot.useReducer((n,r)=>e[n][r]??n,t)}var TZ=t=>{let{present:e,children:n}=t,r=e8t(e),o=typeof n=="function"?n({present:r.isPresent}):cd.Children.only(n),i=s4(r.ref,t8t(o));return typeof n=="function"||r.isPresent?cd.cloneElement(o,{ref:i}):null};TZ.displayName="Presence";function e8t(t){let[e,n]=cd.useState(),r=cd.useRef(null),o=cd.useRef(t),i=cd.useRef("none"),s=t?"mounted":"unmounted",[a,l]=QGt(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return cd.useEffect(()=>{let c=SZ(r.current);i.current=a==="mounted"?c:"none"},[a]),jP(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=SZ(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),jP(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=SZ(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=SZ(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:cd.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function SZ(t){return t?.animationName||"none"}function t8t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var pot=N(U(),1),a8t=N(yo(),1);var da=N(U(),1);var IZ=N(Ve(),1);function PZ(t){let e=n8t(t),n=da.forwardRef((r,o)=>{let{children:i,...s}=r,a=da.Children.toArray(i),l=a.find(o8t);if(l){let c=l.props.children,u=a.map(d=>d===l?da.Children.count(c)>1?da.Children.only(null):da.isValidElement(c)?c.props.children:null:d);return(0,IZ.jsx)(e,{...s,ref:o,children:da.isValidElement(c)?da.cloneElement(c,void 0,u):null})}return(0,IZ.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function n8t(t){let e=da.forwardRef((n,r)=>{let{children:o,...i}=n;if(da.isValidElement(o)){let s=s8t(o),a=i8t(i,o.props);return o.type!==da.Fragment&&(a.ref=r?c_e(r,s):s),da.cloneElement(o,a)}return da.Children.count(o)>1?da.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var r8t=Symbol("radix.slottable");function o8t(t){return da.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===r8t}function i8t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function s8t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var mot=N(Ve(),1),l8t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],d_e=l8t.reduce((t,e)=>{let n=PZ(`Primitive.${e}`),r=pot.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,mot.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var Yp=N(U(),1);var EZ=N(U(),1);var c8t=Yp[" useInsertionEffect ".trim().toString()]||jP;function hot({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=u8t({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=Yp.useRef(t!==void 0);Yp.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=Yp.useCallback(u=>{if(a){let d=d8t(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function u8t({defaultProp:t,onChange:e}){let[n,r]=Yp.useState(t),o=Yp.useRef(n),i=Yp.useRef(e);return c8t(()=>{i.current=e},[e]),Yp.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function d8t(t){return typeof t=="function"}var LOr=Symbol("RADIX:SYNC_STATE");var ks=N(Ve(),1),AZ="Popover",[got,XOr]=cot(AZ,[Vp]),a4=Vp(),[f8t,O_]=got(AZ),yot=t=>{let{__scopePopover:e,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=t,a=a4(e),l=gi.useRef(null),[c,u]=gi.useState(!1),[d,f]=hot({prop:r,defaultProp:o??!1,onChange:i,caller:AZ});return(0,ks.jsx)(Uv,{...a,children:(0,ks.jsx)(f8t,{scope:e,contentId:dot(),triggerRef:l,open:d,onOpenChange:f,onOpenToggle:gi.useCallback(()=>f(p=>!p),[f]),hasCustomAnchor:c,onCustomAnchorAdd:gi.useCallback(()=>u(!0),[]),onCustomAnchorRemove:gi.useCallback(()=>u(!1),[]),modal:s,children:n})})};yot.displayName=AZ;var wot="PopoverAnchor",p8t=gi.forwardRef((t,e)=>{let{__scopePopover:n,...r}=t,o=O_(wot,n),i=a4(n),{onCustomAnchorAdd:s,onCustomAnchorRemove:a}=o;return gi.useEffect(()=>(s(),()=>a()),[s,a]),(0,ks.jsx)(Bv,{...i,...r,ref:e})});p8t.displayName=wot;var vot="PopoverTrigger",xot=gi.forwardRef((t,e)=>{let{__scopePopover:n,...r}=t,o=O_(vot,n),i=a4(n),s=s4(e,o.triggerRef),a=(0,ks.jsx)(d_e.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Tot(o.open),...r,ref:s,onClick:SL(t.onClick,o.onOpenToggle)});return o.hasCustomAnchor?a:(0,ks.jsx)(Bv,{asChild:!0,...i,children:a})});xot.displayName=vot;var f_e="PopoverPortal",[m8t,h8t]=got(f_e,{forceMount:void 0}),bot=t=>{let{__scopePopover:e,forceMount:n,children:r,container:o}=t,i=O_(f_e,e);return(0,ks.jsx)(m8t,{scope:e,forceMount:n,children:(0,ks.jsx)(TZ,{present:n||i.open,children:(0,ks.jsx)(vh,{asChild:!0,container:o,children:r})})})};bot.displayName=f_e;var TL="PopoverContent",Cot=gi.forwardRef((t,e)=>{let n=h8t(TL,t.__scopePopover),{forceMount:r=n.forceMount,...o}=t,i=O_(TL,t.__scopePopover);return(0,ks.jsx)(TZ,{present:r||i.open,children:i.modal?(0,ks.jsx)(y8t,{...o,ref:e}):(0,ks.jsx)(w8t,{...o,ref:e})})});Cot.displayName=TL;var g8t=PZ("PopoverContent.RemoveScroll"),y8t=gi.forwardRef((t,e)=>{let n=O_(TL,t.__scopePopover),r=gi.useRef(null),o=s4(e,r),i=gi.useRef(!1);return gi.useEffect(()=>{let s=r.current;if(s)return I_(s)},[]),(0,ks.jsx)(jv,{as:g8t,allowPinchZoom:!0,children:(0,ks.jsx)(_ot,{...t,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:SL(t.onCloseAutoFocus,s=>{s.preventDefault(),i.current||n.triggerRef.current?.focus()}),onPointerDownOutside:SL(t.onPointerDownOutside,s=>{let a=s.detail.originalEvent,l=a.button===0&&a.ctrlKey===!0,c=a.button===2||l;i.current=c},{checkForDefaultPrevented:!1}),onFocusOutside:SL(t.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})})}),w8t=gi.forwardRef((t,e)=>{let n=O_(TL,t.__scopePopover),r=gi.useRef(!1),o=gi.useRef(!1);return(0,ks.jsx)(_ot,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{t.onCloseAutoFocus?.(i),i.defaultPrevented||(r.current||n.triggerRef.current?.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{t.onInteractOutside?.(i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));let s=i.target;n.triggerRef.current?.contains(s)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),_ot=gi.forwardRef((t,e)=>{let{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onInteractOutside:u,...d}=t,f=O_(TL,n),p=a4(n);return x_(),(0,ks.jsx)(Dv,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:(0,ks.jsx)(mh,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:u,onEscapeKeyDown:a,onPointerDownOutside:l,onFocusOutside:c,onDismiss:()=>f.onOpenChange(!1),children:(0,ks.jsx)(__,{"data-state":Tot(f.open),role:"dialog",id:f.contentId,...p,...d,ref:e,style:{...d.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),Sot="PopoverClose",v8t=gi.forwardRef((t,e)=>{let{__scopePopover:n,...r}=t,o=O_(Sot,n);return(0,ks.jsx)(d_e.button,{type:"button",...r,ref:e,onClick:SL(t.onClick,()=>o.onOpenChange(!1))})});v8t.displayName=Sot;var x8t="PopoverArrow",b8t=gi.forwardRef((t,e)=>{let{__scopePopover:n,...r}=t,o=a4(n);return(0,ks.jsx)(S_,{...o,...r,ref:e})});b8t.displayName=x8t;function Tot(t){return t?"open":"closed"}var Iot=yot;var Pot=xot,Eot=bot,p_e=Cot;var Aot=require("obsidian");Kt();var R_=Iot,L_=Pot;var Kv=l4.forwardRef(({className:t,align:e="center",sideOffset:n=4,container:r,...o},i)=>l4.createElement(Eot,{container:r??activeDocument.body},l4.createElement(p_e,{ref:i,align:e,sideOffset:n,hideWhenDetached:Aot.Platform.isMobile,className:oe("tw-z-popover tw-w-72 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-primary tw-p-4 tw-text-normal tw-shadow-md tw-outline-none data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[side=bottom]:tw-slide-in-from-top-2 data-[side=left]:tw-slide-in-from-right-2 data-[side=right]:tw-slide-in-from-left-2 data-[side=top]:tw-slide-in-from-bottom-2",t),...o})));Kv.displayName=p_e.displayName;var _y=N(U());var tn=N(U(),1);var Oot=N(U(),1),E8t=N(yo(),1);var fa=N(U(),1);var Mot=N(U(),1);function kot(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function m_e(...t){return e=>{let n=!1,r=t.map(o=>{let i=kot(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():kot(t[o],null)}}}}function qv(...t){return Mot.useCallback(m_e(...t),t)}var kZ=N(Ve(),1);function Not(t){let e=_8t(t),n=fa.forwardRef((r,o)=>{let{children:i,...s}=r,a=fa.Children.toArray(i),l=a.find(T8t);if(l){let c=l.props.children,u=a.map(d=>d===l?fa.Children.count(c)>1?fa.Children.only(null):fa.isValidElement(c)?c.props.children:null:d);return(0,kZ.jsx)(e,{...s,ref:o,children:fa.isValidElement(c)?fa.cloneElement(c,void 0,u):null})}return(0,kZ.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function _8t(t){let e=fa.forwardRef((n,r)=>{let{children:o,...i}=n;if(fa.isValidElement(o)){let s=P8t(o),a=I8t(i,o.props);return o.type!==fa.Fragment&&(a.ref=r?m_e(r,s):s),fa.cloneElement(o,a)}return fa.Children.count(o)>1?fa.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var S8t=Symbol("radix.slottable");function T8t(t){return fa.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===S8t}function I8t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function P8t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Rot=N(Ve(),1),A8t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],IL=A8t.reduce((t,e)=>{let n=Not(`Primitive.${e}`),r=Oot.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,Rot.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var ud=N(U(),1);var Lot=N(U(),1),c4=globalThis?.document?Lot.useLayoutEffect:()=>{};var Dot=N(U(),1);function k8t(t,e){return Dot.useReducer((n,r)=>e[n][r]??n,t)}var PL=t=>{let{present:e,children:n}=t,r=M8t(e),o=typeof n=="function"?n({present:r.isPresent}):ud.Children.only(n),i=qv(r.ref,N8t(o));return typeof n=="function"||r.isPresent?ud.cloneElement(o,{ref:i}):null};PL.displayName="Presence";function M8t(t){let[e,n]=ud.useState(),r=ud.useRef(null),o=ud.useRef(t),i=ud.useRef("none"),s=t?"mounted":"unmounted",[a,l]=k8t(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return ud.useEffect(()=>{let c=MZ(r.current);i.current=a==="mounted"?c:"none"},[a]),c4(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=MZ(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),c4(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=MZ(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=MZ(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:ud.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function MZ(t){return t?.animationName||"none"}function N8t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Gv=N(U(),1),$ot=N(Ve(),1);function Fot(t,e=[]){let n=[];function r(i,s){let a=Gv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Gv.useMemo(()=>m,Object.values(m));return(0,$ot.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Gv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Gv.createContext(s));return function(a){let l=a?.[t]||i;return Gv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,O8t(o,...e)]}function O8t(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Gv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var EL=N(U(),1);function D_(t){let e=EL.useRef(t);return EL.useEffect(()=>{e.current=t}),EL.useMemo(()=>(...n)=>e.current?.(...n),[])}var NZ=N(U(),1),R8t=N(Ve(),1),L8t=NZ.createContext(void 0);function Uot(t){let e=NZ.useContext(L8t);return t||e||"ltr"}function $_(t,[e,n]){return Math.min(n,Math.max(e,t))}var gRr=!!(typeof window<"u"&&window.document&&window.document.createElement);function F_(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var zot=N(U(),1),no=N(Ve(),1);function D8t(t,e){return zot.useReducer((n,r)=>e[n][r]??n,t)}var h_e="ScrollArea",[jot,PRr]=Fot(h_e),[$8t,Zp]=jot(h_e),Vot=tn.forwardRef((t,e)=>{let{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=t,[a,l]=tn.useState(null),[c,u]=tn.useState(null),[d,f]=tn.useState(null),[p,m]=tn.useState(null),[h,g]=tn.useState(null),[y,w]=tn.useState(0),[v,x]=tn.useState(0),[b,_]=tn.useState(!1),[T,S]=tn.useState(!1),P=qv(e,O=>l(O)),A=Uot(o);return(0,no.jsx)($8t,{scope:n,type:r,dir:A,scrollHideDelay:i,scrollArea:a,viewport:c,onViewportChange:u,content:d,onContentChange:f,scrollbarX:p,onScrollbarXChange:m,scrollbarXEnabled:b,onScrollbarXEnabledChange:_,scrollbarY:h,onScrollbarYChange:g,scrollbarYEnabled:T,onScrollbarYEnabledChange:S,onCornerWidthChange:w,onCornerHeightChange:x,children:(0,no.jsx)(IL.div,{dir:A,...s,ref:P,style:{position:"relative","--radix-scroll-area-corner-width":y+"px","--radix-scroll-area-corner-height":v+"px",...t.style}})})});Vot.displayName=h_e;var Wot="ScrollAreaViewport",Hot=tn.forwardRef((t,e)=>{let{__scopeScrollArea:n,children:r,nonce:o,...i}=t,s=Zp(Wot,n),a=tn.useRef(null),l=qv(e,a,s.onViewportChange);return(0,no.jsxs)(no.Fragment,{children:[(0,no.jsx)("style",{dangerouslySetInnerHTML:{__html:"[data-radix-scroll-area-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-scroll-area-viewport]::-webkit-scrollbar{display:none}"},nonce:o}),(0,no.jsx)(IL.div,{"data-radix-scroll-area-viewport":"",...i,ref:l,style:{overflowX:s.scrollbarXEnabled?"scroll":"hidden",overflowY:s.scrollbarYEnabled?"scroll":"hidden",...t.style},children:(0,no.jsx)("div",{ref:s.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});Hot.displayName=Wot;var Cy="ScrollAreaScrollbar",LZ=tn.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=Zp(Cy,t.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,a=t.orientation==="horizontal";return tn.useEffect(()=>(a?i(!0):s(!0),()=>{a?i(!1):s(!1)}),[a,i,s]),o.type==="hover"?(0,no.jsx)(F8t,{...r,ref:e,forceMount:n}):o.type==="scroll"?(0,no.jsx)(U8t,{...r,ref:e,forceMount:n}):o.type==="auto"?(0,no.jsx)(Kot,{...r,ref:e,forceMount:n}):o.type==="always"?(0,no.jsx)(g_e,{...r,ref:e}):null});LZ.displayName=Cy;var F8t=tn.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=Zp(Cy,t.__scopeScrollArea),[i,s]=tn.useState(!1);return tn.useEffect(()=>{let a=o.scrollArea,l=0;if(a){let c=()=>{window.clearTimeout(l),s(!0)},u=()=>{l=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return a.addEventListener("pointerenter",c),a.addEventListener("pointerleave",u),()=>{window.clearTimeout(l),a.removeEventListener("pointerenter",c),a.removeEventListener("pointerleave",u)}}},[o.scrollArea,o.scrollHideDelay]),(0,no.jsx)(PL,{present:n||i,children:(0,no.jsx)(Kot,{"data-state":i?"visible":"hidden",...r,ref:e})})}),U8t=tn.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=Zp(Cy,t.__scopeScrollArea),i=t.orientation==="horizontal",s=$Z(()=>l("SCROLL_END"),100),[a,l]=D8t("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return tn.useEffect(()=>{if(a==="idle"){let c=window.setTimeout(()=>l("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(c)}},[a,o.scrollHideDelay,l]),tn.useEffect(()=>{let c=o.viewport,u=i?"scrollLeft":"scrollTop";if(c){let d=c[u],f=()=>{let p=c[u];d!==p&&(l("SCROLL"),s()),d=p};return c.addEventListener("scroll",f),()=>c.removeEventListener("scroll",f)}},[o.viewport,i,l,s]),(0,no.jsx)(PL,{present:n||a!=="hidden",children:(0,no.jsx)(g_e,{"data-state":a==="hidden"?"hidden":"visible",...r,ref:e,onPointerEnter:F_(t.onPointerEnter,()=>l("POINTER_ENTER")),onPointerLeave:F_(t.onPointerLeave,()=>l("POINTER_LEAVE"))})})}),Kot=tn.forwardRef((t,e)=>{let n=Zp(Cy,t.__scopeScrollArea),{forceMount:r,...o}=t,[i,s]=tn.useState(!1),a=t.orientation==="horizontal",l=$Z(()=>{if(n.viewport){let c=n.viewport.offsetWidth<n.viewport.scrollWidth,u=n.viewport.offsetHeight<n.viewport.scrollHeight;s(a?c:u)}},10);return AL(n.viewport,l),AL(n.content,l),(0,no.jsx)(PL,{present:r||i,children:(0,no.jsx)(g_e,{"data-state":i?"visible":"hidden",...o,ref:e})})}),g_e=tn.forwardRef((t,e)=>{let{orientation:n="vertical",...r}=t,o=Zp(Cy,t.__scopeScrollArea),i=tn.useRef(null),s=tn.useRef(0),[a,l]=tn.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),c=Zot(a.viewport,a.content),u={...r,sizes:a,onSizesChange:l,hasThumb:c>0&&c<1,onThumbChange:f=>i.current=f,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:f=>s.current=f};function d(f,p){return H8t(f,s.current,a,p)}return n==="horizontal"?(0,no.jsx)(B8t,{...u,ref:e,onThumbPositionChange:()=>{if(o.viewport&&i.current){let f=o.viewport.scrollLeft,p=Bot(f,a,o.dir);i.current.style.transform=`translate3d(${p}px, 0, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollLeft=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollLeft=d(f,o.dir))}}):n==="vertical"?(0,no.jsx)(z8t,{...u,ref:e,onThumbPositionChange:()=>{if(o.viewport&&i.current){let f=o.viewport.scrollTop,p=Bot(f,a);i.current.style.transform=`translate3d(0, ${p}px, 0)`}},onWheelScroll:f=>{o.viewport&&(o.viewport.scrollTop=f)},onDragScroll:f=>{o.viewport&&(o.viewport.scrollTop=d(f))}}):null}),B8t=tn.forwardRef((t,e)=>{let{sizes:n,onSizesChange:r,...o}=t,i=Zp(Cy,t.__scopeScrollArea),[s,a]=tn.useState(),l=tn.useRef(null),c=qv(e,l,i.onScrollbarXChange);return tn.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),(0,no.jsx)(Got,{"data-orientation":"horizontal",...o,ref:c,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":DZ(n)+"px",...t.style},onThumbPointerDown:u=>t.onThumbPointerDown(u.x),onDragScroll:u=>t.onDragScroll(u.x),onWheelScroll:(u,d)=>{if(i.viewport){let f=i.viewport.scrollLeft+u.deltaX;t.onWheelScroll(f),Xot(f,d)&&u.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:l.current.clientWidth,paddingStart:RZ(s.paddingLeft),paddingEnd:RZ(s.paddingRight)}})}})}),z8t=tn.forwardRef((t,e)=>{let{sizes:n,onSizesChange:r,...o}=t,i=Zp(Cy,t.__scopeScrollArea),[s,a]=tn.useState(),l=tn.useRef(null),c=qv(e,l,i.onScrollbarYChange);return tn.useEffect(()=>{l.current&&a(getComputedStyle(l.current))},[l]),(0,no.jsx)(Got,{"data-orientation":"vertical",...o,ref:c,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":DZ(n)+"px",...t.style},onThumbPointerDown:u=>t.onThumbPointerDown(u.y),onDragScroll:u=>t.onDragScroll(u.y),onWheelScroll:(u,d)=>{if(i.viewport){let f=i.viewport.scrollTop+u.deltaY;t.onWheelScroll(f),Xot(f,d)&&u.preventDefault()}},onResize:()=>{l.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:l.current.clientHeight,paddingStart:RZ(s.paddingTop),paddingEnd:RZ(s.paddingBottom)}})}})}),[j8t,qot]=jot(Cy),Got=tn.forwardRef((t,e)=>{let{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:a,onThumbPositionChange:l,onDragScroll:c,onWheelScroll:u,onResize:d,...f}=t,p=Zp(Cy,n),[m,h]=tn.useState(null),g=qv(e,P=>h(P)),y=tn.useRef(null),w=tn.useRef(""),v=p.viewport,x=r.content-r.viewport,b=D_(u),_=D_(l),T=$Z(d,10);function S(P){if(y.current){let A=P.clientX-y.current.left,O=P.clientY-y.current.top;c({x:A,y:O})}}return tn.useEffect(()=>{let P=A=>{let O=A.target;m?.contains(O)&&b(A,x)};return document.addEventListener("wheel",P,{passive:!1}),()=>document.removeEventListener("wheel",P,{passive:!1})},[v,m,x,b]),tn.useEffect(_,[r,_]),AL(m,T),AL(p.content,T),(0,no.jsx)(j8t,{scope:n,scrollbar:m,hasThumb:o,onThumbChange:D_(i),onThumbPointerUp:D_(s),onThumbPositionChange:_,onThumbPointerDown:D_(a),children:(0,no.jsx)(IL.div,{...f,ref:g,style:{position:"absolute",...f.style},onPointerDown:F_(t.onPointerDown,P=>{P.button===0&&(P.target.setPointerCapture(P.pointerId),y.current=m.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",p.viewport&&(p.viewport.style.scrollBehavior="auto"),S(P))}),onPointerMove:F_(t.onPointerMove,S),onPointerUp:F_(t.onPointerUp,P=>{let A=P.target;A.hasPointerCapture(P.pointerId)&&A.releasePointerCapture(P.pointerId),document.body.style.webkitUserSelect=w.current,p.viewport&&(p.viewport.style.scrollBehavior=""),y.current=null})})})}),OZ="ScrollAreaThumb",y_e=tn.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=qot(OZ,t.__scopeScrollArea);return(0,no.jsx)(PL,{present:n||o.hasThumb,children:(0,no.jsx)(V8t,{ref:e,...r})})}),V8t=tn.forwardRef((t,e)=>{let{__scopeScrollArea:n,style:r,...o}=t,i=Zp(OZ,n),s=qot(OZ,n),{onThumbPositionChange:a}=s,l=qv(e,d=>s.onThumbChange(d)),c=tn.useRef(void 0),u=$Z(()=>{c.current&&(c.current(),c.current=void 0)},100);return tn.useEffect(()=>{let d=i.viewport;if(d){let f=()=>{if(u(),!c.current){let p=K8t(d,a);c.current=p,a()}};return a(),d.addEventListener("scroll",f),()=>d.removeEventListener("scroll",f)}},[i.viewport,u,a]),(0,no.jsx)(IL.div,{"data-state":s.hasThumb?"visible":"hidden",...o,ref:l,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:F_(t.onPointerDownCapture,d=>{let p=d.target.getBoundingClientRect(),m=d.clientX-p.left,h=d.clientY-p.top;s.onThumbPointerDown({x:m,y:h})}),onPointerUp:F_(t.onPointerUp,s.onThumbPointerUp)})});y_e.displayName=OZ;var w_e="ScrollAreaCorner",Yot=tn.forwardRef((t,e)=>{let n=Zp(w_e,t.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?(0,no.jsx)(W8t,{...t,ref:e}):null});Yot.displayName=w_e;var W8t=tn.forwardRef((t,e)=>{let{__scopeScrollArea:n,...r}=t,o=Zp(w_e,n),[i,s]=tn.useState(0),[a,l]=tn.useState(0),c=!!(i&&a);return AL(o.scrollbarX,()=>{let u=o.scrollbarX?.offsetHeight||0;o.onCornerHeightChange(u),l(u)}),AL(o.scrollbarY,()=>{let u=o.scrollbarY?.offsetWidth||0;o.onCornerWidthChange(u),s(u)}),c?(0,no.jsx)(IL.div,{...r,ref:e,style:{width:i,height:a,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...t.style}}):null});function RZ(t){return t?parseInt(t,10):0}function Zot(t,e){let n=t/e;return isNaN(n)?0:n}function DZ(t){let e=Zot(t.viewport,t.content),n=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,r=(t.scrollbar.size-n)*e;return Math.max(r,18)}function H8t(t,e,n,r="ltr"){let o=DZ(n),i=o/2,s=e||i,a=o-s,l=n.scrollbar.paddingStart+s,c=n.scrollbar.size-n.scrollbar.paddingEnd-a,u=n.content-n.viewport,d=r==="ltr"?[0,u]:[u*-1,0];return Jot([l,c],d)(t)}function Bot(t,e,n="ltr"){let r=DZ(e),o=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,i=e.scrollbar.size-o,s=e.content-e.viewport,a=i-r,l=n==="ltr"?[0,s]:[s*-1,0],c=$_(t,l);return Jot([0,s],[0,a])(c)}function Jot(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];let r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}function Xot(t,e){return t>0&&t<e}var K8t=(t,e=()=>{})=>{let n={left:t.scrollLeft,top:t.scrollTop},r=0;return function o(){let i={left:t.scrollLeft,top:t.scrollTop},s=n.left!==i.left,a=n.top!==i.top;(s||a)&&e(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function $Z(t,e){let n=D_(t),r=tn.useRef(0);return tn.useEffect(()=>()=>window.clearTimeout(r.current),[]),tn.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,e)},[n,e])}function AL(t,e){let n=D_(e);c4(()=>{let r=0;if(t){let o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(t),()=>{window.cancelAnimationFrame(r),o.unobserve(t)}}},[t,n])}var v_e=Vot,Qot=Hot;var eit=Yot;Kt();var Sy=_y.forwardRef(({className:t,children:e,...n},r)=>_y.createElement(v_e,{ref:r,className:oe("tw-relative tw-overflow-hidden",t),...n},_y.createElement(Qot,{className:"tw-size-full tw-rounded-[inherit] [&>div:first-child]:!tw-block"},e),_y.createElement(tit,null),_y.createElement(eit,null)));Sy.displayName=v_e.displayName;var tit=_y.forwardRef(({className:t,orientation:e="vertical",...n},r)=>_y.createElement(LZ,{ref:r,orientation:e,className:oe("tw-flex tw-touch-none tw-select-none tw-transition-colors",e==="vertical"&&"tw-h-full tw-w-2.5 tw-border-l tw-border-l-transparent tw-p-px",e==="horizontal"&&"tw-h-2.5 tw-flex-col tw-border-t tw-border-t-transparent tw-p-px",t),...n},_y.createElement(y_e,{className:"tw-relative tw-flex-1 tw-rounded-full tw-bg-[var(--background-modifier-border)]"})));tit.displayName=LZ.displayName;Kt();ye();Se();Ky();var nit=require("obsidian"),FZ=50;function rit({children:t,chatHistory:e,onUpdateTitle:n,onDeleteChat:r,onLoadChat:o,onOpenSourceFile:i}){let[s,a]=(0,Ot.useState)(""),[l,c]=(0,Ot.useState)(null),[u,d]=(0,Ot.useState)(""),[f,p]=(0,Ot.useState)(!1),[m,h]=(0,Ot.useState)(null),[g,y]=(0,Ot.useState)(FZ),w=(0,Ot.useRef)(null),v=(0,Ot.useRef)(null),x=nit.Platform.isMobile,b=Ht(),_=(0,Ot.useMemo)(()=>s.trim()?e.filter(V=>V.title.toLowerCase().includes(s.toLowerCase())):e,[e,s]),T=(0,Ot.useMemo)(()=>Xh(_,b.chatHistorySortStrategy,{getName:V=>V.title,getCreatedAtMs:V=>V.createdAt.getTime(),getLastUsedAtMs:V=>V.lastAccessedAt.getTime()}),[_,b.chatHistorySortStrategy]);(0,Ot.useLayoutEffect)(()=>{f&&y(FZ)},[f,s]);let S=(0,Ot.useMemo)(()=>T.slice(0,g),[T,g]),P=(0,Ot.useRef)({displayCount:FZ,totalCount:0});(0,Ot.useEffect)(()=>{P.current={displayCount:g,totalCount:T.length}},[g,T.length]);let A=(0,Ot.useCallback)(V=>{if(w.current&&(w.current.disconnect(),w.current=null),!V)return;let H=new IntersectionObserver(te=>{if(te[0].isIntersecting){let{displayCount:fe,totalCount:me}=P.current;fe<me&&y(j=>Math.min(j+FZ,me))}},{threshold:.1});H.observe(V),w.current=H},[]),O=(0,Ot.useMemo)(()=>{let V=b.chatHistorySortStrategy;if(V==="name")return[{key:"All",label:"All",chats:S,priority:0}];let H=[],te=new Map,fe=new Date;return S.forEach(me=>{let j=V==="recent"?me.lastAccessedAt:me.createdAt,G=fe.getTime()-j.getTime(),J=Math.floor(G/(1e3*60*60*24)),M,E;if(J===0)M="Today",E=0;else if(J===1)M="Yesterday",E=1;else if(J<7)M=`${J}d ago`,E=2+J;else if(J<30){let R=Math.floor(J/7);M=R===1?"1w ago":`${R}w ago`,E=10+R}else{let R=Math.floor(J/30);M=R===1?"1m ago":`${R}m ago`,E=50+R}te.has(M)||(te.set(M,[]),H.push({key:M,label:M,chats:te.get(M),priority:E})),te.get(M).push(me)}),H.sort((me,j)=>me.priority-j.priority)},[b.chatHistorySortStrategy,S]),D=(V,H)=>{c(V),d(H)},$=async()=>{if(l&&u.trim())try{await n(l,u.trim()),c(null),d("")}catch(V){z("Error updating title:",V);return}else c(null),d("")},B=()=>{c(null),d("")};(0,Ot.useEffect)(()=>()=>{v.current&&window.clearTimeout(v.current)},[]);let W=async V=>{if(m===V)try{await r(V),h(null)}catch(H){z("Error deleting chat:",H),h(null)}else v.current&&window.clearTimeout(v.current),h(V),v.current=window.setTimeout(()=>{h(null),v.current=null},3e3)},F=()=>{h(null)},Z=async V=>{o&&await o(V),p(!1)};return Ot.default.createElement(R_,{open:f,onOpenChange:p},Ot.default.createElement(L_,{asChild:!0},t),Ot.default.createElement(Kv,{className:"tw-w-80 tw-p-0",align:"end",side:"top"},Ot.default.createElement("div",{className:"tw-flex tw-max-h-[400px] tw-flex-col"},Ot.default.createElement("div",{className:"tw-shrink-0 tw-border-b tw-p-1"},Ot.default.createElement(_L,{value:s,onChange:a})),Ot.default.createElement(Sy,{className:"tw-min-h-[150px] tw-flex-1 tw-overflow-y-auto"},Ot.default.createElement("div",{className:"tw-p-2"},O.length===0?Ot.default.createElement("div",{className:"tw-py-8 tw-text-center tw-text-muted"},s?"No matching chat history found.":"No chat history"):Ot.default.createElement(Ot.default.Fragment,null,O.map(V=>Ot.default.createElement("div",{key:V.key,className:"tw-mb-3 tw-border-x-[0px] tw-border-b tw-border-t-[0px] tw-border-border tw-pb-2",style:{borderBottomStyle:"solid"}},Ot.default.createElement("div",{className:"tw-mb-2 tw-px-2 tw-text-xs tw-font-medium tw-tracking-wider tw-text-muted"},V.label),Ot.default.createElement("div",{className:"tw-space-y-1"},V.chats.map(H=>Ot.default.createElement(G8t,{key:H.id,chat:H,isEditing:l===H.id,editingTitle:u,onEditingTitleChange:d,onStartEdit:D,onSaveEdit:$,onCancelEdit:B,onDelete:W,onCancelDelete:F,onLoadChat:Z,onOpenSourceFile:i,isMobile:x,confirmDeleteId:m}))))),Ot.default.createElement("div",{ref:A,className:"tw-h-1"}),g<T.length?Ot.default.createElement("div",{className:"tw-py-2 tw-text-center tw-text-xs tw-text-muted"},"Showing ",g," of ",T.length," \u2014 scroll for more"):null))))))}function G8t({chat:t,isEditing:e,editingTitle:n,onEditingTitleChange:r,onStartEdit:o,onSaveEdit:i,onCancelEdit:s,onDelete:a,onCancelDelete:l,onLoadChat:c,onOpenSourceFile:u,isMobile:d,confirmDeleteId:f}){return e?Ot.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-rounded-md tw-p-2"},Ot.default.createElement(WA,{className:"tw-size-3 tw-shrink-0 tw-text-muted"}),Ot.default.createElement(Xn,{value:n,onChange:p=>r(p.target.value),className:"!tw-h-6 tw-flex-1",autoFocus:!0,onKeyDown:p=>{p.key==="Enter"?i():p.key==="Escape"&&s()}}),Ot.default.createElement(X,{size:"sm",variant:"ghost",onClick:i,className:"tw-size-5 tw-p-0"},Ot.default.createElement(Ro,{className:"tw-size-3"})),Ot.default.createElement(X,{size:"sm",variant:"ghost",onClick:s,className:"tw-size-5 tw-p-0"},Ot.default.createElement(Sn,{className:"tw-size-3"}))):Ot.default.createElement("div",{className:oe("tw-group tw-flex tw-cursor-pointer tw-items-center tw-gap-2 tw-rounded-md tw-p-1 tw-transition-colors hover:tw-bg-modifier-hover"),onClick:()=>c(t.id)},Ot.default.createElement(WA,{className:"tw-size-3 tw-shrink-0 tw-text-muted"}),Ot.default.createElement("div",{className:"tw-min-w-0 tw-flex-1"},Ot.default.createElement("span",{className:"tw-block tw-truncate tw-text-sm tw-font-medium tw-text-normal"},t.title)),Ot.default.createElement("div",{className:oe("tw-flex tw-shrink-0 tw-items-center tw-gap-1.5 tw-transition-opacity",d?"tw-flex":"tw-hidden group-hover:tw-flex")},f===t.id?Ot.default.createElement(Ot.default.Fragment,null,Ot.default.createElement(X,{size:"sm",variant:"ghost",onClick:p=>{p.stopPropagation(),a(t.id)},className:"tw-size-5 tw-p-0 tw-text-error hover:tw-text-error",title:"Confirm Delete"},Ot.default.createElement(Ro,{className:"tw-size-3"})),Ot.default.createElement(X,{size:"sm",variant:"ghost",onClick:p=>{p.stopPropagation(),l()},className:"tw-size-5 tw-p-0",title:"Cancel deletion"},Ot.default.createElement(Sn,{className:"tw-size-3"}))):Ot.default.createElement(Ot.default.Fragment,null,Ot.default.createElement(X,{size:"sm",variant:"ghost",onClick:p=>{p.stopPropagation(),u&&u(t.id)},className:"tw-size-5 tw-p-0",title:"Open the source file"},Ot.default.createElement(Oc,{className:"tw-size-4"})),Ot.default.createElement(X,{size:"sm",variant:"ghost",onClick:p=>{p.stopPropagation(),o(t.id,t.title)},className:"tw-size-5 tw-p-0"},Ot.default.createElement(Rc,{className:"tw-size-3"})),Ot.default.createElement(X,{size:"sm",variant:"ghost",onClick:p=>{p.stopPropagation(),a(t.id)},className:"tw-size-5 tw-p-0 tw-text-error hover:tw-text-error",title:"delete file"},Ot.default.createElement(ka,{className:"tw-size-3"})))))}vt();var VP=N(U()),oit=({tokenCount:t})=>t==null?null:VP.default.createElement(cn,null,VP.default.createElement(un,{asChild:!0},VP.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-text-sm tw-text-faint"},VP.default.createElement(f$,{className:"tw-size-3"}),VP.default.createElement("span",null,(n=>n<1e3?"<1k":`${Math.floor(n/1e3)}k`)(t)))),VP.default.createElement(on,null,"Context used: ",t.toLocaleString()));var _t=N(U());bi();rn();var WP=N(U());Kt();vt();function Ty({options:t,placeholder:e,containerClassName:n,className:r,...o}){return WP.default.createElement("div",{className:oe("tw-group tw-relative tw-w-full",n)},WP.default.createElement("select",{className:oe("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-text-sm tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal",r),...o},e&&WP.default.createElement("option",{value:"",disabled:!0},e),t.map(i=>WP.default.createElement("option",{key:i.value,value:i.value},i.label))),WP.default.createElement("div",{className:oe("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal",o.disabled&&"tw-opacity-50")},WP.default.createElement(hr,{className:"tw-size-4"})))}var BZ=N(U());var fit=N(U(),1);var lit=N(U(),1),t9t=N(yo(),1);var pa=N(U(),1);var Y8t=N(U(),1);function iit(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function sit(...t){return e=>{let n=!1,r=t.map(o=>{let i=iit(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():iit(t[o],null)}}}}var UZ=N(Ve(),1);function ait(t){let e=Z8t(t),n=pa.forwardRef((r,o)=>{let{children:i,...s}=r,a=pa.Children.toArray(i),l=a.find(X8t);if(l){let c=l.props.children,u=a.map(d=>d===l?pa.Children.count(c)>1?pa.Children.only(null):pa.isValidElement(c)?c.props.children:null:d);return(0,UZ.jsx)(e,{...s,ref:o,children:pa.isValidElement(c)?pa.cloneElement(c,void 0,u):null})}return(0,UZ.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function Z8t(t){let e=pa.forwardRef((n,r)=>{let{children:o,...i}=n;if(pa.isValidElement(o)){let s=e9t(o),a=Q8t(i,o.props);return o.type!==pa.Fragment&&(a.ref=r?sit(r,s):s),pa.cloneElement(o,a)}return pa.Children.count(o)>1?pa.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var J8t=Symbol("radix.slottable");function X8t(t){return pa.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===J8t}function Q8t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function e9t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var cit=N(Ve(),1),n9t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],uit=n9t.reduce((t,e)=>{let n=ait(`Primitive.${e}`),r=lit.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,cit.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var pit=N(Ve(),1),r9t="Separator",dit="horizontal",o9t=["horizontal","vertical"],mit=fit.forwardRef((t,e)=>{let{decorative:n,orientation:r=dit,...o}=t,i=i9t(r)?r:dit,a=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return(0,pit.jsx)(uit.div,{"data-orientation":i,...a,...o,ref:e})});mit.displayName=r9t;function i9t(t){return o9t.includes(t)}var x_e=mit;Kt();var Jp=BZ.forwardRef(({className:t,orientation:e="horizontal",decorative:n=!0,...r},o)=>BZ.createElement(x_e,{ref:o,decorative:n,orientation:e,className:oe("tw-shrink-0 tw-bg-[var(--background-modifier-border)]",e==="horizontal"?"tw-h-px tw-w-full":"tw-h-full tw-w-px",t),...r}));Jp.displayName=x_e.displayName;vt();var Un=N(U());var kL=N(U());var Zn=({label:t,required:e=!1,error:n=!1,description:r,errorMessage:o="This field is required",children:i})=>kL.default.createElement("div",{className:"tw-space-y-2"},t&&kL.default.createElement(hi,{className:n?"tw-text-error":""},t," ",e&&kL.default.createElement("span",{className:"tw-text-error"},"*")),r&&kL.default.createElement("p",{className:"tw-text-sm tw-text-muted"},r),i,n&&kL.default.createElement("p",{className:"tw-text-xs tw-text-error"},o));var ho=N(U());var qP=N(U());var vo=N(U(),1);function HP(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var git=N(U(),1);function hit(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function b_e(...t){return e=>{let n=!1,r=t.map(o=>{let i=hit(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():hit(t[o],null)}}}}function KP(...t){return git.useCallback(b_e(...t),t)}var Yv=N(U(),1),yit=N(Ve(),1);function wit(t,e=[]){let n=[];function r(i,s){let a=Yv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Yv.useMemo(()=>m,Object.values(m));return(0,yit.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Yv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Yv.createContext(s));return function(a){let l=a?.[t]||i;return Yv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,a9t(o,...e)]}function a9t(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Yv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var Xp=N(U(),1);var vit=N(U(),1),zZ=globalThis?.document?vit.useLayoutEffect:()=>{};var jZ=N(U(),1);var l9t=Xp[" useInsertionEffect ".trim().toString()]||zZ;function xit({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=c9t({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=Xp.useRef(t!==void 0);Xp.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=Xp.useCallback(u=>{if(a){let d=u9t(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function c9t({defaultProp:t,onChange:e}){let[n,r]=Xp.useState(t),o=Xp.useRef(n),i=Xp.useRef(e);return l9t(()=>{i.current=e},[e]),Xp.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function u9t(t){return typeof t=="function"}var lLr=Symbol("RADIX:SYNC_STATE");var VZ=N(U(),1),d9t=N(Ve(),1),f9t=VZ.createContext(void 0);function bit(t){let e=VZ.useContext(f9t);return t||e||"ltr"}var WZ=N(U(),1);function Cit(t){let e=WZ.useRef({value:t,previous:t});return WZ.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var _it=N(U(),1);function Sit(t){let[e,n]=_it.useState(void 0);return zZ(()=>{if(t){n({width:t.offsetWidth,height:t.offsetHeight});let r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;let i=o[0],s,a;if("borderBoxSize"in i){let l=i.borderBoxSize,c=Array.isArray(l)?l[0]:l;s=c.inlineSize,a=c.blockSize}else s=t.offsetWidth,a=t.offsetHeight;n({width:s,height:a})});return r.observe(t,{box:"border-box"}),()=>r.unobserve(t)}else n(void 0)},[t]),e}var Iit=N(U(),1),w9t=N(yo(),1);var ma=N(U(),1);var HZ=N(Ve(),1);function Tit(t){let e=p9t(t),n=ma.forwardRef((r,o)=>{let{children:i,...s}=r,a=ma.Children.toArray(i),l=a.find(h9t);if(l){let c=l.props.children,u=a.map(d=>d===l?ma.Children.count(c)>1?ma.Children.only(null):ma.isValidElement(c)?c.props.children:null:d);return(0,HZ.jsx)(e,{...s,ref:o,children:ma.isValidElement(c)?ma.cloneElement(c,void 0,u):null})}return(0,HZ.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function p9t(t){let e=ma.forwardRef((n,r)=>{let{children:o,...i}=n;if(ma.isValidElement(o)){let s=y9t(o),a=g9t(i,o.props);return o.type!==ma.Fragment&&(a.ref=r?b_e(r,s):s),ma.cloneElement(o,a)}return ma.Children.count(o)>1?ma.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var m9t=Symbol("radix.slottable");function h9t(t){return ma.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===m9t}function g9t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function y9t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Pit=N(Ve(),1),v9t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ML=v9t.reduce((t,e)=>{let n=Tit(`Primitive.${e}`),r=Iit.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,Pit.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var ha=N(Ve(),1),Eit=["PageUp","PageDown"],Ait=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],kit={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},NL="Slider",[C_e,x9t,b9t]=w_(NL),[Mit,ELr]=wit(NL,[b9t]),[C9t,KZ]=Mit(NL),Nit=vo.forwardRef((t,e)=>{let{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:a=!1,minStepsBetweenThumbs:l=0,defaultValue:c=[r],value:u,onValueChange:d=()=>{},onValueCommit:f=()=>{},inverted:p=!1,form:m,...h}=t,g=vo.useRef(new Set),y=vo.useRef(0),v=s==="horizontal"?_9t:S9t,[x=[],b]=xit({prop:u,defaultProp:c,onChange:O=>{[...g.current][y.current]?.focus(),d(O)}}),_=vo.useRef(x);function T(O){let D=A9t(x,O);A(O,D)}function S(O){A(O,y.current)}function P(){let O=_.current[y.current];x[y.current]!==O&&f(x)}function A(O,D,{commit:$}={commit:!1}){let B=O9t(i),W=R9t(Math.round((O-r)/i)*i+r,B),F=$_(W,[r,o]);b((Z=[])=>{let V=P9t(Z,F,D);if(N9t(V,l*i)){y.current=V.indexOf(F);let H=String(V)!==String(Z);return H&&$&&f(V),H?V:Z}else return Z})}return(0,ha.jsx)(C9t,{scope:t.__scopeSlider,name:n,disabled:a,min:r,max:o,valueIndexToChangeRef:y,thumbs:g.current,values:x,orientation:s,form:m,children:(0,ha.jsx)(C_e.Provider,{scope:t.__scopeSlider,children:(0,ha.jsx)(C_e.Slot,{scope:t.__scopeSlider,children:(0,ha.jsx)(v,{"aria-disabled":a,"data-disabled":a?"":void 0,...h,ref:e,onPointerDown:HP(h.onPointerDown,()=>{a||(_.current=x)}),min:r,max:o,inverted:p,onSlideStart:a?void 0:T,onSlideMove:a?void 0:S,onSlideEnd:a?void 0:P,onHomeKeyDown:()=>!a&&A(r,0,{commit:!0}),onEndKeyDown:()=>!a&&A(o,x.length-1,{commit:!0}),onStepKeyDown:({event:O,direction:D})=>{if(!a){let W=Eit.includes(O.key)||O.shiftKey&&Ait.includes(O.key)?10:1,F=y.current,Z=x[F],V=i*W*D;A(Z+V,F,{commit:!0})}}})})})})});Nit.displayName=NL;var[Oit,Rit]=Mit(NL,{startEdge:"left",endEdge:"right",size:"width",direction:1}),_9t=vo.forwardRef((t,e)=>{let{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:a,onSlideEnd:l,onStepKeyDown:c,...u}=t,[d,f]=vo.useState(null),p=KP(e,v=>f(v)),m=vo.useRef(void 0),h=bit(o),g=h==="ltr",y=g&&!i||!g&&i;function w(v){let x=m.current||d.getBoundingClientRect(),b=[0,x.width],T=T_e(b,y?[n,r]:[r,n]);return m.current=x,T(v-x.left)}return(0,ha.jsx)(Oit,{scope:t.__scopeSlider,startEdge:y?"left":"right",endEdge:y?"right":"left",direction:y?1:-1,size:"width",children:(0,ha.jsx)(Lit,{dir:h,"data-orientation":"horizontal",...u,ref:p,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:v=>{let x=w(v.clientX);s?.(x)},onSlideMove:v=>{let x=w(v.clientX);a?.(x)},onSlideEnd:()=>{m.current=void 0,l?.()},onStepKeyDown:v=>{let b=kit[y?"from-left":"from-right"].includes(v.key);c?.({event:v,direction:b?-1:1})}})})}),S9t=vo.forwardRef((t,e)=>{let{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:a,onStepKeyDown:l,...c}=t,u=vo.useRef(null),d=KP(e,u),f=vo.useRef(void 0),p=!o;function m(h){let g=f.current||u.current.getBoundingClientRect(),y=[0,g.height],v=T_e(y,p?[r,n]:[n,r]);return f.current=g,v(h-g.top)}return(0,ha.jsx)(Oit,{scope:t.__scopeSlider,startEdge:p?"bottom":"top",endEdge:p?"top":"bottom",size:"height",direction:p?1:-1,children:(0,ha.jsx)(Lit,{"data-orientation":"vertical",...c,ref:d,style:{...c.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:h=>{let g=m(h.clientY);i?.(g)},onSlideMove:h=>{let g=m(h.clientY);s?.(g)},onSlideEnd:()=>{f.current=void 0,a?.()},onStepKeyDown:h=>{let y=kit[p?"from-bottom":"from-top"].includes(h.key);l?.({event:h,direction:y?-1:1})}})})}),Lit=vo.forwardRef((t,e)=>{let{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:a,onStepKeyDown:l,...c}=t,u=KZ(NL,n);return(0,ha.jsx)(ML.span,{...c,ref:e,onKeyDown:HP(t.onKeyDown,d=>{d.key==="Home"?(s(d),d.preventDefault()):d.key==="End"?(a(d),d.preventDefault()):Eit.concat(Ait).includes(d.key)&&(l(d),d.preventDefault())}),onPointerDown:HP(t.onPointerDown,d=>{let f=d.target;f.setPointerCapture(d.pointerId),d.preventDefault(),u.thumbs.has(f)?f.focus():r(d)}),onPointerMove:HP(t.onPointerMove,d=>{d.target.hasPointerCapture(d.pointerId)&&o(d)}),onPointerUp:HP(t.onPointerUp,d=>{let f=d.target;f.hasPointerCapture(d.pointerId)&&(f.releasePointerCapture(d.pointerId),i(d))})})}),Dit="SliderTrack",$it=vo.forwardRef((t,e)=>{let{__scopeSlider:n,...r}=t,o=KZ(Dit,n);return(0,ha.jsx)(ML.span,{"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation,...r,ref:e})});$it.displayName=Dit;var __e="SliderRange",Fit=vo.forwardRef((t,e)=>{let{__scopeSlider:n,...r}=t,o=KZ(__e,n),i=Rit(__e,n),s=vo.useRef(null),a=KP(e,s),l=o.values.length,c=o.values.map(f=>zit(f,o.min,o.max)),u=l>1?Math.min(...c):0,d=100-Math.max(...c);return(0,ha.jsx)(ML.span,{"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0,...r,ref:a,style:{...t.style,[i.startEdge]:u+"%",[i.endEdge]:d+"%"}})});Fit.displayName=__e;var S_e="SliderThumb",Uit=vo.forwardRef((t,e)=>{let n=x9t(t.__scopeSlider),[r,o]=vo.useState(null),i=KP(e,a=>o(a)),s=vo.useMemo(()=>r?n().findIndex(a=>a.ref.current===r):-1,[n,r]);return(0,ha.jsx)(T9t,{...t,ref:i,index:s})}),T9t=vo.forwardRef((t,e)=>{let{__scopeSlider:n,index:r,name:o,...i}=t,s=KZ(S_e,n),a=Rit(S_e,n),[l,c]=vo.useState(null),u=KP(e,w=>c(w)),d=l?s.form||!!l.closest("form"):!0,f=Sit(l),p=s.values[r],m=p===void 0?0:zit(p,s.min,s.max),h=E9t(r,s.values.length),g=f?.[a.size],y=g?k9t(g,m,a.direction):0;return vo.useEffect(()=>{if(l)return s.thumbs.add(l),()=>{s.thumbs.delete(l)}},[l,s.thumbs]),(0,ha.jsxs)("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[a.startEdge]:`calc(${m}% + ${y}px)`},children:[(0,ha.jsx)(C_e.ItemSlot,{scope:t.__scopeSlider,children:(0,ha.jsx)(ML.span,{role:"slider","aria-label":t["aria-label"]||h,"aria-valuemin":s.min,"aria-valuenow":p,"aria-valuemax":s.max,"aria-orientation":s.orientation,"data-orientation":s.orientation,"data-disabled":s.disabled?"":void 0,tabIndex:s.disabled?void 0:0,...i,ref:u,style:p===void 0?{display:"none"}:t.style,onFocus:HP(t.onFocus,()=>{s.valueIndexToChangeRef.current=r})})}),d&&(0,ha.jsx)(Bit,{name:o??(s.name?s.name+(s.values.length>1?"[]":""):void 0),form:s.form,value:p},r)]})});Uit.displayName=S_e;var I9t="RadioBubbleInput",Bit=vo.forwardRef(({__scopeSlider:t,value:e,...n},r)=>{let o=vo.useRef(null),i=KP(o,r),s=Cit(e);return vo.useEffect(()=>{let a=o.current;if(!a)return;let l=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==e&&u){let d=new Event("input",{bubbles:!0});u.call(a,e),a.dispatchEvent(d)}},[s,e]),(0,ha.jsx)(ML.input,{style:{display:"none"},...n,ref:i,defaultValue:e})});Bit.displayName=I9t;function P9t(t=[],e,n){let r=[...t];return r[n]=e,r.sort((o,i)=>o-i)}function zit(t,e,n){let i=100/(n-e)*(t-e);return $_(i,[0,100])}function E9t(t,e){return e>2?`Value ${t+1} of ${e}`:e===2?["Minimum","Maximum"][t]:void 0}function A9t(t,e){if(t.length===1)return 0;let n=t.map(o=>Math.abs(o-e)),r=Math.min(...n);return n.indexOf(r)}function k9t(t,e,n){let r=t/2,i=T_e([0,50],[0,r]);return(r-i(e)*n)*n}function M9t(t){return t.slice(0,-1).map((e,n)=>t[n+1]-e)}function N9t(t,e){if(e>0){let n=M9t(t);return Math.min(...n)>=e}return!0}function T_e(t,e){return n=>{if(t[0]===t[1]||e[0]===e[1])return e[0];let r=(e[1]-e[0])/(t[1]-t[0]);return e[0]+r*(n-t[0])}}function O9t(t){return(String(t).split(".")[1]||"").length}function R9t(t,e){let n=Math.pow(10,e);return Math.round(t*n)/n}var I_e=Nit,jit=$it,Vit=Fit,Wit=Uit;Kt();var u4=qP.forwardRef(({className:t,...e},n)=>qP.createElement(I_e,{ref:n,className:oe("tw-relative tw-flex tw-w-full tw-touch-none tw-select-none tw-items-center",t),...e},qP.createElement(jit,{className:"tw-relative tw-h-1.5 tw-w-full tw-grow tw-overflow-hidden tw-rounded-full tw-border tw-border-solid tw-bg-interactive-accent/20 tw-border-interactive-accent/30"},qP.createElement(Vit,{className:"tw-absolute tw-h-full tw-bg-interactive-accent"})),qP.createElement(Wit,{className:"tw-block tw-size-4 tw-rounded-full tw-border tw-bg-toggle-thumb tw-shadow tw-transition-colors focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring disabled:tw-pointer-events-none disabled:tw-opacity-50"})));u4.displayName=I_e.displayName;rn();var xo=N(U());var pt=N(U(),1),L_e=N(yo(),1);var MLr=!!(typeof window<"u"&&window.document&&window.document.createElement);function Ja(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var Kit=N(U(),1);function Hit(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function P_e(...t){return e=>{let n=!1,r=t.map(o=>{let i=Hit(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():Hit(t[o],null)}}}}function Ch(...t){return Kit.useCallback(P_e(...t),t)}var Zv=N(U(),1),qit=N(Ve(),1);function Git(t,e=[]){let n=[];function r(i,s){let a=Zv.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Zv.useMemo(()=>m,Object.values(m));return(0,qit.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Zv.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Zv.createContext(s));return function(a){let l=a?.[t]||i;return Zv.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,D9t(o,...e)]}function D9t(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Zv.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var qZ=N(U(),1),$9t=N(Ve(),1),F9t=qZ.createContext(void 0);function Yit(t){let e=qZ.useContext(F9t);return t||e||"ltr"}var E_e=N(U(),1);var Zit=N(U(),1),yf=globalThis?.document?Zit.useLayoutEffect:()=>{};var U9t=E_e[" useId ".trim().toString()]||(()=>{}),B9t=0;function GZ(t){let[e,n]=E_e.useState(U9t());return yf(()=>{t||n(r=>r??String(B9t++))},[t]),t||(e?`radix-${e}`:"")}var Jit=N(U(),1),K9t=N(yo(),1);var ga=N(U(),1);var YZ=N(Ve(),1);function ZZ(t){let e=z9t(t),n=ga.forwardRef((r,o)=>{let{children:i,...s}=r,a=ga.Children.toArray(i),l=a.find(V9t);if(l){let c=l.props.children,u=a.map(d=>d===l?ga.Children.count(c)>1?ga.Children.only(null):ga.isValidElement(c)?c.props.children:null:d);return(0,YZ.jsx)(e,{...s,ref:o,children:ga.isValidElement(c)?ga.cloneElement(c,void 0,u):null})}return(0,YZ.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function z9t(t){let e=ga.forwardRef((n,r)=>{let{children:o,...i}=n;if(ga.isValidElement(o)){let s=H9t(o),a=W9t(i,o.props);return o.type!==ga.Fragment&&(a.ref=r?P_e(r,s):s),ga.cloneElement(o,a)}return ga.Children.count(o)>1?ga.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var j9t=Symbol("radix.slottable");function V9t(t){return ga.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===j9t}function W9t(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function H9t(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Xit=N(Ve(),1),q9t=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],dd=q9t.reduce((t,e)=>{let n=ZZ(`Primitive.${e}`),r=Jit.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,Xit.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var OL=N(U(),1);function Qit(t){let e=OL.useRef(t);return OL.useEffect(()=>{e.current=t}),OL.useMemo(()=>(...n)=>e.current?.(...n),[])}var Qp=N(U(),1);var JZ=N(U(),1);var G9t=Qp[" useInsertionEffect ".trim().toString()]||yf;function A_e({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=Y9t({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=Qp.useRef(t!==void 0);Qp.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=Qp.useCallback(u=>{if(a){let d=Z9t(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function Y9t({defaultProp:t,onChange:e}){let[n,r]=Qp.useState(t),o=Qp.useRef(n),i=Qp.useRef(e);return G9t(()=>{i.current=e},[e]),Qp.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function Z9t(t){return typeof t=="function"}var HLr=Symbol("RADIX:SYNC_STATE");var XZ=N(U(),1);function est(t){let e=XZ.useRef({value:t,previous:t});return XZ.useMemo(()=>(e.current.value!==t&&(e.current.previous=e.current.value,e.current.value=t),e.current.previous),[t])}var xn=N(Ve(),1),J9t=[" ","Enter","ArrowUp","ArrowDown"],X9t=[" ","Enter"],GP="Select",[e7,t7,Q9t]=w_(GP),[RL,h1r]=Git(GP,[Q9t,Vp]),n7=Vp(),[eYt,U_]=RL(GP),[tYt,nYt]=RL(GP),tst=t=>{let{__scopeSelect:e,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:a,onValueChange:l,dir:c,name:u,autoComplete:d,disabled:f,required:p,form:m}=t,h=n7(e),[g,y]=pt.useState(null),[w,v]=pt.useState(null),[x,b]=pt.useState(!1),_=Yit(c),[T,S]=A_e({prop:r,defaultProp:o??!1,onChange:i,caller:GP}),[P,A]=A_e({prop:s,defaultProp:a,onChange:l,caller:GP}),O=pt.useRef(null),D=g?m||!!g.closest("form"):!0,[$,B]=pt.useState(new Set),W=Array.from($).map(F=>F.props.value).join(";");return(0,xn.jsx)(Uv,{...h,children:(0,xn.jsxs)(eYt,{required:p,scope:e,trigger:g,onTriggerChange:y,valueNode:w,onValueNodeChange:v,valueNodeHasChildren:x,onValueNodeHasChildrenChange:b,contentId:GZ(),value:P,onValueChange:A,open:T,onOpenChange:S,dir:_,triggerPointerDownPosRef:O,disabled:f,children:[(0,xn.jsx)(e7.Provider,{scope:e,children:(0,xn.jsx)(tYt,{scope:t.__scopeSelect,onNativeOptionAdd:pt.useCallback(F=>{B(Z=>new Set(Z).add(F))},[]),onNativeOptionRemove:pt.useCallback(F=>{B(Z=>{let V=new Set(Z);return V.delete(F),V})},[]),children:n})}),D?(0,xn.jsxs)(Tst,{"aria-hidden":!0,required:p,tabIndex:-1,name:u,autoComplete:d,value:P,onChange:F=>A(F.target.value),disabled:f,form:m,children:[P===void 0?(0,xn.jsx)("option",{value:""}):null,Array.from($)]},W):null]})})};tst.displayName=GP;var nst="SelectTrigger",rst=pt.forwardRef((t,e)=>{let{__scopeSelect:n,disabled:r=!1,...o}=t,i=n7(n),s=U_(nst,n),a=s.disabled||r,l=Ch(e,s.onTriggerChange),c=t7(n),u=pt.useRef("touch"),[d,f,p]=Pst(h=>{let g=c().filter(v=>!v.disabled),y=g.find(v=>v.value===s.value),w=Est(g,h,y);w!==void 0&&s.onValueChange(w.value)}),m=h=>{a||(s.onOpenChange(!0),p()),h&&(s.triggerPointerDownPosRef.current={x:Math.round(h.pageX),y:Math.round(h.pageY)})};return(0,xn.jsx)(Bv,{asChild:!0,...i,children:(0,xn.jsx)(dd.button,{type:"button",role:"combobox","aria-controls":s.contentId,"aria-expanded":s.open,"aria-required":s.required,"aria-autocomplete":"none",dir:s.dir,"data-state":s.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":Ist(s.value)?"":void 0,...o,ref:l,onClick:Ja(o.onClick,h=>{h.currentTarget.focus(),u.current!=="mouse"&&m(h)}),onPointerDown:Ja(o.onPointerDown,h=>{u.current=h.pointerType;let g=h.target;g.hasPointerCapture(h.pointerId)&&g.releasePointerCapture(h.pointerId),h.button===0&&h.ctrlKey===!1&&h.pointerType==="mouse"&&(m(h),h.preventDefault())}),onKeyDown:Ja(o.onKeyDown,h=>{let g=d.current!=="";!(h.ctrlKey||h.altKey||h.metaKey)&&h.key.length===1&&f(h.key),!(g&&h.key===" ")&&J9t.includes(h.key)&&(m(),h.preventDefault())})})})});rst.displayName=nst;var ost="SelectValue",ist=pt.forwardRef((t,e)=>{let{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...a}=t,l=U_(ost,n),{onValueNodeHasChildrenChange:c}=l,u=i!==void 0,d=Ch(e,l.onValueNodeChange);return yf(()=>{c(u)},[c,u]),(0,xn.jsx)(dd.span,{...a,ref:d,style:{pointerEvents:"none"},children:Ist(l.value)?(0,xn.jsx)(xn.Fragment,{children:s}):i})});ist.displayName=ost;var rYt="SelectIcon",sst=pt.forwardRef((t,e)=>{let{__scopeSelect:n,children:r,...o}=t;return(0,xn.jsx)(dd.span,{"aria-hidden":!0,...o,ref:e,children:r||"\u25BC"})});sst.displayName=rYt;var oYt="SelectPortal",ast=t=>(0,xn.jsx)(vh,{asChild:!0,...t});ast.displayName=oYt;var YP="SelectContent",lst=pt.forwardRef((t,e)=>{let n=U_(YP,t.__scopeSelect),[r,o]=pt.useState();if(yf(()=>{o(new DocumentFragment)},[]),!n.open){let i=r;return i?L_e.createPortal((0,xn.jsx)(cst,{scope:t.__scopeSelect,children:(0,xn.jsx)(e7.Slot,{scope:t.__scopeSelect,children:(0,xn.jsx)("div",{children:t.children})})}),i):null}return(0,xn.jsx)(ust,{...t,ref:e})});lst.displayName=YP;var _h=10,[cst,B_]=RL(YP),iYt="SelectContentImpl",sYt=ZZ("SelectContent.RemoveScroll"),ust=pt.forwardRef((t,e)=>{let{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:a,sideOffset:l,align:c,alignOffset:u,arrowPadding:d,collisionBoundary:f,collisionPadding:p,sticky:m,hideWhenDetached:h,avoidCollisions:g,...y}=t,w=U_(YP,n),[v,x]=pt.useState(null),[b,_]=pt.useState(null),T=Ch(e,E=>x(E)),[S,P]=pt.useState(null),[A,O]=pt.useState(null),D=t7(n),[$,B]=pt.useState(!1),W=pt.useRef(!1);pt.useEffect(()=>{if(v)return I_(v)},[v]),x_();let F=pt.useCallback(E=>{let[R,...L]=D().map(re=>re.ref.current),[K]=L.slice(-1),Y=document.activeElement;for(let re of E)if(re===Y||(re?.scrollIntoView({block:"nearest"}),re===R&&b&&(b.scrollTop=0),re===K&&b&&(b.scrollTop=b.scrollHeight),re?.focus(),document.activeElement!==Y))return},[D,b]),Z=pt.useCallback(()=>F([S,v]),[F,S,v]);pt.useEffect(()=>{$&&Z()},[$,Z]);let{onOpenChange:V,triggerPointerDownPosRef:H}=w;pt.useEffect(()=>{if(v){let E={x:0,y:0},R=K=>{E={x:Math.abs(Math.round(K.pageX)-(H.current?.x??0)),y:Math.abs(Math.round(K.pageY)-(H.current?.y??0))}},L=K=>{E.x<=10&&E.y<=10?K.preventDefault():v.contains(K.target)||V(!1),document.removeEventListener("pointermove",R),H.current=null};return H.current!==null&&(document.addEventListener("pointermove",R),document.addEventListener("pointerup",L,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",R),document.removeEventListener("pointerup",L,{capture:!0})}}},[v,V,H]),pt.useEffect(()=>{let E=()=>V(!1);return window.addEventListener("blur",E),window.addEventListener("resize",E),()=>{window.removeEventListener("blur",E),window.removeEventListener("resize",E)}},[V]);let[te,fe]=Pst(E=>{let R=D().filter(Y=>!Y.disabled),L=R.find(Y=>Y.ref.current===document.activeElement),K=Est(R,E,L);K&&setTimeout(()=>K.ref.current.focus())}),me=pt.useCallback((E,R,L)=>{let K=!W.current&&!L;(w.value!==void 0&&w.value===R||K)&&(P(E),K&&(W.current=!0))},[w.value]),j=pt.useCallback(()=>v?.focus(),[v]),G=pt.useCallback((E,R,L)=>{let K=!W.current&&!L;(w.value!==void 0&&w.value===R||K)&&O(E)},[w.value]),J=r==="popper"?k_e:dst,M=J===k_e?{side:a,sideOffset:l,align:c,alignOffset:u,arrowPadding:d,collisionBoundary:f,collisionPadding:p,sticky:m,hideWhenDetached:h,avoidCollisions:g}:{};return(0,xn.jsx)(cst,{scope:n,content:v,viewport:b,onViewportChange:_,itemRefCallback:me,selectedItem:S,onItemLeave:j,itemTextRefCallback:G,focusSelectedItem:Z,selectedItemText:A,position:r,isPositioned:$,searchRef:te,children:(0,xn.jsx)(jv,{as:sYt,allowPinchZoom:!0,children:(0,xn.jsx)(Dv,{asChild:!0,trapped:w.open,onMountAutoFocus:E=>{E.preventDefault()},onUnmountAutoFocus:Ja(o,E=>{w.trigger?.focus({preventScroll:!0}),E.preventDefault()}),children:(0,xn.jsx)(mh,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:E=>E.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:(0,xn.jsx)(J,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:E=>E.preventDefault(),...y,...M,onPlaced:()=>B(!0),ref:T,style:{display:"flex",flexDirection:"column",outline:"none",...y.style},onKeyDown:Ja(y.onKeyDown,E=>{let R=E.ctrlKey||E.altKey||E.metaKey;if(E.key==="Tab"&&E.preventDefault(),!R&&E.key.length===1&&fe(E.key),["ArrowUp","ArrowDown","Home","End"].includes(E.key)){let K=D().filter(Y=>!Y.disabled).map(Y=>Y.ref.current);if(["ArrowUp","End"].includes(E.key)&&(K=K.slice().reverse()),["ArrowUp","ArrowDown"].includes(E.key)){let Y=E.target,re=K.indexOf(Y);K=K.slice(re+1)}setTimeout(()=>F(K)),E.preventDefault()}})})})})})})});ust.displayName=iYt;var aYt="SelectItemAlignedPosition",dst=pt.forwardRef((t,e)=>{let{__scopeSelect:n,onPlaced:r,...o}=t,i=U_(YP,n),s=B_(YP,n),[a,l]=pt.useState(null),[c,u]=pt.useState(null),d=Ch(e,T=>u(T)),f=t7(n),p=pt.useRef(!1),m=pt.useRef(!0),{viewport:h,selectedItem:g,selectedItemText:y,focusSelectedItem:w}=s,v=pt.useCallback(()=>{if(i.trigger&&i.valueNode&&a&&c&&h&&g&&y){let T=i.trigger.getBoundingClientRect(),S=c.getBoundingClientRect(),P=i.valueNode.getBoundingClientRect(),A=y.getBoundingClientRect();if(i.dir!=="rtl"){let Y=A.left-S.left,re=P.left-Y,ae=T.left-re,ve=T.width+ae,Te=Math.max(ve,S.width),Ee=window.innerWidth-_h,nt=$_(re,[_h,Math.max(_h,Ee-Te)]);a.style.minWidth=ve+"px",a.style.left=nt+"px"}else{let Y=S.right-A.right,re=window.innerWidth-P.right-Y,ae=window.innerWidth-T.right-re,ve=T.width+ae,Te=Math.max(ve,S.width),Ee=window.innerWidth-_h,nt=$_(re,[_h,Math.max(_h,Ee-Te)]);a.style.minWidth=ve+"px",a.style.right=nt+"px"}let O=f(),D=window.innerHeight-_h*2,$=h.scrollHeight,B=window.getComputedStyle(c),W=parseInt(B.borderTopWidth,10),F=parseInt(B.paddingTop,10),Z=parseInt(B.borderBottomWidth,10),V=parseInt(B.paddingBottom,10),H=W+F+$+V+Z,te=Math.min(g.offsetHeight*5,H),fe=window.getComputedStyle(h),me=parseInt(fe.paddingTop,10),j=parseInt(fe.paddingBottom,10),G=T.top+T.height/2-_h,J=D-G,M=g.offsetHeight/2,E=g.offsetTop+M,R=W+F+E,L=H-R;if(R<=G){let Y=O.length>0&&g===O[O.length-1].ref.current;a.style.bottom="0px";let re=c.clientHeight-h.offsetTop-h.offsetHeight,ae=Math.max(J,M+(Y?j:0)+re+Z),ve=R+ae;a.style.height=ve+"px"}else{let Y=O.length>0&&g===O[0].ref.current;a.style.top="0px";let ae=Math.max(G,W+h.offsetTop+(Y?me:0)+M)+L;a.style.height=ae+"px",h.scrollTop=R-G+h.offsetTop}a.style.margin=`${_h}px 0`,a.style.minHeight=te+"px",a.style.maxHeight=D+"px",r?.(),requestAnimationFrame(()=>p.current=!0)}},[f,i.trigger,i.valueNode,a,c,h,g,y,i.dir,r]);yf(()=>v(),[v]);let[x,b]=pt.useState();yf(()=>{c&&b(window.getComputedStyle(c).zIndex)},[c]);let _=pt.useCallback(T=>{T&&m.current===!0&&(v(),w?.(),m.current=!1)},[v,w]);return(0,xn.jsx)(cYt,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:p,onScrollButtonChange:_,children:(0,xn.jsx)("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:x},children:(0,xn.jsx)(dd.div,{...o,ref:d,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});dst.displayName=aYt;var lYt="SelectPopperPosition",k_e=pt.forwardRef((t,e)=>{let{__scopeSelect:n,align:r="start",collisionPadding:o=_h,...i}=t,s=n7(n);return(0,xn.jsx)(__,{...s,...i,ref:e,align:r,collisionPadding:o,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});k_e.displayName=lYt;var[cYt,D_e]=RL(YP,{}),M_e="SelectViewport",fst=pt.forwardRef((t,e)=>{let{__scopeSelect:n,nonce:r,...o}=t,i=B_(M_e,n),s=D_e(M_e,n),a=Ch(e,i.onViewportChange),l=pt.useRef(0);return(0,xn.jsxs)(xn.Fragment,{children:[(0,xn.jsx)("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),(0,xn.jsx)(e7.Slot,{scope:n,children:(0,xn.jsx)(dd.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:Ja(o.onScroll,c=>{let u=c.currentTarget,{contentWrapper:d,shouldExpandOnScrollRef:f}=s;if(f?.current&&d){let p=Math.abs(l.current-u.scrollTop);if(p>0){let m=window.innerHeight-_h*2,h=parseFloat(d.style.minHeight),g=parseFloat(d.style.height),y=Math.max(h,g);if(y<m){let w=y+p,v=Math.min(m,w),x=w-v;d.style.height=v+"px",d.style.bottom==="0px"&&(u.scrollTop=x>0?x:0,d.style.justifyContent="flex-end")}}}l.current=u.scrollTop})})})]})});fst.displayName=M_e;var pst="SelectGroup",[uYt,dYt]=RL(pst),fYt=pt.forwardRef((t,e)=>{let{__scopeSelect:n,...r}=t,o=GZ();return(0,xn.jsx)(uYt,{scope:n,id:o,children:(0,xn.jsx)(dd.div,{role:"group","aria-labelledby":o,...r,ref:e})})});fYt.displayName=pst;var mst="SelectLabel",hst=pt.forwardRef((t,e)=>{let{__scopeSelect:n,...r}=t,o=dYt(mst,n);return(0,xn.jsx)(dd.div,{id:o.id,...r,ref:e})});hst.displayName=mst;var QZ="SelectItem",[pYt,gst]=RL(QZ),yst=pt.forwardRef((t,e)=>{let{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=t,a=U_(QZ,n),l=B_(QZ,n),c=a.value===r,[u,d]=pt.useState(i??""),[f,p]=pt.useState(!1),m=Ch(e,w=>l.itemRefCallback?.(w,r,o)),h=GZ(),g=pt.useRef("touch"),y=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return(0,xn.jsx)(pYt,{scope:n,value:r,disabled:o,textId:h,isSelected:c,onItemTextChange:pt.useCallback(w=>{d(v=>v||(w?.textContent??"").trim())},[]),children:(0,xn.jsx)(e7.ItemSlot,{scope:n,value:r,disabled:o,textValue:u,children:(0,xn.jsx)(dd.div,{role:"option","aria-labelledby":h,"data-highlighted":f?"":void 0,"aria-selected":c&&f,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...s,ref:m,onFocus:Ja(s.onFocus,()=>p(!0)),onBlur:Ja(s.onBlur,()=>p(!1)),onClick:Ja(s.onClick,()=>{g.current!=="mouse"&&y()}),onPointerUp:Ja(s.onPointerUp,()=>{g.current==="mouse"&&y()}),onPointerDown:Ja(s.onPointerDown,w=>{g.current=w.pointerType}),onPointerMove:Ja(s.onPointerMove,w=>{g.current=w.pointerType,o?l.onItemLeave?.():g.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Ja(s.onPointerLeave,w=>{w.currentTarget===document.activeElement&&l.onItemLeave?.()}),onKeyDown:Ja(s.onKeyDown,w=>{l.searchRef?.current!==""&&w.key===" "||(X9t.includes(w.key)&&y(),w.key===" "&&w.preventDefault())})})})})});yst.displayName=QZ;var d4="SelectItemText",wst=pt.forwardRef((t,e)=>{let{__scopeSelect:n,className:r,style:o,...i}=t,s=U_(d4,n),a=B_(d4,n),l=gst(d4,n),c=nYt(d4,n),[u,d]=pt.useState(null),f=Ch(e,y=>d(y),l.onItemTextChange,y=>a.itemTextRefCallback?.(y,l.value,l.disabled)),p=u?.textContent,m=pt.useMemo(()=>(0,xn.jsx)("option",{value:l.value,disabled:l.disabled,children:p},l.value),[l.disabled,l.value,p]),{onNativeOptionAdd:h,onNativeOptionRemove:g}=c;return yf(()=>(h(m),()=>g(m)),[h,g,m]),(0,xn.jsxs)(xn.Fragment,{children:[(0,xn.jsx)(dd.span,{id:l.textId,...i,ref:f}),l.isSelected&&s.valueNode&&!s.valueNodeHasChildren?L_e.createPortal(i.children,s.valueNode):null]})});wst.displayName=d4;var vst="SelectItemIndicator",xst=pt.forwardRef((t,e)=>{let{__scopeSelect:n,...r}=t;return gst(vst,n).isSelected?(0,xn.jsx)(dd.span,{"aria-hidden":!0,...r,ref:e}):null});xst.displayName=vst;var N_e="SelectScrollUpButton",bst=pt.forwardRef((t,e)=>{let n=B_(N_e,t.__scopeSelect),r=D_e(N_e,t.__scopeSelect),[o,i]=pt.useState(!1),s=Ch(e,r.onScrollButtonChange);return yf(()=>{if(n.viewport&&n.isPositioned){let l=function(){let u=c.scrollTop>0;i(u)};var a=l;let c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),o?(0,xn.jsx)(_st,{...t,ref:s,onAutoScroll:()=>{let{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});bst.displayName=N_e;var O_e="SelectScrollDownButton",Cst=pt.forwardRef((t,e)=>{let n=B_(O_e,t.__scopeSelect),r=D_e(O_e,t.__scopeSelect),[o,i]=pt.useState(!1),s=Ch(e,r.onScrollButtonChange);return yf(()=>{if(n.viewport&&n.isPositioned){let l=function(){let u=c.scrollHeight-c.clientHeight,d=Math.ceil(c.scrollTop)<u;i(d)};var a=l;let c=n.viewport;return l(),c.addEventListener("scroll",l),()=>c.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),o?(0,xn.jsx)(_st,{...t,ref:s,onAutoScroll:()=>{let{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});Cst.displayName=O_e;var _st=pt.forwardRef((t,e)=>{let{__scopeSelect:n,onAutoScroll:r,...o}=t,i=B_("SelectScrollButton",n),s=pt.useRef(null),a=t7(n),l=pt.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return pt.useEffect(()=>()=>l(),[l]),yf(()=>{a().find(u=>u.ref.current===document.activeElement)?.ref.current?.scrollIntoView({block:"nearest"})},[a]),(0,xn.jsx)(dd.div,{"aria-hidden":!0,...o,ref:e,style:{flexShrink:0,...o.style},onPointerDown:Ja(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:Ja(o.onPointerMove,()=>{i.onItemLeave?.(),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:Ja(o.onPointerLeave,()=>{l()})})}),mYt="SelectSeparator",Sst=pt.forwardRef((t,e)=>{let{__scopeSelect:n,...r}=t;return(0,xn.jsx)(dd.div,{"aria-hidden":!0,...r,ref:e})});Sst.displayName=mYt;var R_e="SelectArrow",hYt=pt.forwardRef((t,e)=>{let{__scopeSelect:n,...r}=t,o=n7(n),i=U_(R_e,n),s=B_(R_e,n);return i.open&&s.position==="popper"?(0,xn.jsx)(S_,{...o,...r,ref:e}):null});hYt.displayName=R_e;var gYt="SelectBubbleInput",Tst=pt.forwardRef(({__scopeSelect:t,value:e,...n},r)=>{let o=pt.useRef(null),i=Ch(r,o),s=est(e);return pt.useEffect(()=>{let a=o.current;if(!a)return;let l=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(l,"value").set;if(s!==e&&u){let d=new Event("change",{bubbles:!0});u.call(a,e),a.dispatchEvent(d)}},[s,e]),(0,xn.jsx)(dd.select,{...n,style:{...NCe,...n.style},ref:i,defaultValue:e})});Tst.displayName=gYt;function Ist(t){return t===""||t===void 0}function Pst(t){let e=Qit(t),n=pt.useRef(""),r=pt.useRef(0),o=pt.useCallback(s=>{let a=n.current+s;e(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[e]),i=pt.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return pt.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function Est(t,e,n){let o=e.length>1&&Array.from(e).every(c=>c===e[0])?e[0]:e,i=n?t.indexOf(n):-1,s=yYt(t,Math.max(i,0));o.length===1&&(s=s.filter(c=>c!==n));let l=s.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function yYt(t,e){return t.map((n,r)=>t[(e+r)%t.length])}var Ast=tst,$_e=rst,kst=ist,Mst=sst,Nst=ast,F_e=lst,Ost=fst;var U_e=hst,B_e=yst,Rst=wst,Lst=xst,z_e=bst,j_e=Cst,V_e=Sst;vt();Kt();var ZP=Ast;var JP=kst,z_=xo.forwardRef(({className:t,children:e,...n},r)=>xo.createElement($_e,{ref:r,className:oe("tw-border-solid !tw-bg-dropdown !tw-shadow-sm tw-transition-colors","focus-visible:tw-shadow-sm focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring","hover:data-[state=closed]:!tw-bg-interactive-accent hover:data-[state=closed]:!tw-text-on-accent","tw-flex tw-h-9 tw-w-full tw-items-center tw-justify-between tw-whitespace-nowrap tw-rounded-md tw-border tw-border-border tw-px-3 tw-py-1 tw-text-sm tw-ring-offset-ring placeholder:tw-text-muted focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring disabled:tw-cursor-not-allowed disabled:tw-opacity-50 [&>span]:tw-line-clamp-1",t),...n},e,xo.createElement(Mst,{asChild:!0},xo.createElement(hr,{className:"tw-size-4"}))));z_.displayName=$_e.displayName;var Dst=xo.forwardRef(({className:t,...e},n)=>xo.createElement(z_e,{ref:n,className:oe("tw-flex tw-cursor-default tw-items-center tw-justify-center tw-py-1",t),...e},xo.createElement($s,{className:"tw-size-4"})));Dst.displayName=z_e.displayName;var $st=xo.forwardRef(({className:t,...e},n)=>xo.createElement(j_e,{ref:n,className:oe("tw-flex tw-cursor-default tw-items-center tw-justify-center tw-py-1",t),...e},xo.createElement(hr,{className:"tw-size-4"})));$st.displayName=j_e.displayName;var j_=xo.forwardRef(({className:t,children:e,position:n="popper",container:r,...o},i)=>xo.createElement(Nst,{container:r},xo.createElement(F_e,{ref:i,className:oe("tw-relative tw-z-modal tw-max-h-96 tw-min-w-32 tw-overflow-hidden tw-rounded-md tw-border tw-bg-primary tw-text-normal tw-shadow-md data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[side=bottom]:tw-slide-in-from-top-2 data-[side=left]:tw-slide-in-from-right-2 data-[side=right]:tw-slide-in-from-left-2 data-[side=top]:tw-slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:tw-translate-y-1 data-[side=left]:-tw-translate-x-1 data-[side=right]:tw-translate-x-1 data-[side=top]:-tw-translate-y-1",t),position:n,...o},xo.createElement(Dst,null),xo.createElement(Ost,{className:oe("tw-p-1",n==="popper"&&"tw-h-[var(--radix-select-trigger-height)] tw-w-full tw-min-w-[var(--radix-select-trigger-width)]")},e),xo.createElement($st,null))));j_.displayName=F_e.displayName;var vYt=xo.forwardRef(({className:t,...e},n)=>xo.createElement(U_e,{ref:n,className:oe("tw-px-2 tw-py-1.5 tw-text-sm tw-font-semibold",t),...e}));vYt.displayName=U_e.displayName;var V_=xo.forwardRef(({className:t,children:e,...n},r)=>xo.createElement(B_e,{ref:r,className:oe("tw-relative tw-flex tw-w-full tw-cursor-default tw-select-none tw-items-center tw-rounded-sm tw-py-1.5 tw-pl-2 tw-pr-8 tw-text-sm tw-outline-none focus:tw-bg-interactive-accent focus:tw-text-on-accent data-[disabled]:tw-pointer-events-none data-[disabled]:tw-opacity-50",t),...n},xo.createElement("span",{className:"tw-absolute tw-right-2 tw-flex tw-size-3.5 tw-items-center tw-justify-center"},xo.createElement(Lst,null,xo.createElement(Ro,{className:"tw-size-4"}))),xo.createElement(Rst,null,e)));V_.displayName=B_e.displayName;var xYt=xo.forwardRef(({className:t,...e},n)=>xo.createElement(V_e,{ref:n,className:oe("-tw-mx-1 tw-my-1 tw-h-px tw-bg-primary-alt",t),...e}));xYt.displayName=V_e.displayName;vt();function W_(t){let{label:e,helpText:n,disableFn:r,optional:o=!0}=t,i=t.type,s=o?t.value!==void 0:!0,[a,l]=(0,ho.useState)(s),c=()=>{o&&(l(!a),a?r?.():i==="slider"?t.onChange(t.value??t.defaultValue??0):t.onChange(t.value??t.defaultValue??t.options[0]?.value??""))},u=f=>{a&&i==="slider"&&t.onChange(f[0])},d=f=>{a&&i==="select"&&t.onChange(f)};return ho.default.createElement("div",{className:"tw-space-y-3"},ho.default.createElement(uu,{delayDuration:0},ho.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},ho.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},ho.default.createElement("span",{className:`tw-font-medium ${a?"tw-text-normal":"tw-text-muted"}`},e),n&&ho.default.createElement(Nn,{buttonClassName:"tw-size-4 tw-text-muted",content:ho.default.createElement("div",{className:"tw-max-w-[300px]"},n)})),ho.default.createElement("div",{className:`tw-flex tw-items-center ${o?"tw-gap-3":"tw-gap-0"}`},ho.default.createElement("span",{className:`tw-min-w-8 tw-text-right tw-font-mono tw-text-sm ${a?"tw-text-normal":"tw-text-muted"}`},a?t.value??t.defaultValue:"\u2014"),o&&ho.default.createElement(cn,null,ho.default.createElement(un,{asChild:!0},ho.default.createElement(X,{variant:"ghost2",size:"sm",onClick:c,className:`tw-size-8 tw-p-0 ${a?"tw-text-accent/80 hover:tw-text-accent":"tw-text-muted hover:tw-text-normal"}`},a?ho.default.createElement(R$,{className:"tw-size-4"}):ho.default.createElement(O$,{className:"tw-size-4"}))),ho.default.createElement(on,{side:"bottom"},ho.default.createElement("span",null,a?"Disable parameters":"Enable parameters")))))),ho.default.createElement("div",{className:"tw-relative"},i==="slider"?ho.default.createElement(ho.default.Fragment,null,ho.default.createElement(u4,{value:[a?t.value??t.defaultValue??0:t.min??0],onValueChange:u,min:t.min??0,max:t.max??1,step:t.step,disabled:!a,className:`tw-w-full ${a?"":"tw-opacity-40"}`}),!a&&o&&ho.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-cursor-not-allowed tw-rounded"})):ho.default.createElement(ZP,{value:a?t.value??t.defaultValue??t.options[0]?.value:void 0,onValueChange:d,disabled:!a},ho.default.createElement(z_,{className:`tw-w-full ${a?"":"tw-opacity-40"}`},ho.default.createElement(JP,{placeholder:"Select an option"})),ho.default.createElement(j_,null,t.options.map(f=>ho.default.createElement(V_,{key:f.value,value:f.value},f.label))))))}It();It();var Fst=[{value:"minimal",label:"Minimal"},{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"xhigh",label:"Extra High"}],Ust=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"}];function Bst(){return Pc.REASONING_EFFORT}function zst(){return Pc.VERBOSITY}var yi={temperature:{min:0,max:2,step:.01,default:Pc.TEMPERATURE},topP:{min:0,max:1,step:.05,default:.9},frequencyPenalty:{min:0,max:2,step:.05,default:0},maxTokens:{min:100,max:128e3,step:100,default:Pc.MAX_TOKENS},numCtx:{min:0,max:ZE,step:1024,default:ZE}};function r7({model:t,settings:e,onChange:n,onReset:r,showTokenLimit:o=!0}){let i=t.provider,s=i==="ollama",a=t.temperature??e.temperature,l=t.maxTokens??e.maxTokens,c=t.topP,u=t.frequencyPenalty,d=s?t.numCtx??yi.numCtx.default:t.numCtx,f=t.reasoningEffort,p=t.verbosity,m=(t.name.startsWith("o1")||t.name.startsWith("o3")||t.name.startsWith("o4")||t.name.startsWith("gpt-5"))&&i==="openai",h=t.capabilities?.includes("reasoning")??!1,g=m||i==="openrouterai"||t.provider==="lm_studio"||i==="lm-studio"||h,y=t.name.startsWith("gpt-5")&&i==="openai";return Un.default.createElement("div",{className:"tw-space-y-4"},o&&Un.default.createElement(Zn,null,Un.default.createElement(W_,{type:"slider",optional:!1,label:"Token limit",value:l,onChange:w=>n("maxTokens",w),max:yi.maxTokens.max,min:yi.maxTokens.min,step:yi.maxTokens.step,defaultValue:yi.maxTokens.default,helpText:Un.default.createElement(Un.default.Fragment,null,Un.default.createElement("p",null,"The maximum number of ",Un.default.createElement("em",null,"output tokens")," to generate. Default is"," ",yi.maxTokens.default,"."),Un.default.createElement("em",null,"This number plus the length of your prompt (input tokens) must be smaller than the context window of the model."))})),s&&Un.default.createElement(Zn,null,Un.default.createElement(W_,{type:"slider",optional:!1,label:"num_ctx",value:d,onChange:w=>n("numCtx",w),min:yi.numCtx.min,max:yi.numCtx.max,step:yi.numCtx.step,defaultValue:yi.numCtx.default,helpText:Un.default.createElement(Un.default.Fragment,null,Un.default.createElement("p",null,"The ",Un.default.createElement("code",null,"num_ctx")," parameter sent to Ollama. Controls how many tokens the model can use as context. Default is ",ZE,"."),Un.default.createElement("em",null,"Lower this value to reduce VRAM usage on GPUs with limited memory. Ollama will cap this at the model's actual maximum."))})),Un.default.createElement(Zn,null,Un.default.createElement(W_,{type:"slider",optional:!1,label:"Temperature",value:a,onChange:w=>n("temperature",w),min:yi.temperature.min,max:yi.temperature.max,step:yi.temperature.step,defaultValue:yi.temperature.default,helpText:`Default is ${yi.temperature.default}. Higher values will result in more creativeness, but also more mistakes. Set to 0 for no randomness.`})),Un.default.createElement(Zn,null,Un.default.createElement(W_,{type:"slider",optional:!0,label:"Top-P",value:c,onChange:w=>n("topP",w),disableFn:r?()=>r("topP"):void 0,min:yi.topP.min,max:yi.topP.max,step:yi.topP.step,defaultValue:yi.topP.default,helpText:`Default value is ${yi.topP.default}, the smaller the value, the less variety in the answers, the easier to understand, the larger the value, the larger the range of the AI's vocabulary, the more diverse`})),Un.default.createElement(Zn,null,Un.default.createElement(W_,{type:"slider",optional:!0,label:"Frequency Penalty",value:u,onChange:w=>n("frequencyPenalty",w),disableFn:r?()=>r("frequencyPenalty"):void 0,min:yi.frequencyPenalty.min,max:yi.frequencyPenalty.max,step:yi.frequencyPenalty.step,defaultValue:yi.frequencyPenalty.default,helpText:Un.default.createElement(Un.default.Fragment,null,Un.default.createElement("p",null,"The frequency penalty parameter tells the model not to repeat a word that has already been used multiple times in the conversation."),Un.default.createElement("em",null,"The higher the value, the more the model is penalized for repeating words."))})),g&&Un.default.createElement(Zn,null,Un.default.createElement(W_,{type:"select",optional:!0,label:"Reasoning Effort",value:f,onChange:w=>n("reasoningEffort",w),disableFn:r?()=>r("reasoningEffort"):void 0,defaultValue:e.reasoningEffort??Bst(),options:[...t.name.startsWith("gpt-5")&&t.provider==="openai"?[{value:"minimal",label:"Minimal"}]:[],...Fst.filter(w=>w.value!=="minimal"&&w.value!=="xhigh"),...t.name.startsWith("gpt-5.4")&&t.provider==="openai"?[{value:"xhigh",label:"Extra High"}]:[]],helpText:Un.default.createElement(Un.default.Fragment,null,Un.default.createElement("p",null,"Controls the amount of reasoning effort the model uses. Higher effort provides more thorough reasoning but takes longer."),Un.default.createElement("ul",{className:"tw-mt-2 tw-space-y-1 tw-text-xs"},t.name.startsWith("gpt-5")&&t.provider==="openai"&&Un.default.createElement("li",null,"Minimal: Fastest responses, minimal reasoning (GPT-5 only)"),Un.default.createElement("li",null,"Low: Faster responses, basic reasoning (default)"),Un.default.createElement("li",null,"Medium: Balanced performance"),Un.default.createElement("li",null,"High: Thorough reasoning, slower responses"),t.name.startsWith("gpt-5.4")&&t.provider==="openai"&&Un.default.createElement("li",null,"Extra High: Maximum reasoning depth (GPT-5.4 only)")),!h&&!m&&Un.default.createElement("p",{className:"tw-mt-2 tw-text-warning"},'Enable the "Reasoning" capability above to use this feature.'))})),y&&Un.default.createElement(Zn,null,Un.default.createElement(W_,{type:"select",optional:!0,label:"Verbosity",value:p,onChange:w=>n("verbosity",w),disableFn:r?()=>r("verbosity"):void 0,defaultValue:e.verbosity??zst(),options:Ust,helpText:Un.default.createElement(Un.default.Fragment,null,Un.default.createElement("p",null,"Controls the length and detail of the model responses."),Un.default.createElement("ul",{className:"tw-mt-2 tw-space-y-1 tw-text-xs"},Un.default.createElement("li",null,"Low: Concise, brief responses"),Un.default.createElement("li",null,"Medium: Balanced detail"),Un.default.createElement("li",null,"High: Detailed, comprehensive responses")))})))}Ir();Se();Hx();var CYt=["topP","frequencyPenalty","reasoningEffort","verbosity"];function jst(){let t=tr(),e=q(),n=Iu(),r=e.activeModels.find(D=>`${D.name}|${D.provider}`===n),[o,i]=(0,_t.useState)(r),[s,a]=(0,_t.useState)(n);s!==n&&(a(n),i(r));let l=V8(),[c,u]=W9e(),d=H8(),f=D=>D?l.some($=>$.title===D):!1,p=f(c)?c:f(d)?d:"",[m,h]=(0,_t.useState)(()=>hz()),[g,y]=(0,_t.useState)(!1),w=(0,_t.useRef)(null);(0,_t.useEffect)(()=>{g&&w.current&&w.current.scrollIntoView({behavior:"smooth",block:"end"})},[g]);let v=(0,_t.useMemo)(()=>Li(D=>{let $=e.activeModels.map(B=>`${B.name}|${B.provider}`===n?D:B);pe("activeModels",$)},500),[e.activeModels,n]);(0,_t.useEffect)(()=>()=>{v.flush(),v.cancel()},[v]);let x=(0,_t.useCallback)(D=>{if(D||v.flush(),D){let $=hz();h($),$||y(!1)}},[v]),b=(0,_t.useCallback)((D,$)=>{if(!o)return;let B={...o,[D]:$};i(B),v(B)},[o,v]),_=(0,_t.useCallback)(D=>{if(!o)return;let $={...o};delete $[D],i($),v($)},[o,v]),T=(0,_t.useCallback)(()=>{if(o){let D={...o};CYt.forEach($=>delete D[$]),i(D),v(D)}u(""),h(!1),y(!1),mz(!1)},[o,v,u]),S=D=>{D?y(!0):(h(!1),y(!1),mz(!1))},P=()=>{h(!0),y(!1),mz(!0)},A=()=>{y(!1)},O=()=>{if(!p)return;let D=Gp(p);t.workspace.openLinkText(D,"",!0)};return o?_t.default.createElement(R_,{onOpenChange:x},_t.default.createElement(cn,null,_t.default.createElement(un,{asChild:!0},_t.default.createElement(L_,{asChild:!0},_t.default.createElement(X,{variant:"ghost2",size:"icon"},_t.default.createElement(XS,{className:"tw-size-4"})))),_t.default.createElement(on,null,"Chat Settings")),_t.default.createElement(Kv,{className:"tw-w-80 tw-rounded-md tw-p-0",align:"end"},_t.default.createElement("div",{className:"tw-flex tw-max-h-[500px] tw-flex-col"},_t.default.createElement("div",{className:"tw-shrink-0 tw-border-b tw-px-4"},_t.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},_t.default.createElement("h3",{className:"tw-font-semibold"},"Chat Settings"),_t.default.createElement(X,{variant:"ghost",size:"sm",onClick:T,className:"tw-h-8 tw-text-xs"},_t.default.createElement(A$,{className:"tw-mr-1 tw-size-3"}),"Reset"))),_t.default.createElement(Jp,null),_t.default.createElement(Sy,{className:"tw-flex-1 tw-overflow-y-auto"},_t.default.createElement("div",{className:"tw-space-y-4 tw-p-4"},_t.default.createElement("div",{className:"tw-space-y-2"},_t.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 sm:tw-flex-row sm:tw-items-center sm:tw-justify-between"},_t.default.createElement(hi,{htmlFor:"system-prompt",className:"tw-text-sm sm:tw-min-w-fit"},"System Prompt"),_t.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2 sm:tw-flex-1"},_t.default.createElement(Ty,{value:p,onChange:D=>{let $=D.target.value;$===""?u(""):f($)&&u($)},options:[{label:"None (use built-in prompt)",value:""},...l.map(D=>({label:D.title===d?`${D.title} (Default)`:D.title,value:D.title}))],placeholder:"Select system prompt",containerClassName:"tw-flex-1"}),_t.default.createElement(X,{variant:"ghost",size:"icon",onClick:O,className:"tw-size-5 tw-shrink-0 tw-p-0",title:"Open the source file",disabled:!p},_t.default.createElement(Oc,{className:"tw-size-5"}))))),_t.default.createElement(r7,{model:o,settings:e,onChange:b,onReset:_,showTokenLimit:!0}),_t.default.createElement(Jp,null),_t.default.createElement("div",{className:"tw-space-y-3"},_t.default.createElement("div",{className:"tw-space-y-1.5"},_t.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},_t.default.createElement(hi,{htmlFor:"disable-builtin",className:"tw-text-sm tw-font-medium"},"Disable Builtin System Prompt"),_t.default.createElement(uh,{checked:m,onCheckedChange:S,disabled:g})),_t.default.createElement("div",{className:"tw-pr-12 tw-text-xs tw-leading-relaxed tw-text-muted"},"Disables the builtin system prompt and only uses your custom system prompt."," ",_t.default.createElement("span",{className:"tw-text-xs tw-text-error"},"WARNING: This may break expected functionality."))),(m||g)&&_t.default.createElement("div",{ref:w,className:"tw-rounded-md tw-border tw-bg-error/10 tw-p-3 tw-border-error/50"},_t.default.createElement("div",{className:"tw-flex tw-gap-2"},_t.default.createElement(dl,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0 tw-text-error"}),_t.default.createElement("div",{className:"tw-flex-1 tw-space-y-2"},_t.default.createElement("div",{className:"tw-space-y-1"},_t.default.createElement("div",{className:"tw-text-xs tw-font-semibold tw-text-error"},"Copilot Plus Features Will Become Unavailable"),_t.default.createElement("div",{className:"tw-flex tw-flex-col  tw-items-center tw-gap-2 tw-text-xs tw-leading-relaxed tw-text-muted"},_t.default.createElement("div",null,"When enabled, advanced features such as vault search, web search, and agent mode will become unavailable."," "),_t.default.createElement("div",{className:"tw-italic"},"Only your custom system prompt (configured in Settings) will be used."))),g&&_t.default.createElement("div",{className:"tw-flex tw-gap-2 tw-pt-1"},_t.default.createElement(X,{size:"sm",variant:"destructive",onClick:P,className:"tw-h-7 tw-text-xs"},"Disable Builtin"),_t.default.createElement(X,{size:"sm",variant:"ghost",onClick:A,className:"tw-h-7 tw-bg-transparent tw-text-xs"},"Cancel")))))))),_t.default.createElement(Jp,null),_t.default.createElement("div",{className:"tw-shrink-0 tw-rounded-md tw-bg-primary tw-px-4 tw-py-1"},_t.default.createElement("div",{className:"tw-flex tw-flex-row tw-flex-wrap"},_t.default.createElement("span",{className:"tw-text-xs tw-text-normal"},_t.default.createElement("span",{className:" tw-italic"},"System Prompt and Disable Builtin System Prompt")," ",_t.default.createElement("strong",null,"apply to this chat session only"),";",_t.default.createElement("br",null),"other settings are ",_t.default.createElement("strong",null,"bound to the current model"),".")))))):null}async function _Yt(){try{let{getSettings:t}=await Promise.resolve().then(()=>(Se(),qy)),e=t();if(e.enableSemanticSearchV3){let r=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0});Fa(e)?new Nl.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new Nl.Notice(`Semantic search index refreshed with ${r} documents.`)}else new Nl.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(t){z("Error refreshing vault index:",t),new Nl.Notice("Failed to refresh vault index. Check console for details.")}}async function SYt(){try{let{getSettings:t}=await Promise.resolve().then(()=>(Se(),qy)),e=t();if(e.enableSemanticSearchV3){let r=await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!0,{userInitiated:!0});Fa(e)?new Nl.Notice("Miyo folder index refresh started. Open the Miyo app to check details."):new Nl.Notice(`Semantic search index rebuilt with ${r} documents.`)}else new Nl.Notice("Lexical search builds indexes on demand. No manual indexing required.")}catch(t){z("Error force reindexing vault:",t),new Nl.Notice("Failed to force reindex vault. Check console for details.")}}async function W_e(t){let e=br();if(!e){new Nl.Notice("No project is currently selected to reload.");return}try{rg(!0),await ti.getInstance().invalidateMarkdownContext(e,!0);let n=t.plugins.getPlugin("copilot");if(n&&n.projectManager)await n.projectManager.getProjectContext(e.id),await n.projectManager.getCurrentChainManager().createChainWithNewModel(),new Nl.Notice(`Project context for "${e.name}" reloaded successfully.`);else throw new Error("Copilot plugin or ProjectManager not available.")}catch(n){z("Error reloading project context:",n),uv(n)||new Nl.Notice("Failed to reload project context. Check console for details.")}finally{rg(!1)}}async function TYt(t){let e=br();if(!e){new Nl.Notice("No project is currently selected to rebuild.");return}new Cr(t,async()=>{try{rg(!0),new Nl.Notice(`Force rebuilding context for project: ${e.name}... This will take some time and re-fetch all data.`,1e4),mB.resetRateLimitNoticeTimer(),await ti.getInstance().clearForProject(e),new Nl.Notice(`Cache for project "${e.name}" has been cleared.`);let r=t.plugins.getPlugin("copilot");if(r&&r.projectManager)await r.projectManager.getProjectContext(e.id),new Nl.Notice(`Project context for "${e.name}" rebuilt successfully from scratch.`);else throw new Error("Copilot plugin or ProjectManager not available for rebuild.")}catch(r){z("Error force rebuilding project context:",r),uv(r)||new Nl.Notice("Failed to force rebuild project context. Check console for details.")}finally{rg(!1)}},`DANGER: This will permanently delete all cached data (markdown, web URLs, YouTube transcripts, and processed file content) for the project "${e.name}" from both memory and disk. The context will then be rebuilt from scratch, re-fetching all remote data and re-processing all local files. This cannot be undone. Are you absolutely sure?`,"Force Rebuild Project Context").open()}function Vst({onNewChat:t,onSaveAsNote:e,onLoadHistory:n,onModeChange:r,onCloseProject:o,chatHistory:i,onUpdateChatTitle:s,onDeleteChat:a,onLoadChat:l,onOpenSourceFile:c,latestTokenCount:u}){let d=tr(),f=Ht(),[p,m]=kd(),h=ZN(),g=async y=>{p==="project"&&y!=="project"&&f.autosaveChat&&await e(),m(y),r(y),y!=="project"&&(Gx(null),o?.())};return Pt.default.createElement("div",{className:"tw-flex tw-w-full tw-items-center tw-justify-between tw-p-1"},Pt.default.createElement("div",{className:"tw-flex-1"},Pt.default.createElement(qj,null,Pt.default.createElement(Gj,{asChild:!0},Pt.default.createElement(X,{variant:"ghost2",size:"fit",className:"tw-ml-1 tw-text-sm tw-text-muted"},p==="llm_chain"&&"chat (free)",p==="vault_qa"&&"vault QA (free)",p==="copilot_plus"&&Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Pt.default.createElement(ql,{className:"tw-size-4"}),"copilot plus"),p==="project"&&"projects (alpha)",Pt.default.createElement(hr,{className:"tw-mt-0.5 tw-size-5"}))),Pt.default.createElement(sd,{align:"start"},Pt.default.createElement(wr,{onSelect:()=>{g("llm_chain")}},"chat (free)"),Pt.default.createElement(wr,{onSelect:()=>{g("vault_qa")}},"vault QA (free)"),h?Pt.default.createElement(wr,{onSelect:()=>{g("copilot_plus")}},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Pt.default.createElement(ql,{className:"tw-size-4"}),"copilot plus")):Pt.default.createElement(wr,{onSelect:()=>{hT(Vy.CHAT_MODE_SELECT),o?.()}},"copilot plus",Pt.default.createElement(aw,{className:"tw-size-3"})),h?Pt.default.createElement(wr,{className:"tw-flex tw-items-center tw-gap-1",onSelect:()=>{g("project")}},Pt.default.createElement(YS,{className:"tw-size-4"}),"projects (alpha)"):Pt.default.createElement(wr,{onSelect:()=>{hT(Vy.CHAT_MODE_SELECT),o?.()}},"copilot plus",Pt.default.createElement(aw,{className:"tw-size-3"}))))),Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Pt.default.createElement("div",{className:"tw-mr-2"},Pt.default.createElement(oit,{tokenCount:u??null})),Pt.default.createElement(cn,null,Pt.default.createElement(un,{asChild:!0},Pt.default.createElement(X,{variant:"ghost2",size:"icon",title:"New Chat",onClick:t},Pt.default.createElement(S$,{className:"tw-size-4"}))),Pt.default.createElement(on,null,"New Chat")),p!=="project"&&Pt.default.createElement(jst,null),!f.autosaveChat&&Pt.default.createElement(cn,null,Pt.default.createElement(un,{asChild:!0},Pt.default.createElement(X,{variant:"ghost2",size:"icon",title:"Save Chat as Note",onClick:()=>void e()},Pt.default.createElement(m$,{className:"tw-size-4"}))),Pt.default.createElement(on,null,"Save Chat as Note")),Pt.default.createElement(cn,null,Pt.default.createElement(rit,{chatHistory:i,onUpdateTitle:s,onDeleteChat:a,onLoadChat:l,onOpenSourceFile:c},Pt.default.createElement(un,{asChild:!0},Pt.default.createElement(X,{variant:"ghost2",size:"icon",title:"Chat History",onClick:n},Pt.default.createElement(x$,{className:"tw-size-4"})))),Pt.default.createElement(on,null,"Chat History")),Pt.default.createElement(qj,null,Pt.default.createElement(Gj,{asChild:!0},Pt.default.createElement(X,{variant:"ghost2",size:"icon",title:"Advanced Settings"},Pt.default.createElement(eb,{className:"tw-size-4"}))),Pt.default.createElement(sd,{align:"end",className:"tw-w-64"},Pt.default.createElement(wr,{className:"tw-flex tw-justify-between",onSelect:y=>{y.preventDefault(),pe("showSuggestedPrompts",!f.showSuggestedPrompts)}},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Pt.default.createElement(ql,{className:"tw-size-4"}),"Suggested Prompt"),Pt.default.createElement(uh,{checked:f.showSuggestedPrompts})),Pt.default.createElement(wr,{className:"tw-flex tw-justify-between",onSelect:y=>{y.preventDefault(),pe("showRelevantNotes",!f.showRelevantNotes)}},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Pt.default.createElement(Ur,{className:"tw-size-4"}),"Relevant Note"),Pt.default.createElement(uh,{checked:f.showRelevantNotes})),Pt.default.createElement(wr,{className:"tw-flex tw-justify-between",onSelect:y=>{y.preventDefault(),pe("autoAcceptEdits",!f.autoAcceptEdits)}},Pt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Pt.default.createElement(Pu,{className:"tw-size-4"}),"Auto-accept Edits"),Pt.default.createElement(uh,{checked:f.autoAcceptEdits})),p==="project"?Pt.default.createElement(Pt.default.Fragment,null,Pt.default.createElement(wr,{className:"tw-flex tw-items-center tw-gap-2",onSelect:()=>void W_e(d)},Pt.default.createElement(zf,{className:"tw-size-4"}),"Reload Current Project"),Pt.default.createElement(wr,{className:"tw-flex tw-items-center tw-gap-2",onSelect:()=>void TYt(d)},Pt.default.createElement(dl,{className:"tw-size-4"}),"Force Rebuild Context")):Pt.default.createElement(Pt.default.Fragment,null,Pt.default.createElement(wr,{className:"tw-flex tw-items-center tw-gap-2",onSelect:()=>void _Yt()},Pt.default.createElement(zf,{className:"tw-size-4"}),"Refresh Vault Index"),Pt.default.createElement(wr,{className:"tw-flex tw-items-center tw-gap-2",onSelect:()=>{new Cr(d,()=>SYt(),"This will delete and rebuild your entire vault index from scratch. This operation cannot be undone. Are you sure you want to proceed?","Force Reindex Vault").open()}},Pt.default.createElement(dl,{className:"tw-size-4"}),"Force Reindex Vault"))))))}Ir();Qi();rn();var wt=N(U());vt();rn();Qi();Kt();Se();qe();var Wst=({vaultToggle:t,setVaultToggle:e,webToggle:n,setWebToggle:r,composerToggle:o,setComposerToggle:i,autonomousAgentToggle:s,setAutonomousAgentToggle:a,onVaultToggleOff:l,onWebToggleOff:c,onComposerToggleOff:u,currentChain:d})=>{let f=Mc(d),p=f&&d!=="project",m=()=>{let w=!s;a(w),pe("enableAutonomousAgent",w)},h=()=>{let w=!t;e(w),!w&&l&&l()},g=()=>{let w=!n;r(w),!w&&c&&c()},y=()=>{let w=!o;i(w),!w&&u&&u()};return f?wt.default.createElement(uu,{delayDuration:0},wt.default.createElement("div",{className:"tw-hidden tw-items-center tw-gap-1.5 @[420px]/chat-input:tw-flex"},p&&wt.default.createElement(cn,null,wt.default.createElement(un,{asChild:!0},wt.default.createElement(X,{variant:"ghost2",size:"fit",onClick:m,className:oe("tw-text-muted hover:tw-text-accent",s&&"tw-text-accent tw-bg-accent/10")},wt.default.createElement(zA,{className:"tw-size-4"}))),wt.default.createElement(on,{className:"tw-px-1 tw-py-0.5"},"Toggle autonomous agent mode")),!s&&wt.default.createElement(wt.default.Fragment,null,wt.default.createElement(cn,null,wt.default.createElement(un,{asChild:!0},wt.default.createElement(X,{variant:"ghost2",size:"fit",onClick:h,className:oe("tw-text-muted hover:tw-text-accent",t&&"tw-text-accent tw-bg-accent/10")},wt.default.createElement(xm,{className:"tw-size-4"}))),wt.default.createElement(on,{className:"tw-px-1 tw-py-0.5"},"Toggle vault search")),wt.default.createElement(cn,null,wt.default.createElement(un,{asChild:!0},wt.default.createElement(X,{variant:"ghost2",size:"fit",onClick:g,className:oe("tw-text-muted hover:tw-text-accent",n&&"tw-text-accent tw-bg-accent/10")},wt.default.createElement(Br,{className:"tw-size-4"}))),wt.default.createElement(on,{className:"tw-px-1 tw-py-0.5"},"Toggle web search")),wt.default.createElement(cn,null,wt.default.createElement(un,{asChild:!0},wt.default.createElement(X,{variant:"ghost2",size:"fit",onClick:y,className:oe("tw-text-muted hover:tw-text-accent",o&&"tw-text-accent tw-bg-accent/10")},wt.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-0.5"},wt.default.createElement(ql,{className:"tw-size-2"}),wt.default.createElement(Rc,{className:"tw-size-3"})))),wt.default.createElement(on,{className:"tw-px-1 tw-py-0.5"},"Toggle composer (note editing)")))),wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-0.5 @[420px]/chat-input:tw-hidden"},wt.default.createElement(xy,null,wt.default.createElement(by,{asChild:!0},wt.default.createElement(X,{variant:"ghost2",size:"fit",className:"tw-text-muted hover:tw-text-accent"},wt.default.createElement(Nd,{className:"tw-size-4"}))),wt.default.createElement(sd,{align:"end",className:"tw-w-56"},p&&wt.default.createElement(wr,{onClick:m,className:"tw-flex tw-items-center tw-justify-between"},wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},wt.default.createElement(zA,{className:"tw-size-4"}),wt.default.createElement("span",null,"Autonomous Agent")),s&&wt.default.createElement(Ro,{className:"tw-size-4"})),!s&&wt.default.createElement(wt.default.Fragment,null,wt.default.createElement(wr,{onClick:h,className:"tw-flex tw-items-center tw-justify-between"},wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},wt.default.createElement(xm,{className:"tw-size-4"}),wt.default.createElement("span",null,"Vault Search")),t&&wt.default.createElement(Ro,{className:"tw-size-4"})),wt.default.createElement(wr,{onClick:g,className:"tw-flex tw-items-center tw-justify-between"},wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},wt.default.createElement(Br,{className:"tw-size-4"}),wt.default.createElement("span",null,"Web Search")),n&&wt.default.createElement(Ro,{className:"tw-size-4"})),wt.default.createElement(wr,{onClick:y,className:"tw-flex tw-items-center tw-justify-between"},wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},wt.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-0.5"},wt.default.createElement(ql,{className:"tw-size-2"}),wt.default.createElement(Rc,{className:"tw-size-3"})),wt.default.createElement("span",null,"Composer")),o&&wt.default.createElement(Ro,{className:"tw-size-4"}))),s&&wt.default.createElement(wt.default.Fragment,null,wt.default.createElement(wr,{disabled:!0,className:"tw-flex tw-items-center tw-justify-between tw-opacity-50"},wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},wt.default.createElement(xm,{className:"tw-size-4"}),wt.default.createElement("span",null,"Vault Search"))),wt.default.createElement(wr,{disabled:!0,className:"tw-flex tw-items-center tw-justify-between tw-opacity-50"},wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},wt.default.createElement(Br,{className:"tw-size-4"}),wt.default.createElement("span",null,"Web Search"))),wt.default.createElement(wr,{disabled:!0,className:"tw-flex tw-items-center tw-justify-between tw-opacity-50"},wt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},wt.default.createElement("span",{className:"tw-flex tw-items-center tw-gap-0.5"},wt.default.createElement(ql,{className:"tw-size-2"}),wt.default.createElement(Rc,{className:"tw-size-3"})),wt.default.createElement("span",null,"Composer")))))))):null};qe();fL();Se();qe();function o7(t){return`${t.name}-${t.size}-${t.lastModified}-${t.type}`}function i7(t,e){if(e.length===0)return t;let n=new Set(t.map(o7)),r=e.filter(o=>{let i=o7(o);return n.has(i)?!1:(n.add(i),!0)});return r.length===0?t:[...t,...r]}vt();var tV=require("obsidian"),ct=N(U());var gTe={};zn(gTe,{$addUpdateTag:()=>tct,$applyNodeReplacement:()=>L4,$caretFromPoint:()=>eS,$caretRangeFromSelection:()=>kSe,$cloneWithProperties:()=>lct,$comparePointCaretNext:()=>pTe,$copyNode:()=>aTe,$create:()=>n7t,$createLineBreakNode:()=>VL,$createNodeSelection:()=>qSe,$createParagraphNode:()=>ox,$createPoint:()=>Eh,$createRangeSelection:()=>Nlt,$createRangeSelectionFromDom:()=>IZt,$createTabNode:()=>$7,$createTextNode:()=>Xa,$extendCaretToRange:()=>dTe,$getAdjacentChildCaret:()=>XL,$getAdjacentNode:()=>Qlt,$getAdjacentSiblingOrParentSiblingCaret:()=>u7t,$getCaretInDirection:()=>tS,$getCaretRange:()=>Q_,$getCaretRangeInDirection:()=>hTe,$getCharacterOffsets:()=>CSe,$getChildCaret:()=>ax,$getChildCaretAtIndex:()=>gct,$getChildCaretOrSelf:()=>dct,$getCollapsedCaretRange:()=>fct,$getCommonAncestor:()=>v4,$getCommonAncestorResultBranchOrder:()=>mTe,$getEditor:()=>lTe,$getNearestNodeFromDOMNode:()=>V7,$getNearestRootOrShadowRoot:()=>rct,$getNodeByKey:()=>wa,$getNodeByKeyOrThrow:()=>oct,$getPreviousSelection:()=>lE,$getRoot:()=>md,$getSelection:()=>Gr,$getSiblingCaret:()=>rl,$getState:()=>w7,$getStateChange:()=>eZt,$getTextContent:()=>AZt,$getTextNodeOffset:()=>Ph,$getTextPointCaret:()=>X_,$getTextPointCaretSlice:()=>ESe,$getWritableNodeState:()=>FSe,$hasAncestor:()=>N7,$hasUpdateTag:()=>ZZt,$insertNodes:()=>EZt,$isBlockElementNode:()=>TZt,$isChildCaret:()=>Ih,$isDecoratorNode:()=>Ao,$isElementNode:()=>Le,$isExtendableTextPointCaret:()=>hct,$isInlineElementOrDecoratorNode:()=>JZt,$isLeafNode:()=>qZt,$isLineBreakNode:()=>eE,$isNodeCaret:()=>i7t,$isNodeSelection:()=>F7,$isParagraphNode:()=>FZt,$isRangeSelection:()=>dn,$isRootNode:()=>fd,$isRootOrShadowRoot:()=>Ah,$isSiblingCaret:()=>aE,$isTabNode:()=>KSe,$isTextNode:()=>Bt,$isTextPointCaret:()=>ix,$isTextPointCaretSlice:()=>c7t,$isTokenOrSegmented:()=>ex,$isTokenOrTab:()=>q_,$nodesOfType:()=>YZt,$normalizeCaret:()=>Sh,$normalizeSelection__EXPERIMENTAL:()=>v7,$onUpdate:()=>nct,$parseSerializedNode:()=>NZt,$removeTextFromCaretRange:()=>mct,$rewindSiblingCaret:()=>n1,$selectAll:()=>GZt,$setCompositionKey:()=>el,$setPointFromCaret:()=>QL,$setSelection:()=>hd,$setSelectionFromCaretRange:()=>pct,$setState:()=>tZt,$splitAtPointCaretNext:()=>p7t,$splitNode:()=>XZt,$updateRangeSelectionFromCaretRange:()=>x4,ArtificialNode__DO_NOT_USE:()=>A7,BLUR_COMMAND:()=>ylt,CAN_REDO_COMMAND:()=>pZt,CAN_UNDO_COMMAND:()=>mZt,CLEAR_EDITOR_COMMAND:()=>dZt,CLEAR_HISTORY_COMMAND:()=>fZt,CLICK_COMMAND:()=>Qat,COLLABORATION_TAG:()=>Ult,COMMAND_PRIORITY_CRITICAL:()=>VZt,COMMAND_PRIORITY_EDITOR:()=>UZt,COMMAND_PRIORITY_HIGH:()=>jZt,COMMAND_PRIORITY_LOW:()=>BZt,COMMAND_PRIORITY_NORMAL:()=>zZt,CONTROLLED_TEXT_INSERTION_COMMAND:()=>$L,COPY_COMMAND:()=>VSe,CUT_COMMAND:()=>WSe,DELETE_CHARACTER_COMMAND:()=>P4,DELETE_LINE_COMMAND:()=>A4,DELETE_WORD_COMMAND:()=>E4,DRAGEND_COMMAND:()=>hlt,DRAGOVER_COMMAND:()=>mlt,DRAGSTART_COMMAND:()=>plt,DROP_COMMAND:()=>flt,DecoratorNode:()=>k4,ElementNode:()=>J_,FOCUS_COMMAND:()=>glt,FORMAT_ELEMENT_COMMAND:()=>uZt,FORMAT_TEXT_COMMAND:()=>H_,HISTORIC_TAG:()=>OZt,HISTORY_MERGE_TAG:()=>m7,HISTORY_PUSH_TAG:()=>RZt,INDENT_CONTENT_COMMAND:()=>lZt,INSERT_LINE_BREAK_COMMAND:()=>h4,INSERT_PARAGRAPH_COMMAND:()=>pSe,INSERT_TAB_COMMAND:()=>aZt,INTERNAL_$isBlock:()=>rx,IS_ALL_FORMATTING:()=>Fat,IS_BOLD:()=>LYt,IS_CODE:()=>$Yt,IS_HIGHLIGHT:()=>R7,IS_ITALIC:()=>DYt,IS_STRIKETHROUGH:()=>C4,IS_SUBSCRIPT:()=>FYt,IS_SUPERSCRIPT:()=>UYt,IS_UNDERLINE:()=>_4,KEY_ARROW_DOWN_COMMAND:()=>slt,KEY_ARROW_LEFT_COMMAND:()=>rlt,KEY_ARROW_RIGHT_COMMAND:()=>tlt,KEY_ARROW_UP_COMMAND:()=>ilt,KEY_BACKSPACE_COMMAND:()=>llt,KEY_DELETE_COMMAND:()=>ult,KEY_DOWN_COMMAND:()=>elt,KEY_ENTER_COMMAND:()=>_7,KEY_ESCAPE_COMMAND:()=>clt,KEY_MODIFIER_COMMAND:()=>wlt,KEY_SPACE_COMMAND:()=>alt,KEY_TAB_COMMAND:()=>dlt,LineBreakNode:()=>jL,MOVE_TO_END:()=>nlt,MOVE_TO_START:()=>olt,NODE_STATE_KEY:()=>qYt,OUTDENT_CONTENT_COMMAND:()=>cZt,PASTE_COMMAND:()=>BSe,PASTE_TAG:()=>LZt,ParagraphNode:()=>KL,REDO_COMMAND:()=>jSe,REMOVE_TEXT_COMMAND:()=>mSe,RootNode:()=>HL,SELECTION_CHANGE_COMMAND:()=>USe,SELECTION_INSERT_CLIPBOARD_NODES_COMMAND:()=>sZt,SELECT_ALL_COMMAND:()=>hSe,SKIP_COLLAB_TAG:()=>DZt,SKIP_DOM_SELECTION_TAG:()=>zlt,SKIP_SCROLL_INTO_VIEW_TAG:()=>Blt,TEXT_TYPE_TO_FORMAT:()=>vc,TabNode:()=>WL,TextNode:()=>oE,UNDO_COMMAND:()=>zSe,buildImportMap:()=>yZt,createCommand:()=>Wn,createEditor:()=>WZt,createSharedNodeState:()=>Hat,createState:()=>QYt,flipDirection:()=>nS,getDOMOwnerDocument:()=>iTe,getDOMSelection:()=>Ay,getDOMSelectionFromTarget:()=>ict,getDOMTextNode:()=>sE,getEditorPropertyFromDOMNode:()=>O4,getNearestEditorFromDOMNode:()=>eTe,getRegisteredNode:()=>XSe,getRegisteredNodeOrThrow:()=>JSe,isBlockDomNode:()=>ISe,isCurrentlyReadOnlyMode:()=>e1,isDOMDocumentNode:()=>Wlt,isDOMNode:()=>t1,isDOMTextNode:()=>ky,isDOMUnmanaged:()=>uct,isDocumentFragment:()=>sct,isExactShortcutMatch:()=>ao,isHTMLAnchorElement:()=>QZt,isHTMLElement:()=>pu,isInlineDomNode:()=>act,isLexicalEditor:()=>z7,isModifierMatch:()=>Xlt,isSelectionCapturedInDecoratorInput:()=>QSe,isSelectionWithinEditor:()=>N4,makeStepwiseIterator:()=>fTe,removeFromParent:()=>G_,resetRandomKey:()=>HZt,setDOMUnmanaged:()=>t7t,setNodeIndentFromDOM:()=>cct});function De(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),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.`)}var kh=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,IYt=kh&&"documentMode"in document?document.documentMode:null,Ey=kh&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),tE=kh&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),h7=!(!kh||!("InputEvent"in window)||IYt)&&"getTargetRanges"in new window.InputEvent("input"),b4=kh&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),BL=kh&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,PYt=kh&&/Android/.test(navigator.userAgent),Dat=kh&&/^(?=.*Chrome).*/i.test(navigator.userAgent),Hst=kh&&PYt&&Dat,g7=kh&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!Dat;function y7(...t){let e=[];for(let n of t)if(n&&typeof n=="string")for(let[r]of n.matchAll(/\S+/g))e.push(r);return e}var EYt=1,AYt=3,kYt=9,MYt=11,nE=0,$at=1,zL=2,NYt=0,OYt=1,RYt=2,LYt=1,DYt=2,C4=4,_4=8,$Yt=16,FYt=32,UYt=64,R7=128,Fat=1792|(112|(3|C4|_4)|R7),MSe=1,NSe=2,OSe=3,RSe=4,LSe=5,DSe=6,L7=b4||BL||g7?"\xA0":"\u200B",sx=`

`,BYt=tE?"\xA0":L7,Uat="\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",Bat="A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF",zYt=new RegExp("^[^"+Bat+"]*["+Uat+"]"),jYt=new RegExp("^[^"+Uat+"]*["+Bat+"]"),vc={bold:1,capitalize:1024,code:16,highlight:R7,italic:2,lowercase:256,strikethrough:C4,subscript:32,superscript:64,underline:_4,uppercase:512},VYt={directionless:1,unmergeable:2},Kst={center:NSe,end:DSe,justify:RSe,left:MSe,right:OSe,start:LSe},WYt={[NSe]:"center",[DSe]:"end",[RSe]:"justify",[MSe]:"left",[OSe]:"right",[LSe]:"start"},HYt={normal:0,segmented:2,token:1},KYt={[NYt]:"normal",[RYt]:"segmented",[OYt]:"token"},qYt="$",qst="$config";function zat(t,e,n,r,o,i){let s=t.getFirstChild();for(;s!==null;){let a=s.__key;s.__parent===e&&(Le(s)&&zat(s,a,n,r,o,i),n.has(a)||i.delete(a),o.push(a)),s=s.getNextSibling()}}var GYt=100,oSe=!1,$Se=0;function YYt(t){$Se=t.timeStamp}function H_e(t,e,n){let r=t.nodeName==="BR",o=e.__lexicalLineBreak;return o&&(t===o||r&&t.previousSibling===o)||r&&j7(t,n)!==void 0}function ZYt(t,e,n){let r=Ay(em(n)),o=null,i=null;r!==null&&r.anchorNode===t&&(o=r.anchorOffset,i=r.focusOffset);let s=t.nodeValue;s!==null&&rTe(e,s,o,i,!1)}function JYt(t,e,n){if(dn(t)){let r=t.anchor.getNode();if(r.is(n)&&t.format!==r.getFormat())return!1}return ky(e)&&n.isAttached()}function XYt(t,e,n,r){for(let o=t;o&&!uct(o);o=R4(o)){let i=j7(o,e);if(i!==void 0){let s=wa(i,n);if(s)return Ao(s)||!pu(o)?void 0:[o,s]}else if(o===r)return[r,Glt(n)]}}function jat(t,e,n){oSe=!0;let r=performance.now()-$Se>GYt;try{wf(t,()=>{let o=Gr()||function(f){return f.getEditorState().read(()=>{let p=Gr();return p!==null?p.clone():null})}(t),i=new Map,s=t.getRootElement(),a=t._editorState,l=t._blockCursorElement,c=!1,u="";for(let f=0;f<e.length;f++){let p=e[f],m=p.type,h=p.target,g=XYt(h,t,a,s);if(!g)continue;let[y,w]=g;if(m==="characterData")r&&Bt(w)&&ky(h)&&JYt(o,h,w)&&ZYt(h,w,t);else if(m==="childList"){c=!0;let v=p.addedNodes;for(let _=0;_<v.length;_++){let T=v[_],S=Klt(T),P=T.parentNode;if(P!=null&&T!==l&&S===null&&!H_e(T,P,t)){if(tE){let A=(pu(T)?T.innerText:null)||T.nodeValue;A&&(u+=A)}P.removeChild(T)}}let x=p.removedNodes,b=x.length;if(b>0){let _=0;for(let T=0;T<b;T++){let S=x[T];(H_e(S,h,t)||l===S)&&(h.appendChild(S),_++)}b!==_&&i.set(y,w)}}}if(i.size>0)for(let[f,p]of i)p.reconcileObservedMutation(f,t);let d=n.takeRecords();if(d.length>0){for(let f=0;f<d.length;f++){let p=d[f],m=p.addedNodes,h=p.target;for(let g=0;g<m.length;g++){let y=m[g],w=y.parentNode;w==null||y.nodeName!=="BR"||H_e(y,h,t)||w.removeChild(y)}}n.takeRecords()}o!==null&&(c&&hd(o),tE&&ect(t)&&o.insertRawText(u))})}finally{oSe=!1}}function Vat(t){let e=t._observer;e!==null&&jat(t,e.takeRecords(),e)}function Wat(t){(function(e){$Se===0&&em(e).addEventListener("textInput",YYt,!0)})(t),t._observer=new MutationObserver((e,n)=>{jat(t,e,n)})}var iSe=class{constructor(e,n){this.key=e,this.parse=n.parse.bind(n),this.unparse=(n.unparse||nZt).bind(n),this.isEqual=(n.isEqual||Object.is).bind(n),this.defaultValue=this.parse(void 0)}};function QYt(t,e){return new iSe(t,e)}function w7(t,e,n="latest"){let r=(n==="latest"?t.getLatest():t).__state;return r?r.getValue(e):e.defaultValue}function eZt(t,e,n){let r=w7(t,n,"direct"),o=w7(e,n,"direct");return n.isEqual(r,o)?null:[r,o]}function tZt(t,e,n){let r;if(Qa(),typeof n=="function"){let i=t.getLatest(),s=w7(i,e);if(r=n(s),e.isEqual(s,r))return i}else r=n;let o=t.getWritable();return FSe(o).updateFromKnown(e,r),o}function Hat(t){let e=new Map,n=new Set;for(let r=typeof t=="function"?t:t.replace;r.prototype&&r.prototype.getType!==void 0;r=Object.getPrototypeOf(r)){let{ownNodeConfig:o}=cTe(r);if(o&&o.stateConfigs)for(let i of o.stateConfigs){let s;"stateConfig"in i?(s=i.stateConfig,i.flat&&n.add(s.key)):s=i,e.set(s.key,s)}}return{flatKeys:n,sharedConfigMap:e}}var sSe=class t{constructor(e,n,r=void 0,o=new Map,i=void 0){this.node=e,this.sharedNodeState=n,this.unknownState=r,this.knownState=o;let{sharedConfigMap:s}=this.sharedNodeState,a=i!==void 0?i:function(l,c,u){let d=u.size;if(c)for(let f in c){let p=l.get(f);p&&u.has(p)||d++}return d}(s,r,o);this.size=a}getValue(e){let n=this.knownState.get(e);if(n!==void 0)return n;this.sharedNodeState.sharedConfigMap.set(e.key,e);let r=e.defaultValue;if(this.unknownState&&e.key in this.unknownState){let o=this.unknownState[e.key];o!==void 0&&(r=e.parse(o)),this.updateFromKnown(e,r)}return r}getInternalState(){return[this.unknownState,this.knownState]}toJSON(){let e={...this.unknownState},n={};for(let[r,o]of this.knownState)r.isEqual(o,r.defaultValue)?delete e[r.key]:e[r.key]=r.unparse(o);for(let r of this.sharedNodeState.flatKeys)r in e&&(n[r]=e[r],delete e[r]);return Gst(e)&&(n.$=e),n}getWritable(e){if(this.node===e)return this;let{sharedNodeState:n,unknownState:r}=this,o=new Map(this.knownState);return new t(e,n,function(i,s,a){let l;if(a)for(let[c,u]of Object.entries(a)){let d=i.get(c);d?s.has(d)||s.set(d,d.parse(u)):(l=l||{},l[c]=u)}return l}(n.sharedConfigMap,o,r),o,this.size)}updateFromKnown(e,n){let r=e.key;this.sharedNodeState.sharedConfigMap.set(r,e);let{knownState:o,unknownState:i}=this;o.has(e)||i&&r in i||(i&&(delete i[r],this.unknownState=Gst(i)),this.size++),o.set(e,n)}updateFromUnknown(e,n){let r=this.sharedNodeState.sharedConfigMap.get(e);r?this.updateFromKnown(r,r.parse(n)):(this.unknownState=this.unknownState||{},e in this.unknownState||this.size++,this.unknownState[e]=n)}updateFromJSON(e){let{knownState:n}=this;for(let r of n.keys())n.set(r,r.defaultValue);if(this.size=n.size,this.unknownState=void 0,e)for(let[r,o]of Object.entries(e))this.updateFromUnknown(r,o)}};function FSe(t){let e=t.getWritable(),n=e.__state?e.__state.getWritable(e):new sSe(e,Kat(e));return e.__state=n,n}function Kat(t){return t.__state?t.__state.sharedNodeState:JSe(lTe(),t.getType()).sharedNodeState}function Gst(t){if(t)for(let e in t)return t}function nZt(t){return t}function Yst(t,e,n){for(let[r,o]of e.knownState){if(t.has(r.key))continue;t.add(r.key);let i=n?n.getValue(r):r.defaultValue;if(i!==o&&!r.isEqual(i,o))return!0}return!1}function Zst(t,e,n){let{unknownState:r}=e,o=n?n.unknownState:void 0;if(r){for(let[i,s]of Object.entries(r))if(!t.has(i)&&(t.add(i),s!==(o?o[i]:void 0)))return!0}return!1}function Jst(t,e){let n=t.__state;return n&&n.node===t?n.getWritable(e):n}function Xst(t,e){let n=t.__mode,r=t.__format,o=t.__style,i=e.__mode,s=e.__format,a=e.__style,l=t.__state,c=e.__state;return(n===null||n===i)&&(r===null||r===s)&&(o===null||o===a)&&(t.__state===null||l===c||function(u,d){if(u===d)return!0;if(u&&d&&u.size!==d.size)return!1;let f=new Set;return!(u&&Yst(f,u,d)||d&&Yst(f,d,u)||u&&Zst(f,u,d)||d&&Zst(f,d,u))}(l,c))}function Qst(t,e){let n=t.mergeWithSibling(e),r=wi()._normalizedNodes;return r.add(t.__key),r.add(e.__key),n}function eat(t){let e,n,r=t;if(r.__text!==""||!r.isSimpleText()||r.isUnmergeable()){for(;(e=r.getPreviousSibling())!==null&&Bt(e)&&e.isSimpleText()&&!e.isUnmergeable();){if(e.__text!==""){if(Xst(e,r)){r=Qst(e,r);break}break}e.remove()}for(;(n=r.getNextSibling())!==null&&Bt(n)&&n.isSimpleText()&&!n.isUnmergeable();){if(n.__text!==""){if(Xst(r,n)){r=Qst(r,n);break}break}n.remove()}}else r.remove()}function v7(t){return tat(t.anchor),tat(t.focus),t}function tat(t){for(;t.type==="element";){let e=t.getNode(),n=t.offset,r,o;if(n===e.getChildrenSize()?(r=e.getChildAtIndex(n-1),o=!0):(r=e.getChildAtIndex(n),o=!1),Bt(r)){t.set(r.__key,o?r.getTextContentSize():0,"text",!0);break}if(!Le(r))break;t.set(r.__key,o?r.getChildrenSize():0,"element",!0)}}var Y_,fu,S4,D7,aSe,lSe,rE,Th,cSe,T4,ya="",du="",Iy=null,Py="",tx="",qat=!1,I4=!1,d7=null;function x7(t,e){let n=rE.get(t);if(e!==null){let r=fSe(t);r.parentNode===e&&e.removeChild(r)}if(Th.has(t)||fu._keyToDOMMap.delete(t),Le(n)){let r=C7(n,rE);uSe(r,0,r.length-1,null)}n!==void 0&&oTe(T4,S4,D7,n,"destroyed")}function uSe(t,e,n,r){let o=e;for(;o<=n;++o){let i=t[o];i!==void 0&&x7(i,r)}}function XP(t,e){t.setProperty("text-align",e)}var rZt="40px";function Gat(t,e){let n=Y_.theme.indent;if(typeof n=="string"){let o=t.classList.contains(n);e>0&&!o?t.classList.add(n):e<1&&o&&t.classList.remove(n)}let r=getComputedStyle(t).getPropertyValue("--lexical-indent-base-value")||rZt;t.style.setProperty("padding-inline-start",e===0?"":`calc(${e} * ${r})`)}function Yat(t,e){let n=t.style;e===0?XP(n,""):e===MSe?XP(n,"left"):e===NSe?XP(n,"center"):e===OSe?XP(n,"right"):e===RSe?XP(n,"justify"):e===LSe?XP(n,"start"):e===DSe&&XP(n,"end")}function b7(t,e){let n=Th.get(t);n===void 0&&De(60);let r=n.createDOM(Y_,fu);if(function(o,i,s){let a=s._keyToDOMMap;(function(l,c,u){let d=`__lexicalKey_${c._key}`;l[d]=u})(i,s,o),a.set(o,i)}(t,r,fu),Bt(n)?r.setAttribute("data-lexical-text","true"):Ao(n)&&r.setAttribute("data-lexical-decorator","true"),Le(n)){let o=n.__indent,i=n.__size;if(o!==0&&Gat(r,o),i!==0){let a=i-1;(function(l,c,u,d){let f=du;du="",dSe(l,u,0,c,u.getDOMSlot(d)),Jat(u,d),du=f})(C7(n,Th),a,n,r)}let s=n.__format;s!==0&&Yat(r,s),n.isInline()||Zat(null,n,r),W7(n)&&(ya+=sx,tx+=sx)}else{let o=n.getTextContent();if(Ao(n)){let i=n.decorate(fu,Y_);i!==null&&Xat(t,i),r.contentEditable="false"}else Bt(n)&&(n.isDirectionless()||(du+=o));ya+=o,tx+=o}return e!==null&&e.insertChild(r),oTe(T4,S4,D7,n,"created"),r}function dSe(t,e,n,r,o){let i=ya;ya="";let s=n;for(;s<=r;++s){b7(t[s],o);let a=Th.get(t[s]);a!==null&&Bt(a)&&(Iy===null&&(Iy=a.getFormat()),Py===""&&(Py=a.getStyle()))}W7(e)&&(ya+=sx),o.element.__lexicalTextContent=ya,ya=i+ya}function nat(t,e){if(t){let n=t.__last;if(n){let r=e.get(n);if(r)return eE(r)?"line-break":Ao(r)&&r.isInline()?"decorator":null}return"empty"}return null}function Zat(t,e,n){let r=nat(t,rE),o=nat(e,Th);r!==o&&e.getDOMSlot(n).setManagedLineBreak(o)}function Jat(t,e){let n=e.__lexicalDirTextContent||"",r=e.__lexicalDir||"";if(n!==du||r!==d7){let o=du==="",i=o?d7:function(s){return zYt.test(s)?"rtl":jYt.test(s)?"ltr":null}(du);if(i!==r){let s=e.classList,a=Y_.theme,l=r!==null?a[r]:void 0,c=i!==null?a[i]:void 0;if(l!==void 0){if(typeof l=="string"){let u=y7(l);l=a[r]=u}s.remove(...l)}if(i===null||o&&i==="ltr")e.removeAttribute("dir");else{if(c!==void 0){if(typeof c=="string"){let u=y7(c);c=a[i]=u}c!==void 0&&s.add(...c)}e.dir=i}I4||(t.getWritable().__dir=i)}d7=i,e.__lexicalDirTextContent=du,e.__lexicalDir=i}}function oZt(t,e,n){let r=du;var o;du="",Iy=null,Py="",function(i,s,a){let l=ya,c=i.__size,u=s.__size;ya="";let d=a.element;if(c===1&&u===1){let f=i.__first,p=s.__first;if(f===p)m4(f,d);else{let h=fSe(f),g=b7(p,null);try{d.replaceChild(g,h)}catch(y){if(typeof y=="object"&&y!=null){let w=`${y.toString()} Parent: ${d.tagName}, new child: {tag: ${g.tagName} key: ${p}}, old child: {tag: ${h.tagName}, key: ${f}}.`;throw new Error(w)}throw y}x7(f,null)}let m=Th.get(p);Bt(m)&&(Iy===null&&(Iy=m.getFormat()),Py===""&&(Py=m.getStyle()))}else{let f=C7(i,rE),p=C7(s,Th);if(f.length!==c&&De(227),p.length!==u&&De(228),c===0)u!==0&&dSe(p,s,0,u-1,a);else if(u===0){if(c!==0){let m=a.after==null&&a.before==null&&a.element.__lexicalLineBreak==null;uSe(f,0,c-1,m?null:d),m&&(d.textContent="")}}else(function(m,h,g,y,w,v){let x=y-1,b=w-1,_,T,S=v.getFirstChild(),P=0,A=0;for(;P<=x&&A<=b;){let $=h[P],B=g[A];if($===B)S=K_e(m4(B,v.element)),P++,A++;else{_===void 0&&(_=new Set(h)),T===void 0&&(T=new Set(g));let F=T.has($),Z=_.has(B);if(F)if(Z){let V=GL(fu,B);V===S?S=K_e(m4(B,v.element)):(v.withBefore(S).insertChild(V),m4(B,v.element)),P++,A++}else b7(B,v.withBefore(S)),A++;else S=K_e(fSe($)),x7($,v.element),P++}let W=Th.get(B);W!==null&&Bt(W)&&(Iy===null&&(Iy=W.getFormat()),Py===""&&(Py=W.getStyle()))}let O=P>x,D=A>b;if(O&&!D){let $=g[b+1],B=$===void 0?null:fu.getElementByKey($);dSe(g,m,A,b,v.withBefore(B))}else D&&!O&&uSe(h,P,x,v.element)})(s,f,p,c,u,a)}W7(s)&&(ya+=sx),d.__lexicalTextContent=ya,ya=l+ya}(t,e,e.getDOMSlot(n)),Jat(e,n),o=e,Iy==null||Iy===o.__textFormat||I4||o.setTextFormat(Iy),function(i){Py===""||Py===i.__textStyle||I4||i.setTextStyle(Py)}(e),du=r}function C7(t,e){let n=[],r=t.__first;for(;r!==null;){let o=e.get(r);o===void 0&&De(101),n.push(r),r=o.__next}return n}function m4(t,e){let n=rE.get(t),r=Th.get(t);n!==void 0&&r!==void 0||De(61);let o=qat||lSe.has(t)||aSe.has(t),i=GL(fu,t);if(n===r&&!o){if(Le(n)){let s=i.__lexicalTextContent;s!==void 0&&(ya+=s,tx+=s);let a=i.__lexicalDirTextContent;a!==void 0&&(du+=a)}else{let s=n.getTextContent();Bt(n)&&!n.isDirectionless()&&(du+=s),tx+=s,ya+=s}return i}if(n!==r&&o&&oTe(T4,S4,D7,r,"updated"),r.updateDOM(n,i,Y_)){let s=b7(t,null);return e===null&&De(62),e.replaceChild(s,i),x7(t,null),s}if(Le(n)&&Le(r)){let s=r.__indent;s!==n.__indent&&Gat(i,s);let a=r.__format;a!==n.__format&&Yat(i,a),o&&(oZt(n,r,i),fd(r)||r.isInline()||Zat(n,r,i)),W7(r)&&(ya+=sx,tx+=sx)}else{let s=r.getTextContent();if(Ao(r)){let a=r.decorate(fu,Y_);a!==null&&Xat(t,a)}else Bt(r)&&!r.isDirectionless()&&(du+=s);ya+=s,tx+=s}if(!I4&&fd(r)&&r.__cachedText!==tx){let s=r.getWritable();s.__cachedText=tx,r=s}return i}function Xat(t,e){let n=fu._pendingDecorators,r=fu._decorators;if(n===null){if(r[t]===e)return;n=qlt(fu)}n[t]=e}function K_e(t){let e=t.nextSibling;return e!==null&&e===fu._blockCursorElement&&(e=e.nextSibling),e}function iZt(t,e,n,r,o,i){ya="",tx="",du="",qat=r===zL,d7=null,fu=n,Y_=n._config,S4=n._nodes,D7=fu._listeners.mutation,aSe=o,lSe=i,rE=t._nodeMap,Th=e._nodeMap,I4=e._readOnly,cSe=new Map(n._keyToDOMMap);let s=new Map;return T4=s,m4("root",null),fu=void 0,S4=void 0,aSe=void 0,lSe=void 0,rE=void 0,Th=void 0,Y_=void 0,cSe=void 0,T4=void 0,s}function fSe(t){let e=cSe.get(t);return e===void 0&&De(75,t),e}function Wn(t){return{type:t}}var USe=Wn("SELECTION_CHANGE_COMMAND"),sZt=Wn("SELECTION_INSERT_CLIPBOARD_NODES_COMMAND"),Qat=Wn("CLICK_COMMAND"),P4=Wn("DELETE_CHARACTER_COMMAND"),h4=Wn("INSERT_LINE_BREAK_COMMAND"),pSe=Wn("INSERT_PARAGRAPH_COMMAND"),$L=Wn("CONTROLLED_TEXT_INSERTION_COMMAND"),BSe=Wn("PASTE_COMMAND"),mSe=Wn("REMOVE_TEXT_COMMAND"),E4=Wn("DELETE_WORD_COMMAND"),A4=Wn("DELETE_LINE_COMMAND"),H_=Wn("FORMAT_TEXT_COMMAND"),zSe=Wn("UNDO_COMMAND"),jSe=Wn("REDO_COMMAND"),elt=Wn("KEYDOWN_COMMAND"),tlt=Wn("KEY_ARROW_RIGHT_COMMAND"),nlt=Wn("MOVE_TO_END"),rlt=Wn("KEY_ARROW_LEFT_COMMAND"),olt=Wn("MOVE_TO_START"),ilt=Wn("KEY_ARROW_UP_COMMAND"),slt=Wn("KEY_ARROW_DOWN_COMMAND"),_7=Wn("KEY_ENTER_COMMAND"),alt=Wn("KEY_SPACE_COMMAND"),llt=Wn("KEY_BACKSPACE_COMMAND"),clt=Wn("KEY_ESCAPE_COMMAND"),ult=Wn("KEY_DELETE_COMMAND"),dlt=Wn("KEY_TAB_COMMAND"),aZt=Wn("INSERT_TAB_COMMAND"),lZt=Wn("INDENT_CONTENT_COMMAND"),cZt=Wn("OUTDENT_CONTENT_COMMAND"),flt=Wn("DROP_COMMAND"),uZt=Wn("FORMAT_ELEMENT_COMMAND"),plt=Wn("DRAGSTART_COMMAND"),mlt=Wn("DRAGOVER_COMMAND"),hlt=Wn("DRAGEND_COMMAND"),VSe=Wn("COPY_COMMAND"),WSe=Wn("CUT_COMMAND"),hSe=Wn("SELECT_ALL_COMMAND"),dZt=Wn("CLEAR_EDITOR_COMMAND"),fZt=Wn("CLEAR_HISTORY_COMMAND"),pZt=Wn("CAN_REDO_COMMAND"),mZt=Wn("CAN_UNDO_COMMAND"),glt=Wn("FOCUS_COMMAND"),ylt=Wn("BLUR_COMMAND"),wlt=Wn("KEY_MODIFIER_COMMAND"),Jv=Object.freeze({}),gSe=30,ySe=[["keydown",function(t,e){if(g4=t.timeStamp,vlt=t.key,!e.isComposing()&&!Et(e,elt,t)&&t.key!=null){if(q_e&&kat(t))return wf(e,()=>{s7(e,G_e)}),q_e=!1,void(G_e="");if(function(n){return ao(n,"ArrowRight",{shiftKey:"any"})}(t))Et(e,tlt,t);else if(function(n){return ao(n,"ArrowRight",Qv)}(t))Et(e,nlt,t);else if(function(n){return ao(n,"ArrowLeft",{shiftKey:"any"})}(t))Et(e,rlt,t);else if(function(n){return ao(n,"ArrowLeft",Qv)}(t))Et(e,olt,t);else if(function(n){return ao(n,"ArrowUp",{altKey:"any",shiftKey:"any"})}(t))Et(e,ilt,t);else if(function(n){return ao(n,"ArrowDown",{altKey:"any",shiftKey:"any"})}(t))Et(e,slt,t);else if(function(n){return ao(n,"Enter",{altKey:"any",ctrlKey:"any",metaKey:"any",shiftKey:!0})}(t))y4=!0,Et(e,_7,t);else if(function(n){return n.key===" "}(t))Et(e,alt,t);else if(function(n){return Ey&&ao(n,"o",{ctrlKey:!0})}(t))t.preventDefault(),y4=!0,Et(e,h4,!0);else if(function(n){return ao(n,"Enter",{altKey:"any",ctrlKey:"any",metaKey:"any"})}(t))y4=!1,Et(e,_7,t);else if(function(n){return ao(n,"Backspace",{shiftKey:"any"})||Ey&&ao(n,"h",{ctrlKey:!0})}(t))kat(t)?Et(e,llt,t):(t.preventDefault(),Et(e,P4,!0));else if(function(n){return n.key==="Escape"}(t))Et(e,clt,t);else if(function(n){return ao(n,"Delete",{})||Ey&&ao(n,"d",{ctrlKey:!0})}(t))(function(n){return n.key==="Delete"})(t)?Et(e,ult,t):(t.preventDefault(),Et(e,P4,!1));else if(function(n){return ao(n,"Backspace",Aat)}(t))t.preventDefault(),Et(e,E4,!0);else if(function(n){return ao(n,"Delete",Aat)}(t))t.preventDefault(),Et(e,E4,!1);else if(function(n){return Ey&&ao(n,"Backspace",{metaKey:!0})}(t))t.preventDefault(),Et(e,A4,!0);else if(function(n){return Ey&&(ao(n,"Delete",{metaKey:!0})||ao(n,"k",{ctrlKey:!0}))}(t))t.preventDefault(),Et(e,A4,!1);else if(function(n){return ao(n,"b",Qv)}(t))t.preventDefault(),Et(e,H_,"bold");else if(function(n){return ao(n,"u",Qv)}(t))t.preventDefault(),Et(e,H_,"underline");else if(function(n){return ao(n,"i",Qv)}(t))t.preventDefault(),Et(e,H_,"italic");else if(function(n){return ao(n,"Tab",{shiftKey:"any"})}(t))Et(e,dlt,t);else if(function(n){return ao(n,"z",Qv)}(t))t.preventDefault(),Et(e,zSe,void 0);else if(function(n){return Ey?ao(n,"z",{metaKey:!0,shiftKey:!0}):ao(n,"y",{ctrlKey:!0})||ao(n,"z",{ctrlKey:!0,shiftKey:!0})}(t))t.preventDefault(),Et(e,jSe,void 0);else{let n=e._editorState._selection;n===null||dn(n)?Mat(t)&&(t.preventDefault(),Et(e,hSe,t)):function(r){return ao(r,"c",Qv)}(t)?(t.preventDefault(),Et(e,VSe,t)):function(r){return ao(r,"x",Qv)}(t)?(t.preventDefault(),Et(e,WSe,t)):Mat(t)&&(t.preventDefault(),Et(e,hSe,t))}(function(n){return n.ctrlKey||n.shiftKey||n.altKey||n.metaKey})(t)&&Et(e,wlt,t)}}],["pointerdown",function(t,e){let n=t.target,r=t.pointerType;t1(n)&&r!=="touch"&&r!=="pen"&&t.button===0&&wf(e,()=>{Iat(n)||(vSe=!0)})}],["compositionstart",function(t,e){wf(e,()=>{let n=Gr();if(dn(n)&&!e.isComposing()){let r=n.anchor,o=n.anchor.getNode();el(r.key),(t.timeStamp<g4+gSe||r.type==="element"||!n.isCollapsed()||o.getFormat()!==n.format||Bt(o)&&o.getStyle()!==n.style)&&Et(e,$L,BYt)}})}],["compositionend",function(t,e){tE?f4=!0:BL||!b4&&!g7?wf(e,()=>{s7(e,t.data)}):(q_e=!0,G_e=t.data)}],["input",function(t,e){t.stopPropagation(),wf(e,()=>{if(pu(t.target)&&Iat(t.target))return;let n=Gr(),r=t.data,o=Slt(t);if(r!=null&&dn(n)&&Clt(n,o,r,t.timeStamp,!1)){f4&&(s7(e,r),f4=!1);let i=n.anchor.getNode(),s=Ay(em(e));if(s===null)return;let a=n.isBackward(),l=a?n.anchor.offset:n.focus.offset,c=a?n.focus.offset:n.anchor.offset;h7&&!n.isCollapsed()&&Bt(i)&&s.anchorNode!==null&&i.getTextContent().slice(0,l)+r+i.getTextContent().slice(l+c)===Jlt(s.anchorNode)||Et(e,$L,r);let u=r.length;tE&&u>1&&t.inputType==="insertCompositionText"&&!e.isComposing()&&(n.anchor.offset-=u),b4||BL||g7||!e.isComposing()||(g4=0,el(null))}else nTe(!1,e,r!==null?r:void 0),f4&&(s7(e,r||void 0),f4=!1);(function(){Qa();let i=wi();Vat(i)})()},{event:t}),LL=null}],["click",function(t,e){wf(e,()=>{let n=Gr(),r=Ay(em(e)),o=lE();if(r){if(dn(n)){let i=n.anchor,s=i.getNode();if(i.type==="element"&&i.offset===0&&n.isCollapsed()&&!fd(s)&&md().getChildrenSize()===1&&s.getTopLevelElementOrThrow().isEmpty()&&o!==null&&n.is(o))r.removeAllRanges(),n.dirty=!0;else if(t.detail===3&&!n.isCollapsed()&&s!==n.focus.getNode()){let a=function(l,c){let u=l;for(;u!==md()&&u!=null;){if(c(u))return u;u=u.getParent()}return null}(s,l=>Le(l)&&!l.isInline());Le(a)&&a.select(0)}}else if(t.pointerType==="touch"||t.pointerType==="pen"){let i=r.anchorNode;(pu(i)||ky(i))&&hd(U7(o,r,e,t))}}Et(e,Qat,t)})}],["cut",Jv],["copy",Jv],["dragstart",Jv],["dragover",Jv],["dragend",Jv],["paste",Jv],["focus",Jv],["blur",Jv],["drop",Jv]];h7&&ySe.push(["beforeinput",(t,e)=>function(n,r){let o=n.inputType,i=Slt(n);o==="deleteCompositionText"||tE&&ect(r)||o!=="insertCompositionText"&&wf(r,()=>{let s=Gr();if(o==="deleteContentBackward"){if(s===null){let p=lE();if(!dn(p))return;hd(p.clone())}if(dn(s)){let p=s.anchor.key===s.focus.key;if(a=n.timeStamp,vlt==="MediaLast"&&a<g4+gSe&&r.isComposing()&&p){if(el(null),g4=0,setTimeout(()=>{wf(r,()=>{el(null)})},gSe),dn(s)){let m=s.anchor.getNode();m.markDirty(),Bt(m)||De(142),_lt(s,m)}}else{el(null),n.preventDefault();let m=s.anchor.getNode(),h=m.getTextContent(),g=m.canInsertTextAfter(),y=s.anchor.offset===0&&s.focus.offset===h.length,w=Hst&&p&&!y&&g;if(w&&s.isCollapsed()&&(w=!Ao(Qlt(s.anchor,!0))),!w){Et(r,P4,!0);let v=Gr();Hst&&dn(v)&&v.isCollapsed()&&(QP=v,setTimeout(()=>QP=null))}}return}}var a;if(!dn(s))return;let l=n.data;LL!==null&&nTe(!1,r,LL),s.dirty&&LL===null||!s.isCollapsed()||fd(s.anchor.getNode())||i===null||s.applyDOMRange(i),LL=null;let c=s.anchor,u=s.focus,d=c.getNode(),f=u.getNode();if(o!=="insertText"&&o!=="insertTranspose")switch(n.preventDefault(),o){case"insertFromYank":case"insertFromDrop":case"insertReplacementText":Et(r,$L,n);break;case"insertFromComposition":el(null),Et(r,$L,n);break;case"insertLineBreak":el(null),Et(r,h4,!1);break;case"insertParagraph":el(null),y4&&!BL?(y4=!1,Et(r,h4,!1)):Et(r,pSe,void 0);break;case"insertFromPaste":case"insertFromPasteAsQuotation":Et(r,BSe,n);break;case"deleteByComposition":(function(p,m){return p!==m||Le(p)||Le(m)||!q_(p)||!q_(m)})(d,f)&&Et(r,mSe,n);break;case"deleteByDrag":case"deleteByCut":Et(r,mSe,n);break;case"deleteContent":Et(r,P4,!1);break;case"deleteWordBackward":Et(r,E4,!0);break;case"deleteWordForward":Et(r,E4,!1);break;case"deleteHardLineBackward":case"deleteSoftLineBackward":Et(r,A4,!0);break;case"deleteContentForward":case"deleteHardLineForward":case"deleteSoftLineForward":Et(r,A4,!1);break;case"formatStrikeThrough":Et(r,H_,"strikethrough");break;case"formatBold":Et(r,H_,"bold");break;case"formatItalic":Et(r,H_,"italic");break;case"formatUnderline":Et(r,H_,"underline");break;case"historyUndo":Et(r,zSe,void 0);break;case"historyRedo":Et(r,jSe,void 0)}else{if(l===`
`)n.preventDefault(),Et(r,h4,!1);else if(l===sx)n.preventDefault(),Et(r,pSe,void 0);else if(l==null&&n.dataTransfer){let p=n.dataTransfer.getData("text/plain");n.preventDefault(),s.insertRawText(p)}else l!=null&&Clt(s,i,l,n.timeStamp,!0)?(n.preventDefault(),Et(r,$L,l)):LL=l;xlt=n.timeStamp}})}(t,e)]);var g4=0,vlt=null,xlt=0,LL=null,S7=new WeakMap,wSe=!1,vSe=!1,y4=!1,f4=!1,q_e=!1,G_e="",QP=null,blt=[0,"",0,"root",0];function Clt(t,e,n,r,o){let i=t.anchor,s=t.focus,a=i.getNode(),l=wi(),c=Ay(em(l)),u=c!==null?c.anchorNode:null,d=i.key,f=l.getElementByKey(d),p=n.length;return d!==s.key||!Bt(a)||(!o&&(!h7||xlt<r+50)||a.isDirty()&&p<2||Ylt(n))&&i.offset!==s.offset&&!a.isComposing()||ex(a)||a.isDirty()&&p>1||(o||!h7)&&f!==null&&!a.isComposing()&&u!==sE(f)||c!==null&&e!==null&&(!e.collapsed||e.startContainer!==c.anchorNode||e.startOffset!==c.anchorOffset)||a.getFormat()!==t.format||a.getStyle()!==t.style||function(m,h){if(h.isSegmented())return!0;if(!m.isCollapsed())return!1;let g=m.anchor.offset,y=h.getParentOrThrow(),w=q_(h);return g===0?!h.canInsertTextBefore()||!y.canInsertTextBefore()&&!h.isComposing()||w||function(v){let x=v.getPreviousSibling();return(Bt(x)||Le(x)&&x.isInline())&&!x.canInsertTextAfter()}(h):g===h.getTextContentSize()&&(!h.canInsertTextAfter()||!y.canInsertTextAfter()&&!h.isComposing()||w)}(t,a)}function rat(t,e){return ky(t)&&t.nodeValue!==null&&e!==0&&e!==t.nodeValue.length}function oat(t,e,n){let{anchorNode:r,anchorOffset:o,focusNode:i,focusOffset:s}=t;wSe&&(wSe=!1,rat(r,o)&&rat(i,s)&&!QP)||wf(e,()=>{if(!n)return void hd(null);if(!N4(e,r,i))return;let a=Gr();if(QP&&dn(a)&&a.isCollapsed()){let l=a.anchor,c=QP.anchor;(l.key===c.key&&l.offset===c.offset+1||l.offset===1&&c.getNode().is(l.getNode().getPreviousSibling()))&&(a=QP.clone(),hd(a))}if(QP=null,dn(a)){let l=a.anchor,c=l.getNode();if(a.isCollapsed()){t.type==="Range"&&t.anchorNode===t.focusNode&&(a.dirty=!0);let u=em(e).event,d=u?u.timeStamp:performance.now(),[f,p,m,h,g]=blt,y=md(),w=e.isComposing()===!1&&y.getTextContent()==="";if(d<g+200&&l.offset===m&&l.key===h)f7(a,f,p);else if(l.type==="text")Bt(c)||De(141),_lt(a,c);else if(l.type==="element"&&!w){Le(c)||De(259);let v=l.getNode();v.isEmpty()?function(x,b){let _=b.getTextFormat(),T=b.getTextStyle();f7(x,_,T)}(a,v):f7(a,0,"")}}else{let u=l.key,d=a.focus.key,f=a.getNodes(),p=f.length,m=a.isBackward(),h=m?s:o,g=m?o:s,y=m?d:u,w=m?u:d,v=Fat,x=!1;for(let b=0;b<p;b++){let _=f[b],T=_.getTextContentSize();if(Bt(_)&&T!==0&&!(b===0&&_.__key===y&&h===T||b===p-1&&_.__key===w&&g===0)&&(x=!0,v&=_.getFormat(),v===0))break}a.format=x?v:0}}Et(e,USe,void 0)})}function f7(t,e,n){t.format===e&&t.style===n||(t.format=e,t.style=n,t.dirty=!0)}function _lt(t,e){f7(t,e.getFormat(),e.getStyle())}function Slt(t){if(!t.getTargetRanges)return null;let e=t.getTargetRanges();return e.length===0?null:e[0]}function s7(t,e){let n=t._compositionKey;if(el(null),n!==null&&e!=null){if(e===""){let r=wa(n),o=sE(t.getElementByKey(n));return void(o!==null&&o.nodeValue!==null&&Bt(r)&&rTe(r,o.nodeValue,null,null,!0))}if(e[e.length-1]===`
`){let r=Gr();if(dn(r)){let o=r.focus;return r.anchor.set(o.key,o.offset,o.type),void Et(t,_7,null)}}}nTe(!0,t,e)}function Tlt(t){let e=t.__lexicalEventHandles;return e===void 0&&(e=[],t.__lexicalEventHandles=e),e}var FL=new Map;function Ilt(t){let e=ict(t.target);if(e===null)return;let n=eTe(e.anchorNode);if(n===null)return;vSe&&(vSe=!1,wf(n,()=>{let l=lE(),c=e.anchorNode;(pu(c)||ky(c))&&hd(U7(l,e,n,t))}));let r=tTe(n),o=r[r.length-1],i=o._key,s=FL.get(i),a=s||o;a!==n&&oat(e,a,!1),oat(e,n,!0),n!==o?FL.set(i,n):s&&FL.delete(i)}function iat(t){t._lexicalHandled=!0}function sat(t){return t._lexicalHandled===!0}var hZt=()=>{};function gZt(t){let e=t.ownerDocument,n=S7.get(e);if(n===void 0)return void hZt();let r=n-1;r>=0||De(164),S7.set(e,r),r===0&&e.removeEventListener("selectionchange",Ilt);let o=O4(t);z7(o)?(function(s){if(s._parentEditor!==null){let a=tTe(s),l=a[a.length-1]._key;FL.get(l)===s&&FL.delete(l)}else FL.delete(s._key)}(o),t.__lexicalEditor=null):o&&De(198);let i=Tlt(t);for(let s=0;s<i.length;s++)i[s]();t.__lexicalEventHandles=[]}function xSe(t,e,n){Qa();let r=t.__key,o=t.getParent();if(o===null)return;let i=function(a){let l=Gr();if(!dn(l)||!Le(a))return l;let{anchor:c,focus:u}=l,d=c.getNode(),f=u.getNode();return N7(d,a)&&c.set(a.__key,0,"element"),N7(f,a)&&u.set(a.__key,0,"element"),l}(t),s=!1;if(dn(i)&&e){let a=i.anchor,l=i.focus;a.key===r&&(P7(a,t,o,t.getPreviousSibling(),t.getNextSibling()),s=!0),l.key===r&&(P7(l,t,o,t.getPreviousSibling(),t.getNextSibling()),s=!0)}else F7(i)&&e&&t.isSelected()&&t.selectPrevious();if(dn(i)&&e&&!s){let a=t.getIndexWithinParent();G_(t),I7(i,o,a,-1)}else G_(t);n||Ah(o)||o.canBeEmpty()||!o.isEmpty()||xSe(o,e),e&&i&&fd(o)&&o.isEmpty()&&o.selectEnd()}function yZt(t){return t}var Z_=class{static getType(){let{ownNodeType:e}=cTe(this);return e===void 0&&De(64,this.name),e}static clone(e){De(65,this.name)}$config(){return{}}config(e,n){let r=n.extends||Object.getPrototypeOf(this.constructor);return Object.assign(n,{extends:r,type:e}),{[e]:n}}afterCloneFrom(e){this.__key===e.__key?(this.__parent=e.__parent,this.__next=e.__next,this.__prev=e.__prev,this.__state=e.__state):e.__state&&(this.__state=e.__state.getWritable(this))}constructor(e){this.__type=this.constructor.getType(),this.__parent=null,this.__prev=null,this.__next=null,Object.defineProperty(this,"__state",{configurable:!0,enumerable:!1,value:void 0,writable:!0}),Hlt(this,e)}getType(){return this.__type}isInline(){De(137,this.constructor.name)}isAttached(){let e=this.__key;for(;e!==null;){if(e==="root")return!0;let n=wa(e);if(n===null)break;e=n.__parent}return!1}isSelected(e){let n=e||Gr();if(n==null)return!1;let r=n.getNodes().some(o=>o.__key===this.__key);if(Bt(this))return r;if(dn(n)&&n.anchor.type==="element"&&n.focus.type==="element"){if(n.isCollapsed())return!1;let o=this.getParent();if(Ao(this)&&this.isInline()&&o){let i=n.isBackward()?n.focus:n.anchor;if(o.is(i.getNode())&&i.offset===o.getChildrenSize()&&this.is(o.getLastChild()))return!1}}return r}getKey(){return this.__key}getIndexWithinParent(){let e=this.getParent();if(e===null)return-1;let n=e.getFirstChild(),r=0;for(;n!==null;){if(this.is(n))return r;r++,n=n.getNextSibling()}return-1}getParent(){let e=this.getLatest().__parent;return e===null?null:wa(e)}getParentOrThrow(){let e=this.getParent();return e===null&&De(66,this.__key),e}getTopLevelElement(){let e=this;for(;e!==null;){let n=e.getParent();if(Ah(n))return Le(e)||e===this&&Ao(e)||De(194),e;e=n}return null}getTopLevelElementOrThrow(){let e=this.getTopLevelElement();return e===null&&De(67,this.__key),e}getParents(){let e=[],n=this.getParent();for(;n!==null;)e.push(n),n=n.getParent();return e}getParentKeys(){let e=[],n=this.getParent();for(;n!==null;)e.push(n.__key),n=n.getParent();return e}getPreviousSibling(){let e=this.getLatest().__prev;return e===null?null:wa(e)}getPreviousSiblings(){let e=[],n=this.getParent();if(n===null)return e;let r=n.getFirstChild();for(;r!==null&&!r.is(this);)e.push(r),r=r.getNextSibling();return e}getNextSibling(){let e=this.getLatest().__next;return e===null?null:wa(e)}getNextSiblings(){let e=[],n=this.getNextSibling();for(;n!==null;)e.push(n),n=n.getNextSibling();return e}getCommonAncestor(e){let n=Le(this)?this:this.getParent(),r=Le(e)?e:e.getParent(),o=n&&r?v4(n,r):null;return o?o.commonAncestor:null}is(e){return e!=null&&this.__key===e.__key}isBefore(e){let n=v4(this,e);return n!==null&&(n.type==="descendant"||(n.type==="branch"?mTe(n)===-1:(n.type!=="same"&&n.type!=="ancestor"&&De(279),!1)))}isParentOf(e){let n=v4(this,e);return n!==null&&n.type==="ancestor"}getNodesBetween(e){let n=this.isBefore(e),r=[],o=new Set,i=this;for(;i!==null;){let s=i.__key;if(o.has(s)||(o.add(s),r.push(i)),i===e)break;let a=Le(i)?n?i.getFirstChild():i.getLastChild():null;if(a!==null){i=a;continue}let l=n?i.getNextSibling():i.getPreviousSibling();if(l!==null){i=l;continue}let c=i.getParentOrThrow();if(o.has(c.__key)||r.push(c),c===e)break;let u=null,d=c;do{if(d===null&&De(68),u=n?d.getNextSibling():d.getPreviousSibling(),d=d.getParent(),d===null)break;u!==null||o.has(d.__key)||r.push(d)}while(u===null);i=u}return n||r.reverse(),r}isDirty(){let e=wi()._dirtyLeaves;return e!==null&&e.has(this.__key)}getLatest(){let e=wa(this.__key);return e===null&&De(113),e}getWritable(){Qa();let e=lx(),n=wi(),r=e._nodeMap,o=this.__key,i=this.getLatest(),s=n._cloneNotNeeded,a=Gr();if(a!==null&&a.setCachedNodes(null),s.has(o))return M7(i),i;let l=lct(i);return s.add(o),M7(l),r.set(o,l),l}getTextContent(){return""}getTextContentSize(){return this.getTextContent().length}createDOM(e,n){De(70)}updateDOM(e,n,r){De(71)}exportDOM(e){return{element:this.createDOM(e._config,e)}}exportJSON(){let e=this.__state?this.__state.toJSON():void 0;return{type:this.__type,version:1,...e}}static importJSON(e){De(18,this.name)}updateFromJSON(e){return function(n,r){let o=n.getWritable(),i=r.$,s=i;for(let a of Kat(o).flatKeys)a in r&&(s!==void 0&&s!==i||(s={...i}),s[a]=r[a]);return(o.__state||s)&&FSe(n).updateFromJSON(s),o}(this,e)}static transform(){return null}remove(e){xSe(this,!0,e)}replace(e,n){Qa();let r=Gr();r!==null&&(r=r.clone()),eSe(this,e);let o=this.getLatest(),i=this.__key,s=e.__key,a=e.getWritable(),l=this.getParentOrThrow().getWritable(),c=l.__size;G_(a);let u=o.getPreviousSibling(),d=o.getNextSibling(),f=o.__prev,p=o.__next,m=o.__parent;if(xSe(o,!1,!0),u===null?l.__first=s:u.getWritable().__next=s,a.__prev=f,d===null?l.__last=s:d.getWritable().__prev=s,a.__next=p,a.__parent=m,l.__size=c,n&&(Le(this)&&Le(a)||De(139),this.getChildren().forEach(h=>{a.append(h)})),dn(r)){hd(r);let h=r.anchor,g=r.focus;h.key===i&&uat(h,a),g.key===i&&uat(g,a)}return K_()===i&&el(s),a}insertAfter(e,n=!0){Qa(),eSe(this,e);let r=this.getWritable(),o=e.getWritable(),i=o.getParent(),s=Gr(),a=!1,l=!1;if(i!==null){let p=e.getIndexWithinParent();if(G_(o),dn(s)){let m=i.__key,h=s.anchor,g=s.focus;a=h.type==="element"&&h.key===m&&h.offset===p+1,l=g.type==="element"&&g.key===m&&g.offset===p+1}}let c=this.getNextSibling(),u=this.getParentOrThrow().getWritable(),d=o.__key,f=r.__next;if(c===null?u.__last=d:c.getWritable().__prev=d,u.__size++,r.__next=d,o.__next=f,o.__prev=r.__key,o.__parent=r.__parent,n&&dn(s)){let p=this.getIndexWithinParent();I7(s,u,p+1);let m=u.__key;a&&s.anchor.set(m,p+2,"element"),l&&s.focus.set(m,p+2,"element")}return e}insertBefore(e,n=!0){Qa(),eSe(this,e);let r=this.getWritable(),o=e.getWritable(),i=o.__key;G_(o);let s=this.getPreviousSibling(),a=this.getParentOrThrow().getWritable(),l=r.__prev,c=this.getIndexWithinParent();s===null?a.__first=i:s.getWritable().__next=i,a.__size++,r.__prev=i,o.__prev=l,o.__next=r.__key,o.__parent=r.__parent;let u=Gr();return n&&dn(u)&&I7(u,this.getParentOrThrow(),c),e}isParentRequired(){return!1}createParentElementNode(){return ox()}selectStart(){return this.selectPrevious()}selectEnd(){return this.selectNext(0,0)}selectPrevious(e,n){Qa();let r=this.getPreviousSibling(),o=this.getParentOrThrow();if(r===null)return o.select(0,0);if(Le(r))return r.select();if(!Bt(r)){let i=r.getIndexWithinParent()+1;return o.select(i,i)}return r.select(e,n)}selectNext(e,n){Qa();let r=this.getNextSibling(),o=this.getParentOrThrow();if(r===null)return o.select();if(Le(r))return r.select(0,0);if(!Bt(r)){let i=r.getIndexWithinParent();return o.select(i,i)}return r.select(e,n)}markDirty(){this.getWritable()}reconcileObservedMutation(e,n){this.markDirty()}},jL=class t extends Z_{static getType(){return"linebreak"}static clone(e){return new t(e.__key)}constructor(e){super(e)}getTextContent(){return`
`}createDOM(){return document.createElement("br")}updateDOM(){return!1}isInline(){return!0}static importDOM(){return{br:e=>function(n){let r=n.parentElement;if(r!==null&&ISe(r)){let o=r.firstChild;if(o===n||o.nextSibling===n&&a7(o)){let i=r.lastChild;if(i===n||i.previousSibling===n&&a7(i))return!0}}return!1}(e)||function(n){let r=n.parentElement;if(r!==null&&ISe(r)){let o=r.firstChild;if(o===n||o.nextSibling===n&&a7(o))return!1;let i=r.lastChild;if(i===n||i.previousSibling===n&&a7(i))return!0}return!1}(e)?null:{conversion:wZt,priority:0}}}static importJSON(e){return VL().updateFromJSON(e)}};function wZt(t){return{node:VL()}}function VL(){return L4(new jL)}function eE(t){return t instanceof jL}function a7(t){return ky(t)&&/^( |\t|\r?\n)+$/.test(t.textContent||"")}function Y_e(t,e){return 16&e?"code":e&R7?"mark":32&e?"sub":64&e?"sup":null}function Z_e(t,e){return 1&e?"strong":2&e?"em":"span"}function Plt(t,e,n,r,o){let i=r.classList,s=UL(o,"base");s!==void 0&&i.add(...s),s=UL(o,"underlineStrikethrough");let a=!1,l=e&_4&&e&C4;s!==void 0&&(n&_4&&n&C4?(a=!0,l||i.add(...s)):l&&i.remove(...s));for(let c in vc){let u=vc[c];if(s=UL(o,c),s!==void 0)if(n&u){if(a&&(c==="underline"||c==="strikethrough")){e&u&&i.remove(...s);continue}e&u&&(!l||c!=="underline")&&c!=="strikethrough"||i.add(...s)}else e&u&&i.remove(...s)}}function Elt(t,e,n){let r=e.firstChild,o=n.isComposing(),i=t+(o?L7:"");if(r==null)e.textContent=i;else{let s=r.nodeValue;if(s!==i)if(o||tE){let[a,l,c]=function(u,d){let f=u.length,p=d.length,m=0,h=0;for(;m<f&&m<p&&u[m]===d[m];)m++;for(;h+m<f&&h+m<p&&u[f-h-1]===d[p-h-1];)h++;return[m,f-m-h,d.slice(m,p-h)]}(s,i);l!==0&&r.deleteData(a,l),r.insertData(a,c)}else r.nodeValue=i}}function aat(t,e,n,r,o,i){Elt(o,t,e);let s=i.theme.text;s!==void 0&&Plt(0,0,r,t,s)}function l7(t,e){let n=document.createElement(e);return n.appendChild(t),n}var oE=class t extends Z_{static getType(){return"text"}static clone(e){return new t(e.__text,e.__key)}afterCloneFrom(e){super.afterCloneFrom(e),this.__text=e.__text,this.__format=e.__format,this.__style=e.__style,this.__mode=e.__mode,this.__detail=e.__detail}constructor(e="",n){super(n),this.__text=e,this.__format=0,this.__style="",this.__mode=0,this.__detail=0}getFormat(){return this.getLatest().__format}getDetail(){return this.getLatest().__detail}getMode(){let e=this.getLatest();return KYt[e.__mode]}getStyle(){return this.getLatest().__style}isToken(){return this.getLatest().__mode===1}isComposing(){return this.__key===K_()}isSegmented(){return this.getLatest().__mode===2}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(e){let n=vc[e];return!!(this.getFormat()&n)}isSimpleText(){return this.__type==="text"&&this.__mode===0}getTextContent(){return this.getLatest().__text}getFormatFlags(e,n){return k7(this.getLatest().__format,e,n)}canHaveFormat(){return!0}isInline(){return!0}createDOM(e,n){let r=this.__format,o=Y_e(0,r),i=Z_e(0,r),s=o===null?i:o,a=document.createElement(s),l=a;this.hasFormat("code")&&a.setAttribute("spellcheck","false"),o!==null&&(l=document.createElement(i),a.appendChild(l)),aat(l,this,0,r,this.__text,e);let c=this.__style;return c!==""&&(a.style.cssText=c),a}updateDOM(e,n,r){let o=this.__text,i=e.__format,s=this.__format,a=Y_e(0,i),l=Y_e(0,s),c=Z_e(0,i),u=Z_e(0,s);if((a===null?c:a)!==(l===null?u:l))return!0;if(a===l&&c!==u){let h=n.firstChild;h==null&&De(48);let g=document.createElement(u);return aat(g,this,0,s,o,r),n.replaceChild(g,h),!1}let d=n;l!==null&&a!==null&&(d=n.firstChild,d==null&&De(49)),Elt(o,d,this);let f=r.theme.text;f!==void 0&&i!==s&&Plt(0,i,s,d,f);let p=e.__style,m=this.__style;return p!==m&&(n.style.cssText=m),!1}static importDOM(){return{"#text":()=>({conversion:CZt,priority:0}),b:()=>({conversion:xZt,priority:0}),code:()=>({conversion:Xv,priority:0}),em:()=>({conversion:Xv,priority:0}),i:()=>({conversion:Xv,priority:0}),mark:()=>({conversion:Xv,priority:0}),s:()=>({conversion:Xv,priority:0}),span:()=>({conversion:vZt,priority:0}),strong:()=>({conversion:Xv,priority:0}),sub:()=>({conversion:Xv,priority:0}),sup:()=>({conversion:Xv,priority:0}),u:()=>({conversion:Xv,priority:0})}}static importJSON(e){return Xa().updateFromJSON(e)}updateFromJSON(e){return super.updateFromJSON(e).setTextContent(e.text).setFormat(e.format).setDetail(e.detail).setMode(e.mode).setStyle(e.style)}exportDOM(e){let{element:n}=super.exportDOM(e);return pu(n)||De(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=l7(n,"b")),this.hasFormat("italic")&&(n=l7(n,"i")),this.hasFormat("strikethrough")&&(n=l7(n,"s")),this.hasFormat("underline")&&(n=l7(n,"u")),{element:n}}exportJSON(){return{detail:this.getDetail(),format:this.getFormat(),mode:this.getMode(),style:this.getStyle(),text:this.getTextContent(),...super.exportJSON()}}selectionTransform(e,n){}setFormat(e){let n=this.getWritable();return n.__format=typeof e=="string"?vc[e]:e,n}setDetail(e){let n=this.getWritable();return n.__detail=typeof e=="string"?VYt[e]:e,n}setStyle(e){let n=this.getWritable();return n.__style=e,n}toggleFormat(e){let n=k7(this.getFormat(),e,null);return this.setFormat(n)}toggleDirectionless(){let e=this.getWritable();return e.__detail^=1,e}toggleUnmergeable(){let e=this.getWritable();return e.__detail^=2,e}setMode(e){let n=HYt[e];if(this.__mode===n)return this;let r=this.getWritable();return r.__mode=n,r}setTextContent(e){if(this.__text===e)return this;let n=this.getWritable();return n.__text=e,n}select(e,n){Qa();let r=e,o=n,i=Gr(),s=this.getTextContent(),a=this.__key;if(typeof s=="string"){let l=s.length;r===void 0&&(r=l),o===void 0&&(o=l)}else r=0,o=0;if(!dn(i))return Mlt(a,r,a,o,"text","text");{let l=K_();l!==i.anchor.key&&l!==i.focus.key||el(a),i.setTextNodeRange(this,r,this,o)}return i}selectStart(){return this.select(0,0)}selectEnd(){let e=this.getTextContentSize();return this.select(e,e)}spliceText(e,n,r,o){let i=this.getWritable(),s=i.__text,a=r.length,l=e;l<0&&(l=a+l,l<0&&(l=0));let c=Gr();if(o&&dn(c)){let d=e+a;c.setTextNodeRange(i,d,i,d)}let u=s.slice(0,l)+r+s.slice(l+n);return i.__text=u,i}canInsertTextBefore(){return!0}canInsertTextAfter(){return!0}splitText(...e){Qa();let n=this.getLatest(),r=n.getTextContent();if(r==="")return[];let o=n.__key,i=K_(),s=r.length;e.sort((S,P)=>S-P),e.push(s);let a=[],l=e.length;for(let S=0,P=0;S<s&&P<=l;P++){let A=e[P];A>S&&(a.push(r.slice(S,A)),S=A)}let c=a.length;if(c===1)return[n];let u=a[0],d=n.getParent(),f,p=n.getFormat(),m=n.getStyle(),h=n.__detail,g=!1,y=null,w=null,v=Gr();if(dn(v)){let[S,P]=v.isBackward()?[v.focus,v.anchor]:[v.anchor,v.focus];S.type==="text"&&S.key===o&&(y=S),P.type==="text"&&P.key===o&&(w=P)}n.isSegmented()?(f=Xa(u),f.__format=p,f.__style=m,f.__detail=h,f.__state=Jst(n,f),g=!0):f=n.setTextContent(u);let x=[f];for(let S=1;S<c;S++){let P=Xa(a[S]);P.__format=p,P.__style=m,P.__detail=h,P.__state=Jst(n,P);let A=P.__key;i===o&&el(A),x.push(P)}let b=y?y.offset:null,_=w?w.offset:null,T=0;for(let S of x){if(!y&&!w)break;let P=T+S.getTextContentSize();if(y!==null&&b!==null&&b<=P&&b>=T&&(y.set(S.getKey(),b-T,"text"),b<P&&(y=null)),w!==null&&_!==null&&_<=P&&_>=T){w.set(S.getKey(),_-T,"text");break}T=P}if(d!==null){(function(A){let O=A.getPreviousSibling(),D=A.getNextSibling();O!==null&&M7(O),D!==null&&M7(D)})(this);let S=d.getWritable(),P=this.getIndexWithinParent();g?(S.splice(P,0,x),this.remove()):S.splice(P,1,x),dn(v)&&I7(v,d,P,c-1)}return x}mergeWithSibling(e){let n=e===this.getPreviousSibling();n||e===this.getNextSibling()||De(50);let r=this.__key,o=e.__key,i=this.__text,s=i.length;K_()===o&&el(r);let a=Gr();if(dn(a)){let d=a.anchor,f=a.focus;d!==null&&d.key===o&&yat(d,n,r,e,s),f!==null&&f.key===o&&yat(f,n,r,e,s)}let l=e.__text,c=n?l+i:i+l;this.setTextContent(c);let u=this.getWritable();return e.remove(),u}isTextEntity(){return!1}};function vZt(t){return{forChild:HSe(t.style),node:null}}function xZt(t){let e=t,n=e.style.fontWeight==="normal";return{forChild:HSe(e.style,n?void 0:"bold"),node:null}}var lat=new WeakMap;function bZt(t){if(!pu(t))return!1;if(t.nodeName==="PRE")return!0;let e=t.style.whiteSpace;return typeof e=="string"&&e.startsWith("pre")}function CZt(t){let e=t;t.parentElement===null&&De(129);let n=e.textContent||"";if(function(r){let o,i=r.parentNode,s=[r];for(;i!==null&&(o=lat.get(i))===void 0&&!bZt(i);)s.push(i),i=i.parentNode;let a=o===void 0?i:o;for(let l=0;l<s.length;l++)lat.set(s[l],a);return a}(e)!==null){let r=n.split(/(\r?\n|\t)/),o=[],i=r.length;for(let s=0;s<i;s++){let a=r[s];a===`
`||a===`\r
`?o.push(VL()):a==="	"?o.push($7()):a!==""&&o.push(Xa(a))}return{node:o}}if(n=n.replace(/\r/g,"").replace(/[ \t\n]+/g," "),n==="")return{node:null};if(n[0]===" "){let r=e,o=!0;for(;r!==null&&(r=cat(r,!1))!==null;){let i=r.textContent||"";if(i.length>0){/[ \t\n]$/.test(i)&&(n=n.slice(1)),o=!1;break}}o&&(n=n.slice(1))}if(n[n.length-1]===" "){let r=e,o=!0;for(;r!==null&&(r=cat(r,!0))!==null;)if((r.textContent||"").replace(/^( |\t|\r?\n)+/,"").length>0){o=!1;break}o&&(n=n.slice(0,n.length-1))}return n===""?{node:null}:{node:Xa(n)}}function cat(t,e){let n=t;for(;;){let r;for(;(r=e?n.nextSibling:n.previousSibling)===null;){let i=n.parentElement;if(i===null)return null;n=i}if(n=r,pu(n)){let i=n.style.display;if(i===""&&!act(n)||i!==""&&!i.startsWith("inline"))return null}let o=n;for(;(o=e?n.firstChild:n.lastChild)!==null;)n=o;if(ky(n))return n;if(n.nodeName==="BR")return null}}var _Zt={code:"code",em:"italic",i:"italic",mark:"highlight",s:"strikethrough",strong:"bold",sub:"subscript",sup:"superscript",u:"underline"};function Xv(t){let e=_Zt[t.nodeName.toLowerCase()];return e===void 0?{node:null}:{forChild:HSe(t.style,e),node:null}}function Xa(t=""){return L4(new oE(t))}function Bt(t){return t instanceof oE}function HSe(t,e){let n=t.fontWeight,r=t.textDecoration.split(" "),o=n==="700"||n==="bold",i=r.includes("line-through"),s=t.fontStyle==="italic",a=r.includes("underline"),l=t.verticalAlign;return c=>(Bt(c)&&(o&&!c.hasFormat("bold")&&c.toggleFormat("bold"),i&&!c.hasFormat("strikethrough")&&c.toggleFormat("strikethrough"),s&&!c.hasFormat("italic")&&c.toggleFormat("italic"),a&&!c.hasFormat("underline")&&c.toggleFormat("underline"),l!=="sub"||c.hasFormat("subscript")||c.toggleFormat("subscript"),l!=="super"||c.hasFormat("superscript")||c.toggleFormat("superscript"),e&&!c.hasFormat(e)&&c.toggleFormat(e)),c)}var WL=class t extends oE{static getType(){return"tab"}static clone(e){return new t(e.__key)}constructor(e){super("	",e),this.__detail=2}static importDOM(){return null}createDOM(e){let n=super.createDOM(e),r=UL(e.theme,"tab");return r!==void 0&&n.classList.add(...r),n}static importJSON(e){return $7().updateFromJSON(e)}setTextContent(e){return e!=="	"&&e!==""&&De(126),super.setTextContent("	")}spliceText(e,n,r,o){return r===""&&n===0||r==="	"&&n===1||De(286),this}setDetail(e){return e!==2&&De(127),this}setMode(e){return e!=="normal"&&De(128),this}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}};function $7(){return L4(new WL)}function KSe(t){return t instanceof WL}var bSe=class{constructor(e,n,r){this._selection=null,this.key=e,this.offset=n,this.type=r}is(e){return this.key===e.key&&this.offset===e.offset&&this.type===e.type}isBefore(e){return this.key===e.key?this.offset<e.offset:pTe(Sh(eS(this,"next")),Sh(eS(e,"next")))<0}getNode(){let e=wa(this.key);return e===null&&De(20),e}set(e,n,r,o){let i=this._selection,s=this.key;o&&this.key===e&&this.offset===n&&this.type===r||(this.key=e,this.offset=n,this.type=r,e1()||(K_()===s&&el(e),i!==null&&(i.setCachedNodes(null),i.dirty=!0)))}};function Eh(t,e,n){return new bSe(t,e,n)}function J_e(t,e){let n=e.__key,r=t.offset,o="element";if(Bt(e)){o="text";let i=e.getTextContentSize();r>i&&(r=i)}else if(!Le(e)){let i=e.getNextSibling();if(Bt(i))n=i.__key,r=0,o="text";else{let s=e.getParent();s&&(n=s.__key,r=e.getIndexWithinParent()+1)}}t.set(n,r,o)}function uat(t,e){if(Le(e)){let n=e.getLastDescendant();Le(n)||Bt(n)?J_e(t,n):J_e(t,e)}else J_e(t,e)}var T7=class t{constructor(e){this._cachedNodes=null,this._nodes=e,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){if(!F7(e))return!1;let n=this._nodes,r=e._nodes;return n.size===r.size&&Array.from(n).every(o=>r.has(o))}isCollapsed(){return!1}isBackward(){return!1}getStartEndPoints(){return null}add(e){this.dirty=!0,this._nodes.add(e),this._cachedNodes=null}delete(e){this.dirty=!0,this._nodes.delete(e),this._cachedNodes=null}clear(){this.dirty=!0,this._nodes.clear(),this._cachedNodes=null}has(e){return this._nodes.has(e)}clone(){return new t(new Set(this._nodes))}extract(){return this.getNodes()}insertRawText(e){}insertText(){}insertNodes(e){let n=this.getNodes(),r=n.length,o=n[r-1],i;if(Bt(o))i=o.select();else{let s=o.getIndexWithinParent()+1;i=o.getParentOrThrow().select(s,s)}i.insertNodes(e);for(let s=0;s<r;s++)n[s].remove()}getNodes(){let e=this._cachedNodes;if(e!==null)return e;let n=this._nodes,r=[];for(let o of n){let i=wa(o);i!==null&&r.push(i)}return e1()||(this._cachedNodes=r),r}getTextContent(){let e=this.getNodes(),n="";for(let r=0;r<e.length;r++)n+=e[r].getTextContent();return n}deleteNodes(){let e=this.getNodes();if((Gr()||lE())===this&&e[0]){let n=rl(e[0],"next");pct(Q_(n,n))}for(let n of e)n.remove()}};function dn(t){return t instanceof iE}var iE=class t{constructor(e,n,r,o){this.anchor=e,this.focus=n,e._selection=this,n._selection=this,this._cachedNodes=null,this.format=r,this.style=o,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(e){this._cachedNodes=e}is(e){return!!dn(e)&&this.anchor.is(e.anchor)&&this.focus.is(e.focus)&&this.format===e.format&&this.style===e.style}isCollapsed(){return this.anchor.is(this.focus)}getNodes(){let e=this._cachedNodes;if(e!==null)return e;let n=function(r){let o=[],[i,s]=r.getTextSlices();i&&o.push(i.caret.origin);let a=new Set,l=new Set;for(let c of r)if(Ih(c)){let{origin:u}=c;o.length===0?a.add(u):(l.add(u),o.push(u))}else{let{origin:u}=c;Le(u)&&l.has(u)||o.push(u)}if(s&&o.push(s.caret.origin),aE(r.focus)&&Le(r.focus.origin)&&r.focus.getNodeAtCaret()===null)for(let c=ax(r.focus.origin,"previous");Ih(c)&&a.has(c.origin)&&!c.origin.isEmpty()&&c.origin.is(o[o.length-1]);c=XL(c))a.delete(c.origin),o.pop();for(;o.length>1;){let c=o[o.length-1];if(!Le(c)||l.has(c)||c.isEmpty()||a.has(c))break;o.pop()}if(o.length===0&&r.isCollapsed()){let c=Sh(r.anchor),u=Sh(r.anchor.getFlipped()),d=p=>ix(p)?p.origin:p.getNodeAtCaret(),f=d(c)||d(u)||(r.anchor.getNodeAtCaret()?c.origin:u.origin);o.push(f)}return o}(hTe(kSe(this),"next"));return e1()||(this._cachedNodes=n),n}setTextNodeRange(e,n,r,o){this.anchor.set(e.__key,n,"text"),this.focus.set(r.__key,o,"text")}getTextContent(){let e=this.getNodes();if(e.length===0)return"";let n=e[0],r=e[e.length-1],o=this.anchor,i=this.focus,s=o.isBefore(i),[a,l]=CSe(this),c="",u=!0;for(let d=0;d<e.length;d++){let f=e[d];if(Le(f)&&!f.isInline())u||(c+=`
`),u=!f.isEmpty();else if(u=!1,Bt(f)){let p=f.getTextContent();f===n?f===r?o.type==="element"&&i.type==="element"&&i.offset!==o.offset||(p=a<l?p.slice(a,l):p.slice(l,a)):p=s?p.slice(a):p.slice(l):f===r&&(p=s?p.slice(0,l):p.slice(0,a)),c+=p}else!Ao(f)&&!eE(f)||f===r&&this.isCollapsed()||(c+=f.getTextContent())}return c}applyDOMRange(e){let n=wi(),r=n.getEditorState()._selection,o=klt(e.startContainer,e.startOffset,e.endContainer,e.endOffset,n,r);if(o===null)return;let[i,s]=o;this.anchor.set(i.key,i.offset,i.type,!0),this.focus.set(s.key,s.offset,s.type,!0),v7(this)}clone(){let e=this.anchor,n=this.focus;return new t(Eh(e.key,e.offset,e.type),Eh(n.key,n.offset,n.type),this.format,this.style)}toggleFormat(e){this.format=k7(this.format,e,null),this.dirty=!0}setFormat(e){this.format=e,this.dirty=!0}setStyle(e){this.style=e,this.dirty=!0}hasFormat(e){let n=vc[e];return!!(this.format&n)}insertRawText(e){let n=e.split(/(\r?\n|\t)/),r=[],o=n.length;for(let i=0;i<o;i++){let s=n[i];s===`
`||s===`\r
`?r.push(VL()):s==="	"?r.push($7()):r.push(Xa(s))}this.insertNodes(r)}insertText(e){let n=this.anchor,r=this.focus,o=this.format,i=this.style,s=n,a=r;!this.isCollapsed()&&r.isBefore(n)&&(s=r,a=n),s.type==="element"&&function(g,y,w,v){let x=g.getNode(),b=x.getChildAtIndex(g.offset),_=Xa(),T=fd(x)?ox().append(_):_;_.setFormat(w),_.setStyle(v),b===null?x.append(T):b.insertBefore(T),g.is(y)&&y.set(_.__key,0,"text"),g.set(_.__key,0,"text")}(s,a,o,i),a.type==="element"&&QL(a,Sh(eS(a,"next")));let l=s.offset,c=a.offset,u=this.getNodes(),d=u.length,f=u[0];Bt(f)||De(26);let p=f.getTextContent().length,m=f.getParentOrThrow(),h=u[d-1];if(d===1&&a.type==="element"&&(c=p,a.set(s.key,c,"text")),this.isCollapsed()&&l===p&&(ex(f)||!f.canInsertTextAfter()||!m.canInsertTextAfter()&&f.getNextSibling()===null)){let g=f.getNextSibling();if(Bt(g)&&g.canInsertTextBefore()&&!ex(g)||(g=Xa(),g.setFormat(o),g.setStyle(i),m.canInsertTextAfter()?f.insertAfter(g):m.insertAfter(g)),g.select(0,0),f=g,e!=="")return void this.insertText(e)}else if(this.isCollapsed()&&l===0&&(ex(f)||!f.canInsertTextBefore()||!m.canInsertTextBefore()&&f.getPreviousSibling()===null)){let g=f.getPreviousSibling();if(Bt(g)&&!ex(g)||(g=Xa(),g.setFormat(o),m.canInsertTextBefore()?f.insertBefore(g):m.insertBefore(g)),g.select(),f=g,e!=="")return void this.insertText(e)}else if(f.isSegmented()&&l!==p){let g=Xa(f.getTextContent());g.setFormat(o),f.replace(g),f=g}else if(!this.isCollapsed()&&e!==""){let g=h.getParent();if(!m.canInsertTextBefore()||!m.canInsertTextAfter()||Le(g)&&(!g.canInsertTextBefore()||!g.canInsertTextAfter()))return this.insertText(""),Alt(this.anchor,this.focus,null),void this.insertText(e)}if(d===1){if(q_(f)){let v=Xa(e);return v.select(),void f.replace(v)}let g=f.getFormat(),y=f.getStyle();if(l!==c||g===o&&y===i){if(KSe(f)){let v=Xa(e);return v.setFormat(o),v.setStyle(i),v.select(),void f.replace(v)}}else{if(f.getTextContent()!==""){let v=Xa(e);if(v.setFormat(o),v.setStyle(i),v.select(),l===0)f.insertBefore(v,!1);else{let[x]=f.splitText(l);x.insertAfter(v,!1)}return void(v.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length))}f.setFormat(o),f.setStyle(i)}let w=c-l;f=f.spliceText(l,w,e,!0),f.getTextContent()===""?f.remove():this.anchor.type==="text"&&(f.isComposing()?this.anchor.offset-=e.length:(this.format=g,this.style=y))}else{let g=new Set([...f.getParentKeys(),...h.getParentKeys()]),y=Le(f)?f:f.getParentOrThrow(),w=Le(h)?h:h.getParentOrThrow(),v=h;if(!y.is(w)&&w.isInline())do v=w,w=w.getParentOrThrow();while(w.isInline());if(a.type==="text"&&(c!==0||h.getTextContent()==="")||a.type==="element"&&h.getIndexWithinParent()<c)if(Bt(h)&&!q_(h)&&c!==h.getTextContentSize()){if(h.isSegmented()){let S=Xa(h.getTextContent());h.replace(S),h=S}fd(a.getNode())||a.type!=="text"||(h=h.spliceText(0,c,"")),g.add(h.__key)}else{let S=h.getParentOrThrow();S.canBeEmpty()||S.getChildrenSize()!==1?h.remove():S.remove()}else g.add(h.__key);let x=w.getChildren(),b=new Set(u),_=y.is(w),T=y.isInline()&&f.getNextSibling()===null?y:f;for(let S=x.length-1;S>=0;S--){let P=x[S];if(P.is(f)||Le(P)&&P.isParentOf(f))break;P.isAttached()&&(!b.has(P)||P.is(v)?_||T.insertAfter(P,!1):P.remove())}if(!_){let S=w,P=null;for(;S!==null;){let A=S.getChildren(),O=A.length;(O===0||A[O-1].is(P))&&(g.delete(S.__key),P=S),S=S.getParent()}}if(q_(f))if(l===p)f.select();else{let S=Xa(e);S.select(),f.replace(S)}else f=f.spliceText(l,p-l,e,!0),f.getTextContent()===""?f.remove():f.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=e.length);for(let S=1;S<d;S++){let P=u[S],A=P.__key;g.has(A)||P.remove()}}}removeText(){let e=Gr()===this;x4(this,mct(kSe(this))),e&&Gr()!==this&&hd(this)}formatText(e,n=null){if(this.isCollapsed())return this.toggleFormat(e),void el(null);let r=this.getNodes(),o=[];for(let x of r)Bt(x)&&o.push(x);let i=x=>{r.forEach(b=>{if(Le(b)){let _=b.getFormatFlags(e,x);b.setTextFormat(_)}})},s=o.length;if(s===0)return this.toggleFormat(e),el(null),void i(n);let a=this.anchor,l=this.focus,c=this.isBackward(),u=c?l:a,d=c?a:l,f=0,p=o[0],m=u.type==="element"?0:u.offset;if(u.type==="text"&&m===p.getTextContentSize()&&(f=1,p=o[1],m=0),p==null)return;let h=p.getFormatFlags(e,n);i(h);let g=s-1,y=o[g],w=d.type==="text"?d.offset:y.getTextContentSize();if(p.is(y)){if(m===w)return;if(ex(p)||m===0&&w===p.getTextContentSize())p.setFormat(h);else{let x=p.splitText(m,w),b=m===0?x[0]:x[1];b.setFormat(h),u.type==="text"&&u.set(b.__key,0,"text"),d.type==="text"&&d.set(b.__key,w-m,"text")}return void(this.format=h)}m===0||ex(p)||([,p]=p.splitText(m),m=0),p.setFormat(h);let v=y.getFormatFlags(e,h);w>0&&(w===y.getTextContentSize()||ex(y)||([y]=y.splitText(w)),y.setFormat(v));for(let x=f+1;x<g;x++){let b=o[x],_=b.getFormatFlags(e,v);b.setFormat(_)}u.type==="text"&&u.set(p.__key,m,"text"),d.type==="text"&&d.set(y.__key,w,"text"),this.format=h|v}insertNodes(e){if(e.length===0)return;if(this.isCollapsed()||this.removeText(),this.anchor.key==="root"){this.insertParagraph();let m=Gr();return dn(m)||De(134),m.insertNodes(e)}let n=(this.isBackward()?this.focus:this.anchor).getNode(),r=nSe(n,rx),o=e[e.length-1];if(Le(r)&&"__language"in r){if("__language"in e[0])this.insertText(e[0].getTextContent());else{let m=X_e(this);r.splice(m,0,e),o.selectEnd()}return}if(!e.some(m=>(Le(m)||Ao(m))&&!m.isInline())){Le(r)||De(211,n.constructor.name,n.getType());let m=X_e(this);return r.splice(m,0,e),void o.selectEnd()}let i=function(m){let h=ox(),g=null;for(let y=0;y<m.length;y++){let w=m[y],v=eE(w);if(v||Ao(w)&&w.isInline()||Le(w)&&w.isInline()||Bt(w)||w.isParentRequired()){if(g===null&&(g=w.createParentElementNode(),h.append(g),v))continue;g!==null&&g.append(w)}else h.append(w),g=null}return h}(e),s=i.getLastDescendant(),a=i.getChildren(),l=!Le(r)||!r.isEmpty()?this.insertParagraph():null,c=a[a.length-1],u=a[0];var d;Le(d=u)&&rx(d)&&!d.isEmpty()&&Le(r)&&(!r.isEmpty()||r.canMergeWhenEmpty())&&(Le(r)||De(211,n.constructor.name,n.getType()),r.append(...u.getChildren()),u=a[1]),u&&(r===null&&De(212,n.constructor.name,n.getType()),function(m,h,g){let y=h.getParentOrThrow().getLastChild(),w=h,v=[h];for(;w!==y;)w.getNextSibling()||De(140),w=w.getNextSibling(),v.push(w);let x=m;for(let b of v)x=x.insertAfter(b)}(r,u));let f=nSe(s,rx);l&&Le(f)&&(l.canMergeWhenEmpty()||rx(c))&&(f.append(...l.getChildren()),l.remove()),Le(r)&&r.isEmpty()&&r.remove(),s.selectEnd();let p=Le(r)?r.getLastChild():null;eE(p)&&f!==r&&p.remove()}insertParagraph(){if(this.anchor.key==="root"){let s=ox();return md().splice(this.anchor.offset,0,[s]),s.select(),s}let e=X_e(this),n=nSe(this.anchor.getNode(),rx);Le(n)||De(213);let r=n.getChildAtIndex(e),o=r?[r,...r.getNextSiblings()]:[],i=n.insertNewAfter(this,!1);return i?(i.append(...o),i.selectStart(),i):null}insertLineBreak(e){let n=VL();if(this.insertNodes([n]),e){let r=n.getParentOrThrow(),o=n.getIndexWithinParent();r.select(o,o)}}extract(){let e=this.getNodes(),n=e.length,r=n-1,o=this.anchor,i=this.focus,s=e[0],a=e[r],[l,c]=CSe(this);if(n===0)return[];if(n===1){if(Bt(s)&&!this.isCollapsed()){let d=l>c?c:l,f=l>c?l:c,p=s.splitText(d,f),m=d===0?p[0]:p[1];return m!=null?[m]:[]}return[s]}let u=o.isBefore(i);if(Bt(s)){let d=u?l:c;d===s.getTextContentSize()?e.shift():d!==0&&([,s]=s.splitText(d),e[0]=s)}if(Bt(a)){let d=a.getTextContent().length,f=u?c:l;f===0?e.pop():f!==d&&([a]=a.splitText(f),e[r]=a)}return e}modify(e,n,r){if(wat(this,e,n,r))return;let o=e==="move",i=wi(),s=Ay(em(i));if(!s)return;let a=i._blockCursorElement,l=i._rootElement,c=this.focus.getNode();if(l===null||a===null||!Le(c)||c.isInline()||c.canBeEmpty()||TSe(a,i,l),this.dirty){let u=GL(i,this.anchor.key),d=GL(i,this.focus.key);this.anchor.type==="text"&&(u=sE(u)),this.focus.type==="text"&&(d=sE(d)),u&&d&&Olt(s,u,this.anchor.offset,d,this.focus.offset)}if(function(u,d,f,p){u.modify(d,f,p)}(s,e,n?"backward":"forward",r),s.rangeCount>0){let u=s.getRangeAt(0),d=this.anchor.getNode(),f=fd(d)?d:rct(d);if(this.applyDOMRange(u),this.dirty=!0,!o){let p=this.getNodes(),m=[],h=!1;for(let g=0;g<p.length;g++){let y=p[g];N7(y,f)?m.push(y):h=!0}if(h&&m.length>0)if(n){let g=m[0];Le(g)?g.selectStart():g.getParentOrThrow().selectStart()}else{let g=m[m.length-1];Le(g)?g.selectEnd():g.getParentOrThrow().selectEnd()}s.anchorNode===u.startContainer&&s.anchorOffset===u.startOffset||function(g){let y=g.focus,w=g.anchor,v=w.key,x=w.offset,b=w.type;w.set(y.key,y.offset,y.type,!0),y.set(v,x,b,!0)}(this)}}r==="lineboundary"&&wat(this,e,n,r,"decorators")}forwardDeletion(e,n,r){if(!r&&(e.type==="element"&&Le(n)&&e.offset===n.getChildrenSize()||e.type==="text"&&e.offset===n.getTextContentSize())){let o=n.getParent(),i=n.getNextSibling()||(o===null?null:o.getNextSibling());if(Le(i)&&i.isShadowRoot())return!0}return!1}deleteCharacter(e){let n=this.isCollapsed();if(this.isCollapsed()){let r=this.anchor,o=r.getNode();if(this.forwardDeletion(r,o,e))return;let i=dTe(eS(r,e?"previous":"next"));if(i.getTextSlices().every(a=>a===null||a.distance===0)){let a={type:"initial"};for(let l of i.iterNodeCarets("shadowRoot"))if(Ih(l)){if(!l.origin.isInline()){if(l.origin.isShadowRoot()){if(a.type==="merge-block")break;if(Le(i.anchor.origin)&&i.anchor.origin.isEmpty()){let c=Sh(l);x4(this,Q_(c,c)),i.anchor.origin.remove()}return}a.type!=="merge-next-block"&&a.type!=="merge-block"||(a={block:a.block,caret:l,type:"merge-block"})}}else{if(a.type==="merge-block")break;if(aE(l)){if(Le(l.origin)){if(l.origin.isInline()){if(!l.origin.isParentOf(i.anchor.origin))break}else a={block:l.origin,type:"merge-next-block"};continue}if(Ao(l.origin)){if(!l.origin.isIsolated())if(a.type==="merge-next-block"&&(l.origin.isKeyboardSelectable()||!l.origin.isInline())&&Le(i.anchor.origin)&&i.anchor.origin.isEmpty()){i.anchor.origin.remove();let c=qSe();c.add(l.origin.getKey()),hd(c)}else l.origin.remove();return}break}}if(a.type==="merge-block"){let{caret:l,block:c}=a;return x4(this,Q_(!l.origin.isEmpty()&&c.isEmpty()?n1(rl(c,l.direction)):i.anchor,l)),this.removeText()}}let s=this.focus;if(this.modify("extend",e,"character"),this.isCollapsed()){if(e&&r.offset===0&&fat(this,r.getNode()))return}else{let a=s.type==="text"?s.getNode():null;if(o=r.type==="text"?r.getNode():null,a!==null&&a.isSegmented()){let l=s.offset,c=a.getTextContentSize();if(a.is(o)||e&&l!==c||!e&&l!==0)return void pat(a,e,l)}else if(o!==null&&o.isSegmented()){let l=r.offset,c=o.getTextContentSize();if(o.is(a)||e&&l!==0||!e&&l!==c)return void pat(o,e,l)}(function(l,c){let u=l.anchor,d=l.focus,f=u.getNode(),p=d.getNode();if(f===p&&u.type==="text"&&d.type==="text"){let m=u.offset,h=d.offset,g=m<h,y=g?m:h,w=g?h:m,v=w-1;y!==v&&function(x){return!(Ylt(x)||SZt(x))}(f.getTextContent().slice(y,w))&&(c?d.set(d.key,v,d.type):u.set(u.key,v,u.type))}})(this,e)}}if(this.removeText(),e&&!n&&this.isCollapsed()&&this.anchor.type==="element"&&this.anchor.offset===0){let r=this.anchor.getNode();r.isEmpty()&&fd(r.getParent())&&r.getPreviousSibling()===null&&fat(this,r)}}deleteLine(e){this.isCollapsed()&&this.modify("extend",e,"lineboundary"),this.isCollapsed()?this.deleteCharacter(e):this.removeText()}deleteWord(e){if(this.isCollapsed()){let n=this.anchor,r=n.getNode();if(this.forwardDeletion(n,r,e))return;this.modify("extend",e,"word")}this.removeText()}isBackward(){return this.focus.isBefore(this.anchor)}getStartEndPoints(){return[this.anchor,this.focus]}};function F7(t){return t instanceof T7}function dat(t){let e=t.offset;if(t.type==="text")return e;let n=t.getNode();return e===n.getChildrenSize()?n.getTextContent().length:0}function CSe(t){let e=t.getStartEndPoints();if(e===null)return[0,0];let[n,r]=e;return n.type==="element"&&r.type==="element"&&n.key===r.key&&n.offset===r.offset?[0,0]:[dat(n),dat(r)]}function fat(t,e){for(let n=e;n;n=n.getParent()){if(Le(n)){if(n.collapseAtStart(t))return!0;if(Ah(n))break}if(n.getPreviousSibling())break}return!1}var SZt=(()=>{try{let t=new RegExp("\\p{Emoji}","u"),e=t.test.bind(t);if(e("\u2764\uFE0F")&&e("#\uFE0F\u20E3")&&e("\u{1F44D}"))return e}catch{}return()=>!1})();function pat(t,e,n){let r=t,o=r.getTextContent().split(/(?=\s)/g),i=o.length,s=0,a=0;for(let c=0;c<i;c++){let u=c===i-1;if(a=s,s+=o[c].length,e&&s===n||s>n||u){o.splice(c,1),u&&(a=void 0);break}}let l=o.join("").trim();l===""?r.remove():(r.setTextContent(l),r.select(a,a))}function mat(t,e,n,r){let o,i=e;if(pu(t)){let s=!1,a=t.childNodes,l=a.length,c=r._blockCursorElement;i===l&&(s=!0,i=l-1);let u=a[i],d=!1;if(u===c)u=a[i+1],d=!0;else if(c!==null){let f=c.parentNode;t===f&&e>Array.prototype.indexOf.call(f.children,c)&&i--}if(o=DL(u),Bt(o))i=Ph(o,s?"next":"previous");else{let f=DL(t);if(f===null)return null;if(Le(f)){let p=r.getElementByKey(f.getKey());p===null&&De(214),[f,i]=f.getDOMSlot(p).resolveChildIndex(f,p,t,e),Le(f)||De(215),s&&i>=f.getChildrenSize()&&(i=Math.max(0,f.getChildrenSize()-1));let h=f.getChildAtIndex(i);if(Le(h)&&function(g,y,w){let v=g.getParent();return w===null||v===null||!v.canBeEmpty()||v!==w.getNode()}(h,0,n)){let g=s?h.getLastDescendant():h.getFirstDescendant();g===null?f=h:(h=g,f=Le(h)?h:h.getParentOrThrow()),i=0}Bt(h)?(o=h,f=null,i=Ph(h,s?"next":"previous")):h!==f&&s&&!d&&(Le(f)||De(216),i=Math.min(f.getChildrenSize(),i+1))}else{let p=f.getIndexWithinParent();i=e===0&&Ao(f)&&DL(t)===f?p:p+1,f=f.getParentOrThrow()}if(Le(f))return Eh(f.__key,i,"element")}}else o=DL(t);return Bt(o)?Eh(o.__key,Ph(o,i,"clamp"),"text"):null}function hat(t,e,n){let r=t.offset,o=t.getNode();if(r===0){let i=o.getPreviousSibling(),s=o.getParent();if(e){if((n||!e)&&i===null&&Le(s)&&s.isInline()){let a=s.getPreviousSibling();Bt(a)&&t.set(a.__key,a.getTextContent().length,"text")}}else Le(i)&&!n&&i.isInline()?t.set(i.__key,i.getChildrenSize(),"element"):Bt(i)&&t.set(i.__key,i.getTextContent().length,"text")}else if(r===o.getTextContent().length){let i=o.getNextSibling(),s=o.getParent();if(e&&Le(i)&&i.isInline())t.set(i.__key,0,"element");else if((n||e)&&i===null&&Le(s)&&s.isInline()&&!s.canInsertTextAfter()){let a=s.getNextSibling();Bt(a)&&t.set(a.__key,0,"text")}}}function Alt(t,e,n){if(t.type==="text"&&e.type==="text"){let r=t.isBefore(e),o=t.is(e);hat(t,r,o),hat(e,!r,o),o&&e.set(t.key,t.offset,t.type);let i=wi();if(i.isComposing()&&i._compositionKey!==t.key&&dn(n)){let s=n.anchor,a=n.focus;t.set(s.key,s.offset,s.type,!0),e.set(a.key,a.offset,a.type,!0)}}}function klt(t,e,n,r,o,i){if(t===null||n===null||!N4(o,t,n))return null;let s=mat(t,e,dn(i)?i.anchor:null,o);if(s===null)return null;let a=mat(n,r,dn(i)?i.focus:null,o);if(a===null)return null;if(s.type==="element"&&a.type==="element"){let l=DL(t),c=DL(n);if(Ao(l)&&Ao(c))return null}return Alt(s,a,i),[s,a]}function TZt(t){return Le(t)&&!t.isInline()}function Mlt(t,e,n,r,o,i){let s=lx(),a=new iE(Eh(t,e,o),Eh(n,r,i),0,"");return a.dirty=!0,s._selection=a,a}function Nlt(){let t=Eh("root",0,"element"),e=Eh("root",0,"element");return new iE(t,e,0,"")}function qSe(){return new T7(new Set)}function IZt(t,e){return U7(null,t,e,null)}function U7(t,e,n,r){let o=n._window;if(o===null)return null;let i=r||o.event,s=i?i.type:void 0,a=s==="selectionchange",l=!oSe&&(a||s==="beforeinput"||s==="compositionstart"||s==="compositionend"||s==="click"&&i&&i.detail===3||s==="drop"||s===void 0),c,u,d,f;if(dn(t)&&!l)return t.clone();if(e===null)return null;if(c=e.anchorNode,u=e.focusNode,d=e.anchorOffset,f=e.focusOffset,a&&dn(t)&&!N4(n,c,u))return t.clone();let p=klt(c,d,u,f,n,t);if(p===null)return null;let[m,h]=p;return new iE(m,h,dn(t)?t.format:0,dn(t)?t.style:"")}function Gr(){return lx()._selection}function lE(){return wi()._editorState._selection}function I7(t,e,n,r=1){let o=t.anchor,i=t.focus,s=o.getNode(),a=i.getNode();if(!e.is(s)&&!e.is(a))return;let l=e.__key;if(t.isCollapsed()){let c=o.offset;if(n<=c&&r>0||n<c&&r<0){let u=Math.max(0,c+r);o.set(l,u,"element"),i.set(l,u,"element"),gat(t)}}else{let c=t.isBackward(),u=c?i:o,d=u.getNode(),f=c?o:i,p=f.getNode();if(e.is(d)){let m=u.offset;(n<=m&&r>0||n<m&&r<0)&&u.set(l,Math.max(0,m+r),"element")}if(e.is(p)){let m=f.offset;(n<=m&&r>0||n<m&&r<0)&&f.set(l,Math.max(0,m+r),"element")}}gat(t)}function gat(t){let e=t.anchor,n=e.offset,r=t.focus,o=r.offset,i=e.getNode(),s=r.getNode();if(t.isCollapsed()){if(!Le(i))return;let a=i.getChildrenSize(),l=n>=a,c=l?i.getChildAtIndex(a-1):i.getChildAtIndex(n);if(Bt(c)){let u=0;l&&(u=c.getTextContentSize()),e.set(c.__key,u,"text"),r.set(c.__key,u,"text")}}else{if(Le(i)){let a=i.getChildrenSize(),l=n>=a,c=l?i.getChildAtIndex(a-1):i.getChildAtIndex(n);if(Bt(c)){let u=0;l&&(u=c.getTextContentSize()),e.set(c.__key,u,"text")}}if(Le(s)){let a=s.getChildrenSize(),l=o>=a,c=l?s.getChildAtIndex(a-1):s.getChildAtIndex(o);if(Bt(c)){let u=0;l&&(u=c.getTextContentSize()),r.set(c.__key,u,"text")}}}}function P7(t,e,n,r,o){let i=null,s=0,a=null;r!==null?(i=r.__key,Bt(r)?(s=r.getTextContentSize(),a="text"):Le(r)&&(s=r.getChildrenSize(),a="element")):o!==null&&(i=o.__key,Bt(o)?a="text":Le(o)&&(a="element")),i!==null&&a!==null?t.set(i,s,a):(s=e.getIndexWithinParent(),s===-1&&(s=n.getChildrenSize()),t.set(n.__key,s,"element"))}function yat(t,e,n,r,o){t.type==="text"?t.set(n,t.offset+(e?0:o),"text"):t.offset>r.getIndexWithinParent()&&t.set(t.key,t.offset-1,"element")}function Olt(t,e,n,r,o){try{t.setBaseAndExtent(e,n,r,o)}catch{}}function PZt(t,e,n,r,o,i,s){let a=r.anchorNode,l=r.focusNode,c=r.anchorOffset,u=r.focusOffset,d=document.activeElement;if(o.has(Ult)&&d!==i||d!==null&&QSe(d))return;if(!dn(e))return void(t!==null&&N4(n,a,l)&&r.removeAllRanges());let f=e.anchor,p=e.focus,m=f.key,h=p.key,g=GL(n,m),y=GL(n,h),w=f.offset,v=p.offset,x=e.format,b=e.style,_=e.isCollapsed(),T=g,S=y,P=!1;if(f.type==="text"){T=sE(g);let W=f.getNode();P=W.getFormat()!==x||W.getStyle()!==b}else dn(t)&&t.anchor.type==="text"&&(P=!0);var A,O,D,$,B;if(p.type==="text"&&(S=sE(y)),T!==null&&S!==null&&(_&&(t===null||P||dn(t)&&(t.format!==x||t.style!==b))&&(A=x,O=b,D=w,$=m,B=performance.now(),blt=[A,O,D,$,B]),c!==w||u!==v||a!==T||l!==S||r.type==="Range"&&_||(d!==null&&i.contains(d)||i.focus({preventScroll:!0}),f.type==="element"))){if(Olt(r,T,w,S,v),!o.has(Blt)&&e.isCollapsed()&&i!==null&&i===document.activeElement){let W=dn(e)&&e.anchor.type==="element"?T.childNodes[w]||null:r.rangeCount>0?r.getRangeAt(0):null;if(W!==null){let F;if(W instanceof Text){let Z=document.createRange();Z.selectNode(W),F=Z.getBoundingClientRect()}else F=W.getBoundingClientRect();(function(Z,V,H){let te=iTe(H),fe=sTe(te);if(te===null||fe===null)return;let{top:me,bottom:j}=V,G=0,J=0,M=H;for(;M!==null;){let E=M===te.body;if(E)G=0,J=em(Z).innerHeight;else{let L=M.getBoundingClientRect();G=L.top,J=L.bottom}let R=0;if(me<G?R=-(G-me):j>J&&(R=j-J),R!==0)if(E)fe.scrollBy(0,R);else{let L=M.scrollTop;M.scrollTop+=R;let K=M.scrollTop-L;me-=K,j-=K}if(E)break;M=R4(M)}})(n,F,i)}}wSe=!0}}function EZt(t){let e=Gr()||lE();e===null&&(e=md().selectEnd()),e.insertNodes(t)}function AZt(){let t=Gr();return t===null?"":t.getTextContent()}function X_e(t){let e=t;t.isCollapsed()||e.removeText();let n=Gr();dn(n)&&(e=n),dn(e)||De(161);let r=e.anchor,o=r.getNode(),i=r.offset;for(;!rx(o);){let s=o;if([o,i]=kZt(o,i),s.is(o))break}return i}function kZt(t,e){let n=t.getParent();if(!n){let o=ox();return md().append(o),o.select(),[md(),0]}if(Bt(t)){let o=t.splitText(e);if(o.length===0)return[n,t.getIndexWithinParent()];let i=e===0?0:1;return[n,o[0].getIndexWithinParent()+i]}if(!Le(t)||e===0)return[n,t.getIndexWithinParent()];let r=t.getChildAtIndex(e);if(r){let o=new iE(Eh(t.__key,e,"element"),Eh(t.__key,e,"element"),0,""),i=t.insertNewAfter(o);i&&i.append(r,...r.getNextSiblings())}return[n,t.getIndexWithinParent()+1]}function wat(t,e,n,r,o="decorators-and-blocks"){if(e==="move"&&r==="character"&&!t.isCollapsed()){let[u,d]=n===t.isBackward()?[t.focus,t.anchor]:[t.anchor,t.focus];return d.set(u.key,u.offset,u.type),!0}let i=eS(t.focus,n?"previous":"next"),s=r==="lineboundary",a=e==="move",l=i,c=o==="decorators-and-blocks";if(!hct(l)){for(let u of l){c=!1;let{origin:d}=u;if(!Ao(d)||d.isIsolated()||(l=u,!s||!d.isInline()))break}if(c)for(let u of dTe(i).iterNodeCarets(e==="extend"?"shadowRoot":"root")){if(Ih(u))u.origin.isInline()||(l=u);else{if(Le(u.origin))continue;Ao(u.origin)&&!u.origin.isInline()&&(l=u)}break}}if(l===i)return!1;if(a&&!s&&Ao(l.origin)&&l.origin.isKeyboardSelectable()){let u=qSe();return u.add(l.origin.getKey()),hd(u),!0}return l=Sh(l),a&&QL(t.anchor,l),QL(t.focus,l),c||!s}var tl=null,nl=null,pd=!1,Q_e=!1,p7=0,vat={characterData:!0,childList:!0,subtree:!0};function e1(){return pd||tl!==null&&tl._readOnly}function Qa(){pd&&De(13)}function Rlt(){p7>99&&De(14)}function lx(){return tl===null&&De(195,Llt()),tl}function wi(){return nl===null&&De(196,Llt()),nl}function Llt(){let t=0,e=new Set,n=qL.version;if(typeof window<"u")for(let o of document.querySelectorAll("[contenteditable]")){let i=O4(o);if(z7(i))t++;else if(i){let s=String(i.constructor.version||"<0.17.1");s===n&&(s+=" (separately built, likely a bundler configuration issue)"),e.add(s)}}let r=` Detected on the page: ${t} compatible editor(s) with version ${n}`;return e.size&&(r+=` and incompatible editors with versions ${Array.from(e).join(", ")}`),r}function MZt(){return nl}function xat(t,e,n){let r=e.__type,o=JSe(t,r),i=n.get(r);i===void 0&&(i=Array.from(o.transforms),n.set(r,i));let s=i.length;for(let a=0;a<s&&(i[a](e),e.isAttached());a++);}function bat(t,e){return t!==void 0&&t.__key!==e&&t.isAttached()}function Dlt(t,e){if(!e)return;let n=t._updateTags,r=e;Array.isArray(e)||(r=[e]);for(let o of r)n.add(o)}function NZt(t){return GSe(t,wi()._nodes)}function GSe(t,e){let n=t.type,r=e.get(n);r===void 0&&De(17,n);let o=r.klass;t.type!==o.getType()&&De(18,o.name);let i=o.importJSON(t),s=t.children;if(Le(i)&&Array.isArray(s))for(let a=0;a<s.length;a++){let l=GSe(s[a],e);i.append(l)}return i}function Cat(t,e,n){let r=tl,o=pd,i=nl;tl=e,pd=!0,nl=t;try{return n()}finally{tl=r,pd=o,nl=i}}function nx(t,e){let n=t._pendingEditorState,r=t._rootElement,o=t._headless||r===null;if(n===null)return;let i=t._editorState,s=i._selection,a=n._selection,l=t._dirtyType!==nE,c=tl,u=pd,d=nl,f=t._updating,p=t._observer,m=null;if(t._pendingEditorState=null,t._editorState=n,!o&&l&&p!==null){nl=t,tl=n,pd=!1,t._updating=!0;try{let _=t._dirtyType,T=t._dirtyElements,S=t._dirtyLeaves;p.disconnect(),m=iZt(i,n,t,_,T,S)}catch(_){if(_ instanceof Error&&t._onError(_),Q_e)throw _;return jlt(t,null,r,n),Wat(t),t._dirtyType=zL,Q_e=!0,nx(t,i),void(Q_e=!1)}finally{p.observe(r,vat),t._updating=f,tl=c,pd=u,nl=d}}n._readOnly||(n._readOnly=!0);let h=t._dirtyLeaves,g=t._dirtyElements,y=t._normalizedNodes,w=t._updateTags,v=t._deferred;l&&(t._dirtyType=nE,t._cloneNotNeeded.clear(),t._dirtyLeaves=new Set,t._dirtyElements=new Map,t._normalizedNodes=new Set,t._updateTags=new Set),function(_,T){let S=_._decorators,P=_._pendingDecorators||S,A=T._nodeMap,O;for(O in P)A.has(O)||(P===S&&(P=qlt(_)),delete P[O])}(t,n);let x=o?null:Ay(em(t));if(t._editable&&x!==null&&(l||a===null||a.dirty)&&r!==null&&!w.has(zlt)){nl=t,tl=n;try{if(p!==null&&p.disconnect(),l||a===null||a.dirty){let _=t._blockCursorElement;_!==null&&TSe(_,t,r),PZt(s,a,t,x,w,r)}(function(_,T,S){let P=_._blockCursorElement;if(dn(S)&&S.isCollapsed()&&S.anchor.type==="element"&&T.contains(document.activeElement)){let A=S.anchor,O=A.getNode(),D=A.offset,$=!1,B=null;if(D===O.getChildrenSize())tSe(O.getChildAtIndex(D-1))&&($=!0);else{let W=O.getChildAtIndex(D);if(W!==null&&tSe(W)){let F=W.getPreviousSibling();(F===null||tSe(F))&&($=!0,B=_.getElementByKey(W.__key))}}if($){let W=_.getElementByKey(O.__key);return P===null&&(_._blockCursorElement=P=function(F){let Z=F.theme,V=document.createElement("div");V.contentEditable="false",V.setAttribute("data-lexical-cursor","true");let H=Z.blockCursor;if(H!==void 0){if(typeof H=="string"){let te=y7(H);H=Z.blockCursor=te}H!==void 0&&V.classList.add(...H)}return V}(_._config)),T.style.caretColor="transparent",void(B===null?W.appendChild(P):W.insertBefore(P,B))}}P!==null&&TSe(P,_,T)})(t,r,a)}finally{p!==null&&p.observe(r,vat),nl=d,tl=c}}m!==null&&function(_,T,S,P,A){let O=Array.from(_._listeners.mutation),D=O.length;for(let $=0;$<D;$++){let[B,W]=O[$];for(let F of W){let Z=T.get(F);Z!==void 0&&B(Z,{dirtyLeaves:P,prevEditorState:A,updateTags:S})}}}(t,m,w,h,i),dn(a)||a===null||s!==null&&s.is(a)||t.dispatchCommand(USe,void 0);let b=t._pendingDecorators;b!==null&&(t._decorators=b,t._pendingDecorators=null,w4("decorator",t,!0,b)),function(_,T,S){let P=Pat(T),A=Pat(S);P!==A&&w4("textcontent",_,!0,A)}(t,e||i,n),w4("update",t,!0,{dirtyElements:g,dirtyLeaves:h,editorState:n,mutatedNodes:m,normalizedNodes:y,prevEditorState:e||i,tags:w}),function(_,T){if(_._deferred=[],T.length!==0){let S=_._updating;_._updating=!0;try{for(let P=0;P<T.length;P++)T[P]()}finally{_._updating=S}}}(t,v),function(_){let T=_._updates;if(T.length!==0){let S=T.shift();if(S){let[P,A]=S;B7(_,P,A)}}}(t)}function w4(t,e,n,...r){let o=e._updating;e._updating=n;try{let i=Array.from(e._listeners[t]);for(let s=0;s<i.length;s++)i[s].apply(null,r)}finally{e._updating=o}}function _at(t,e){let n=t._updates,r=e||!1;for(;n.length!==0;){let o=n.shift();if(o){let[i,s]=o,a=t._pendingEditorState,l;s!==void 0&&(l=s.onUpdate,s.skipTransforms&&(r=!0),s.discrete&&(a===null&&De(191),a._flushSync=!0),l&&t._deferred.push(l),Dlt(t,s.tag)),a==null?B7(t,i,s):i()}}return r}function B7(t,e,n){let r=t._updateTags,o,i=!1,s=!1;n!==void 0&&(o=n.onUpdate,Dlt(t,n.tag),i=n.skipTransforms||!1,s=n.discrete||!1),o&&t._deferred.push(o);let a=t._editorState,l=t._pendingEditorState,c=!1;(l===null||l._readOnly)&&(l=t._pendingEditorState=$lt(l||a),c=!0),l._flushSync=s;let u=tl,d=pd,f=nl,p=t._updating;tl=l,pd=!1,t._updating=!0,nl=t;let m=t._headless||t.getRootElement()===null;ZSe(null);try{c&&(m?a._selection!==null&&(l._selection=a._selection.clone()):l._selection=function(w,v){let x=w.getEditorState()._selection,b=Ay(em(w));return dn(x)||x==null?U7(x,b,w,v):x.clone()}(t,n&&n.event||null));let g=t._compositionKey;e(),i=_at(t,i),function(w,v){let x=v.getEditorState()._selection,b=w._selection;if(dn(b)){let _=b.anchor,T=b.focus,S;if(_.type==="text"&&(S=_.getNode(),S.selectionTransform(x,b)),T.type==="text"){let P=T.getNode();S!==P&&P.selectionTransform(x,b)}}}(l,t),t._dirtyType!==nE&&(i?function(w,v){let x=v._dirtyLeaves,b=w._nodeMap;for(let _ of x){let T=b.get(_);Bt(T)&&T.isAttached()&&T.isSimpleText()&&!T.isUnmergeable()&&eat(T)}}(l,t):function(w,v){let x=v._dirtyLeaves,b=v._dirtyElements,_=w._nodeMap,T=K_(),S=new Map,P=x,A=P.size,O=b,D=O.size;for(;A>0||D>0;){if(A>0){v._dirtyLeaves=new Set;for(let $ of P){let B=_.get($);Bt(B)&&B.isAttached()&&B.isSimpleText()&&!B.isUnmergeable()&&eat(B),B!==void 0&&bat(B,T)&&xat(v,B,S),x.add($)}if(P=v._dirtyLeaves,A=P.size,A>0){p7++;continue}}v._dirtyLeaves=new Set,v._dirtyElements=new Map,O.delete("root")&&O.set("root",!0);for(let $ of O){let B=$[0],W=$[1];if(b.set(B,W),!W)continue;let F=_.get(B);F!==void 0&&bat(F,T)&&xat(v,F,S)}P=v._dirtyLeaves,A=P.size,O=v._dirtyElements,D=O.size,p7++}v._dirtyLeaves=x,v._dirtyElements=b}(l,t),_at(t),function(w,v,x,b){let _=w._nodeMap,T=v._nodeMap,S=[];for(let[P]of b){let A=T.get(P);A!==void 0&&(A.isAttached()||(Le(A)&&zat(A,P,_,T,S,b),_.has(P)||b.delete(P),S.push(P)))}for(let P of S)T.delete(P);for(let P of x){let A=T.get(P);A===void 0||A.isAttached()||(_.has(P)||x.delete(P),T.delete(P))}}(a,l,t._dirtyLeaves,t._dirtyElements)),g!==t._compositionKey&&(l._flushSync=!0);let y=l._selection;if(dn(y)){let w=l._nodeMap,v=y.anchor.key,x=y.focus.key;w.get(v)!==void 0&&w.get(x)!==void 0||De(19)}else F7(y)&&y._nodes.size===0&&(l._selection=null)}catch(g){return g instanceof Error&&t._onError(g),t._pendingEditorState=a,t._dirtyType=zL,t._cloneNotNeeded.clear(),t._dirtyLeaves=new Set,t._dirtyElements.clear(),void nx(t)}finally{tl=u,pd=d,nl=f,t._updating=p,p7=0}t._dirtyType!==nE||t._deferred.length>0||function(g,y){let w=y.getEditorState()._selection,v=g._selection;if(v!==null){if(v.dirty||!v.is(w))return!0}else if(w!==null)return!0;return!1}(l,t)?l._flushSync?(l._flushSync=!1,nx(t)):c&&KZt(()=>{nx(t)}):(l._flushSync=!1,c&&(r.clear(),t._deferred=[],t._pendingEditorState=null))}function wf(t,e,n){nl===t&&n===void 0?e():B7(t,e,n)}var _Se=class t{constructor(e,n,r){this.element=e,this.before=n||null,this.after=r||null}withBefore(e){return new t(this.element,e,this.after)}withAfter(e){return new t(this.element,this.before,e)}withElement(e){return this.element===e?this:new t(e,this.before,this.after)}insertChild(e){let n=this.before||this.getManagedLineBreak();return n!==null&&n.parentElement!==this.element&&De(222),this.element.insertBefore(e,n),this}removeChild(e){return e.parentElement!==this.element&&De(223),this.element.removeChild(e),this}replaceChild(e,n){return n.parentElement!==this.element&&De(224),this.element.replaceChild(e,n),this}getFirstChild(){let e=this.after?this.after.nextSibling:this.element.firstChild;return e===this.before||e===this.getManagedLineBreak()?null:e}getManagedLineBreak(){return this.element.__lexicalLineBreak||null}setManagedLineBreak(e){if(e===null)this.removeManagedLineBreak();else{let n=e==="decorator"&&(BL||b4);this.insertManagedLineBreak(n)}}removeManagedLineBreak(){let e=this.getManagedLineBreak();if(e){let n=this.element,r=e.nodeName==="IMG"?e.nextSibling:null;r&&n.removeChild(r),n.removeChild(e),n.__lexicalLineBreak=void 0}}insertManagedLineBreak(e){let n=this.getManagedLineBreak();if(n){if(e===(n.nodeName==="IMG"))return;this.removeManagedLineBreak()}let r=this.element,o=this.before,i=document.createElement("br");if(r.insertBefore(i,o),e){let s=document.createElement("img");s.setAttribute("data-lexical-linebreak","true"),s.style.cssText="display: inline !important; border: 0px !important; margin: 0px !important;",s.alt="",r.insertBefore(s,i),r.__lexicalLineBreak=s}else r.__lexicalLineBreak=i}getFirstChildOffset(){let e=0;for(let n=this.after;n!==null;n=n.previousSibling)e++;return e}resolveChildIndex(e,n,r,o){if(r===this.element){let l=this.getFirstChildOffset();return[e,Math.min(l+e.getChildrenSize(),Math.max(l,o))]}let i=Sat(n,r);i.push(o);let s=Sat(n,this.element),a=e.getIndexWithinParent();for(let l=0;l<s.length;l++){let c=i[l],u=s[l];if(c===void 0||c<u)break;if(c>u){a+=1;break}}return[e.getParentOrThrow(),a]}};function Sat(t,e){let n=[],r=e;for(;r!==t&&r!==null;r=r.parentNode){let o=0;for(let i=r.previousSibling;i!==null;i=i.previousSibling)o++;n.push(o)}return r!==t&&De(225),n.reverse()}var J_=class extends Z_{constructor(e){super(e),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=""}afterCloneFrom(e){super.afterCloneFrom(e),this.__key===e.__key&&(this.__first=e.__first,this.__last=e.__last,this.__size=e.__size),this.__indent=e.__indent,this.__format=e.__format,this.__style=e.__style,this.__dir=e.__dir,this.__textFormat=e.__textFormat,this.__textStyle=e.__textStyle}getFormat(){return this.getLatest().__format}getFormatType(){let e=this.getFormat();return WYt[e]||""}getStyle(){return this.getLatest().__style}getIndent(){return this.getLatest().__indent}getChildren(){let e=[],n=this.getFirstChild();for(;n!==null;)e.push(n),n=n.getNextSibling();return e}getChildrenKeys(){let e=[],n=this.getFirstChild();for(;n!==null;)e.push(n.__key),n=n.getNextSibling();return e}getChildrenSize(){return this.getLatest().__size}isEmpty(){return this.getChildrenSize()===0}isDirty(){let e=wi()._dirtyElements;return e!==null&&e.has(this.__key)}isLastChild(){let e=this.getLatest(),n=this.getParentOrThrow().getLastChild();return n!==null&&n.is(e)}getAllTextNodes(){let e=[],n=this.getFirstChild();for(;n!==null;){if(Bt(n)&&e.push(n),Le(n)){let r=n.getAllTextNodes();e.push(...r)}n=n.getNextSibling()}return e}getFirstDescendant(){let e=this.getFirstChild();for(;Le(e);){let n=e.getFirstChild();if(n===null)break;e=n}return e}getLastDescendant(){let e=this.getLastChild();for(;Le(e);){let n=e.getLastChild();if(n===null)break;e=n}return e}getDescendantByIndex(e){let n=this.getChildren(),r=n.length;if(e>=r){let i=n[r-1];return Le(i)&&i.getLastDescendant()||i||null}let o=n[e];return Le(o)&&o.getFirstDescendant()||o||null}getFirstChild(){let e=this.getLatest().__first;return e===null?null:wa(e)}getFirstChildOrThrow(){let e=this.getFirstChild();return e===null&&De(45,this.__key),e}getLastChild(){let e=this.getLatest().__last;return e===null?null:wa(e)}getLastChildOrThrow(){let e=this.getLastChild();return e===null&&De(96,this.__key),e}getChildAtIndex(e){let n=this.getChildrenSize(),r,o;if(e<n/2){for(r=this.getFirstChild(),o=0;r!==null&&o<=e;){if(o===e)return r;r=r.getNextSibling(),o++}return null}for(r=this.getLastChild(),o=n-1;r!==null&&o>=e;){if(o===e)return r;r=r.getPreviousSibling(),o--}return null}getTextContent(){let e="",n=this.getChildren(),r=n.length;for(let o=0;o<r;o++){let i=n[o];e+=i.getTextContent(),Le(i)&&o!==r-1&&!i.isInline()&&(e+=sx)}return e}getTextContentSize(){let e=0,n=this.getChildren(),r=n.length;for(let o=0;o<r;o++){let i=n[o];e+=i.getTextContentSize(),Le(i)&&o!==r-1&&!i.isInline()&&(e+=sx.length)}return e}getDirection(){return this.getLatest().__dir}getTextFormat(){return this.getLatest().__textFormat}hasFormat(e){if(e!==""){let n=Kst[e];return!!(this.getFormat()&n)}return!1}hasTextFormat(e){let n=vc[e];return!!(this.getTextFormat()&n)}getFormatFlags(e,n){return k7(this.getLatest().__textFormat,e,n)}getTextStyle(){return this.getLatest().__textStyle}select(e,n){Qa();let r=Gr(),o=e,i=n,s=this.getChildrenSize();if(!this.canBeEmpty()){if(e===0&&n===0){let l=this.getFirstChild();if(Bt(l)||Le(l))return l.select(0,0)}else if(!(e!==void 0&&e!==s||n!==void 0&&n!==s)){let l=this.getLastChild();if(Bt(l)||Le(l))return l.select()}}o===void 0&&(o=s),i===void 0&&(i=s);let a=this.__key;return dn(r)?(r.anchor.set(a,o,"element"),r.focus.set(a,i,"element"),r.dirty=!0,r):Mlt(a,o,a,i,"element","element")}selectStart(){let e=this.getFirstDescendant();return e?e.selectStart():this.select()}selectEnd(){let e=this.getLastDescendant();return e?e.selectEnd():this.select()}clear(){let e=this.getWritable();return this.getChildren().forEach(n=>n.remove()),e}append(...e){return this.splice(this.getChildrenSize(),0,e)}setDirection(e){let n=this.getWritable();return n.__dir=e,n}setFormat(e){return this.getWritable().__format=e!==""?Kst[e]:0,this}setStyle(e){return this.getWritable().__style=e||"",this}setTextFormat(e){let n=this.getWritable();return n.__textFormat=e,n}setTextStyle(e){let n=this.getWritable();return n.__textStyle=e,n}setIndent(e){return this.getWritable().__indent=e,this}splice(e,n,r){let o=r.length,i=this.getChildrenSize(),s=this.getWritable();e+n<=i||De(226,String(e),String(n),String(i));let a=s.__key,l=[],c=[],u=this.getChildAtIndex(e+n),d=null,f=i-n+o;if(e!==0)if(e===i)d=this.getLastChild();else{let m=this.getChildAtIndex(e);m!==null&&(d=m.getPreviousSibling())}if(n>0){let m=d===null?this.getFirstChild():d.getNextSibling();for(let h=0;h<n;h++){m===null&&De(100);let g=m.getNextSibling(),y=m.__key;G_(m.getWritable()),c.push(y),m=g}}let p=d;for(let m=0;m<o;m++){let h=r[m];p!==null&&h.is(p)&&(d=p=p.getPreviousSibling());let g=h.getWritable();g.__parent===a&&f--,G_(g);let y=h.__key;if(p===null)s.__first=y,g.__prev=null;else{let w=p.getWritable();w.__next=y,g.__prev=w.__key}h.__key===a&&De(76),g.__parent=a,l.push(y),p=h}if(e+n===i)p!==null&&(p.getWritable().__next=null,s.__last=p.__key);else if(u!==null){let m=u.getWritable();if(p!==null){let h=p.getWritable();m.__prev=p.__key,h.__next=u.__key}else m.__prev=null}if(s.__size=f,c.length){let m=Gr();if(dn(m)){let h=new Set(c),g=new Set(l),{anchor:y,focus:w}=m;Tat(y,h,g)&&P7(y,y.getNode(),this,d,u),Tat(w,h,g)&&P7(w,w.getNode(),this,d,u),f!==0||this.canBeEmpty()||Ah(this)||this.remove()}}return s}getDOMSlot(e){return new _Se(e)}exportDOM(e){let{element:n}=super.exportDOM(e);if(pu(n)){let r=this.getIndent();r>0&&(n.style.paddingInlineStart=40*r+"px");let o=this.getDirection();o&&(n.dir=o)}return{element:n}}exportJSON(){let e={children:[],direction:this.getDirection(),format:this.getFormatType(),indent:this.getIndent(),...super.exportJSON()},n=this.getTextFormat(),r=this.getTextStyle();return n!==0&&(e.textFormat=n),r!==""&&(e.textStyle=r),e}updateFromJSON(e){return super.updateFromJSON(e).setFormat(e.format).setIndent(e.indent).setDirection(e.direction).setTextFormat(e.textFormat||0).setTextStyle(e.textStyle||"")}insertNewAfter(e,n){return null}canIndent(){return!0}collapseAtStart(e){return!1}excludeFromCopy(e){return!1}canReplaceWith(e){return!0}canInsertAfter(e){return!0}canBeEmpty(){return!0}canInsertTextBefore(){return!0}canInsertTextAfter(){return!0}isInline(){return!1}isShadowRoot(){return!1}canMergeWith(e){return!1}extractWithChild(e,n,r){return!1}canMergeWhenEmpty(){return!1}reconcileObservedMutation(e,n){let r=this.getDOMSlot(e),o=r.getFirstChild();for(let i=this.getFirstChild();i;i=i.getNextSibling()){let s=n.getElementByKey(i.getKey());s!==null&&(o==null?(r.insertChild(s),o=s):o!==s&&r.replaceChild(s,o),o=o.nextSibling)}}};function Le(t){return t instanceof J_}function Tat(t,e,n){let r=t.getNode();for(;r;){let o=r.__key;if(e.has(o)&&!n.has(o))return!0;r=r.getParent()}return!1}var k4=class extends Z_{decorate(e,n){De(47)}isIsolated(){return!1}isInline(){return!0}isKeyboardSelectable(){return!0}};function Ao(t){return t instanceof k4}var HL=class t extends J_{static getType(){return"root"}static clone(){return new t}constructor(){super("root"),this.__cachedText=null}getTopLevelElementOrThrow(){De(51)}getTextContent(){let e=this.__cachedText;return!e1()&&wi()._dirtyType!==nE||e===null?super.getTextContent():e}remove(){De(52)}replace(e){De(53)}insertBefore(e){De(54)}insertAfter(e){De(55)}updateDOM(e,n){return!1}splice(e,n,r){for(let o of r)Le(o)||Ao(o)||De(282);return super.splice(e,n,r)}static importJSON(e){return md().updateFromJSON(e)}collapseAtStart(){return!0}};function fd(t){return t instanceof HL}function $lt(t){return new E7(new Map(t._nodeMap))}function YSe(){return new E7(new Map([["root",new HL]]))}function Flt(t){let e=t.exportJSON(),n=t.constructor;if(e.type!==n.getType()&&De(130,n.name),Le(t)){let r=e.children;Array.isArray(r)||De(59,n.name);let o=t.getChildren();for(let i=0;i<o.length;i++){let s=Flt(o[i]);r.push(s)}}return e}var E7=class t{constructor(e,n){this._nodeMap=e,this._selection=n||null,this._flushSync=!1,this._readOnly=!1}isEmpty(){return this._nodeMap.size===1&&this._selection===null}read(e,n){return Cat(n&&n.editor||null,this,e)}clone(e){let n=new t(this._nodeMap,e===void 0?this._selection:e);return n._readOnly=!0,n}toJSON(){return Cat(null,this,()=>({root:Flt(md())}))}},OZt="historic",RZt="history-push",m7="history-merge",LZt="paste",Ult="collaboration",DZt="skip-collab",Blt="skip-scroll-into-view",zlt="skip-dom-selection",A7=class extends J_{static getType(){return"artificial"}createDOM(e){return document.createElement("div")}},KL=class t extends J_{static getType(){return"paragraph"}static clone(e){return new t(e.__key)}createDOM(e){let n=document.createElement("p"),r=UL(e.theme,"paragraph");return r!==void 0&&n.classList.add(...r),n}updateDOM(e,n,r){return!1}static importDOM(){return{p:e=>({conversion:$Zt,priority:0})}}exportDOM(e){let{element:n}=super.exportDOM(e);if(pu(n)){this.isEmpty()&&n.append(document.createElement("br"));let r=this.getFormatType();r&&(n.style.textAlign=r)}return{element:n}}static importJSON(e){return ox().updateFromJSON(e)}exportJSON(){return{...super.exportJSON(),textFormat:this.getTextFormat(),textStyle:this.getTextStyle()}}insertNewAfter(e,n){let r=ox();r.setTextFormat(e.format),r.setTextStyle(e.style);let o=this.getDirection();return r.setDirection(o),r.setFormat(this.getFormatType()),r.setStyle(this.getStyle()),this.insertAfter(r,n),r}collapseAtStart(){let e=this.getChildren();if(e.length===0||Bt(e[0])&&e[0].getTextContent().trim()===""){if(this.getNextSibling()!==null)return this.selectNext(),this.remove(),!0;if(this.getPreviousSibling()!==null)return this.selectPrevious(),this.remove(),!0}return!1}};function $Zt(t){let e=ox();return t.style&&(e.setFormat(t.style.textAlign),cct(t,e)),{node:e}}function ox(){return L4(new KL)}function FZt(t){return t instanceof KL}var UZt=0,BZt=1,zZt=2,jZt=3,VZt=4;function jlt(t,e,n,r){let o=t._keyToDOMMap;o.clear(),t._editorState=YSe(),t._pendingEditorState=r,t._compositionKey=null,t._dirtyType=nE,t._cloneNotNeeded.clear(),t._dirtyLeaves=new Set,t._dirtyElements.clear(),t._normalizedNodes=new Set,t._updateTags=new Set,t._updates=[],t._blockCursorElement=null;let i=t._observer;i!==null&&(i.disconnect(),t._observer=null),e!==null&&(e.textContent=""),n!==null&&(n.textContent="",o.set("root",n))}function WZt(t){let e=t||{},n=MZt(),r=e.theme||{},o=t===void 0?n:e.parentEditor||null,i=e.disableEvents||!1,s=YSe(),a=e.namespace||(o!==null?o._config.namespace:Zlt()),l=e.editorState,c=[HL,oE,jL,WL,KL,A7,...e.nodes||[]],{onError:u,html:d}=e,f=e.editable===void 0||e.editable,p;if(t===void 0&&n!==null)p=n._nodes;else{p=new Map;for(let h=0;h<c.length;h++){let g=c[h],y=null,w=null;if(typeof g!="function"){let T=g;g=T.replace,y=T.with,w=T.withKlass||null}let{ownNodeConfig:v}=cTe(g),x=g.getType(),b=g.transform(),_=new Set;v&&v.$transform&&_.add(v.$transform),b!==null&&_.add(b),p.set(x,{exportDOM:d&&d.export?d.export.get(g):void 0,klass:g,replace:y,replaceWithKlass:w,sharedNodeState:Hat(c[h]),transforms:_})}}let m=new qL(s,o,p,{disableEvents:i,namespace:a,theme:r},u||console.error,function(h,g){let y=new Map,w=new Set,v=x=>{Object.keys(x).forEach(b=>{let _=y.get(b);_===void 0&&(_=[],y.set(b,_)),_.push(x[b])})};return h.forEach(x=>{let b=x.klass.importDOM;if(b==null||w.has(b))return;w.add(b);let _=b.call(x.klass);_!==null&&v(_)}),g&&v(g),y}(p,d?d.import:void 0),f,t);return l!==void 0&&(m._pendingEditorState=l,m._dirtyType=zL),m}var qL=class{constructor(e,n,r,o,i,s,a,l){this._createEditorArgs=l,this._parentEditor=n,this._rootElement=null,this._editorState=e,this._pendingEditorState=null,this._compositionKey=null,this._deferred=[],this._keyToDOMMap=new Map,this._updates=[],this._updating=!1,this._listeners={decorator:new Set,editable:new Set,mutation:new Map,root:new Set,textcontent:new Set,update:new Set},this._commands=new Map,this._config=o,this._nodes=r,this._decorators={},this._pendingDecorators=null,this._dirtyType=nE,this._cloneNotNeeded=new Set,this._dirtyLeaves=new Set,this._dirtyElements=new Map,this._normalizedNodes=new Set,this._updateTags=new Set,this._observer=null,this._key=Zlt(),this._onError=i,this._htmlConversions=s,this._editable=a,this._headless=n!==null&&n._headless,this._window=null,this._blockCursorElement=null}isComposing(){return this._compositionKey!=null}registerUpdateListener(e){let n=this._listeners.update;return n.add(e),()=>{n.delete(e)}}registerEditableListener(e){let n=this._listeners.editable;return n.add(e),()=>{n.delete(e)}}registerDecoratorListener(e){let n=this._listeners.decorator;return n.add(e),()=>{n.delete(e)}}registerTextContentListener(e){let n=this._listeners.textcontent;return n.add(e),()=>{n.delete(e)}}registerRootListener(e){let n=this._listeners.root;return e(this._rootElement,null),n.add(e),()=>{e(null,this._rootElement),n.delete(e)}}registerCommand(e,n,r){r===void 0&&De(35);let o=this._commands;o.has(e)||o.set(e,[new Set,new Set,new Set,new Set,new Set]);let i=o.get(e);i===void 0&&De(36,String(e));let s=i[r];return s.add(n),()=>{s.delete(n),i.every(a=>a.size===0)&&o.delete(e)}}registerMutationListener(e,n,r){let o=this.resolveRegisteredNodeAfterReplacements(this.getRegisteredNode(e)).klass,i=this._listeners.mutation,s=i.get(n);s===void 0&&(s=new Set,i.set(n,s)),s.add(o);let a=r&&r.skipInitialization;return a!==void 0&&a||this.initializeMutationListener(n,o),()=>{s.delete(o),s.size===0&&i.delete(n)}}getRegisteredNode(e){let n=this._nodes.get(e.getType());return n===void 0&&De(37,e.name),n}resolveRegisteredNodeAfterReplacements(e){for(;e.replaceWithKlass;)e=this.getRegisteredNode(e.replaceWithKlass);return e}initializeMutationListener(e,n){let r=this._editorState,o=PSe(r).get(n.getType());if(!o)return;let i=new Map;for(let s of o.keys())i.set(s,"created");i.size>0&&e(i,{dirtyLeaves:new Set,prevEditorState:r,updateTags:new Set(["registerMutationListener"])})}registerNodeTransformToKlass(e,n){let r=this.getRegisteredNode(e);return r.transforms.add(n),r}registerNodeTransform(e,n){let r=this.registerNodeTransformToKlass(e,n),o=[r],i=r.replaceWithKlass;if(i!=null){let s=this.registerNodeTransformToKlass(i,n);o.push(s)}return function(s,a){let l=PSe(s.getEditorState()),c=[];for(let u of a){let d=l.get(u);d&&c.push(d)}c.length!==0&&s.update(()=>{for(let u of c)for(let d of u.keys()){let f=wa(d);f&&f.markDirty()}},s._pendingEditorState===null?{tag:m7}:void 0)}(this,o.map(s=>s.klass.getType())),()=>{o.forEach(s=>s.transforms.delete(n))}}hasNode(e){return this._nodes.has(e.getType())}hasNodes(e){return e.every(this.hasNode.bind(this))}dispatchCommand(e,n){return Et(this,e,n)}getDecorators(){return this._decorators}getRootElement(){return this._rootElement}getKey(){return this._key}setRootElement(e){let n=this._rootElement;if(e!==n){let r=UL(this._config.theme,"root"),o=this._pendingEditorState||this._editorState;if(this._rootElement=e,jlt(this,n,e,o),n!==null&&(this._config.disableEvents||gZt(n),r!=null&&n.classList.remove(...r)),e!==null){let i=sTe(e),s=e.style;s.userSelect="text",s.whiteSpace="pre-wrap",s.wordBreak="break-word",e.setAttribute("data-lexical-editor","true"),this._window=i,this._dirtyType=zL,Wat(this),this._updateTags.add(m7),nx(this),this._config.disableEvents||function(a,l){let c=a.ownerDocument,u=S7.get(c);(u===void 0||u<1)&&c.addEventListener("selectionchange",Ilt),S7.set(c,(u||0)+1),a.__lexicalEditor=l;let d=Tlt(a);for(let f=0;f<ySe.length;f++){let[p,m]=ySe[f],h=typeof m=="function"?g=>{sat(g)||(iat(g),(l.isEditable()||p==="click")&&m(g,l))}:g=>{if(sat(g))return;iat(g);let y=l.isEditable();switch(p){case"cut":return y&&Et(l,WSe,g);case"copy":return Et(l,VSe,g);case"paste":return y&&Et(l,BSe,g);case"dragstart":return y&&Et(l,plt,g);case"dragover":return y&&Et(l,mlt,g);case"dragend":return y&&Et(l,hlt,g);case"focus":return y&&Et(l,glt,g);case"blur":return y&&Et(l,ylt,g);case"drop":return y&&Et(l,flt,g)}};a.addEventListener(p,h),d.push(()=>{a.removeEventListener(p,h)})}}(e,this),r!=null&&e.classList.add(...r)}else this._window=null,this._updateTags.add(m7),nx(this);w4("root",this,!1,e,n)}}getElementByKey(e){return this._keyToDOMMap.get(e)||null}getEditorState(){return this._editorState}setEditorState(e,n){e.isEmpty()&&De(38);let r=e;r._readOnly&&(r=$lt(e),r._selection=e._selection?e._selection.clone():null),Vat(this);let o=this._pendingEditorState,i=this._updateTags,s=n!==void 0?n.tag:null;o===null||o.isEmpty()||(s!=null&&i.add(s),nx(this)),this._pendingEditorState=r,this._dirtyType=zL,this._dirtyElements.set("root",!1),this._compositionKey=null,s!=null&&i.add(s),this._updating||nx(this)}parseEditorState(e,n){return function(r,o,i){let s=YSe(),a=tl,l=pd,c=nl,u=o._dirtyElements,d=o._dirtyLeaves,f=o._cloneNotNeeded,p=o._dirtyType;o._dirtyElements=new Map,o._dirtyLeaves=new Set,o._cloneNotNeeded=new Set,o._dirtyType=0,tl=s,pd=!1,nl=o,ZSe(null);try{let m=o._nodes;GSe(r.root,m),i&&i(),s._readOnly=!0}catch(m){m instanceof Error&&o._onError(m)}finally{o._dirtyElements=u,o._dirtyLeaves=d,o._cloneNotNeeded=f,o._dirtyType=p,tl=a,pd=l,nl=c}return s}(typeof e=="string"?JSON.parse(e):e,this,n)}read(e){return nx(this),this.getEditorState().read(e,{editor:this})}update(e,n){(function(r,o,i){r._updating?r._updates.push([o,i]):B7(r,o,i)})(this,e,n)}focus(e,n={}){let r=this._rootElement;r!==null&&(r.setAttribute("autocapitalize","off"),wf(this,()=>{let o=Gr(),i=md();o!==null?o.dirty||hd(o.clone()):i.getChildrenSize()!==0&&(n.defaultSelection==="rootStart"?i.selectStart():i.selectEnd()),tct("focus"),nct(()=>{r.removeAttribute("autocapitalize"),e&&e()})}),this._pendingEditorState===null&&r.removeAttribute("autocapitalize"))}blur(){let e=this._rootElement;e!==null&&e.blur();let n=Ay(this._window);n!==null&&n.removeAllRanges()}isEditable(){return this._editable}setEditable(e){this._editable!==e&&(this._editable=e,w4("editable",this,!0,e))}toJSON(){return{editorState:this._editorState.toJSON()}}};qL.version="0.34.0+prod.esm";var SSe=null;function ZSe(t){SSe=t}var Vlt=1;function HZt(){Vlt=1}function JSe(t,e){let n=XSe(t,e);return n===void 0&&De(30,e),n}function XSe(t,e){return t._nodes.get(e)}var KZt=typeof queueMicrotask=="function"?queueMicrotask:t=>{Promise.resolve().then(t)};function Iat(t){return Ao(V7(t))}function QSe(t){let e=document.activeElement;if(!pu(e))return!1;let n=e.nodeName;return Ao(V7(t))&&(n==="INPUT"||n==="TEXTAREA"||e.contentEditable==="true"&&O4(e)==null)}function N4(t,e,n){let r=t.getRootElement();try{return r!==null&&r.contains(e)&&r.contains(n)&&e!==null&&!QSe(e)&&eTe(e)===t}catch{return!1}}function z7(t){return t instanceof qL}function eTe(t){let e=t;for(;e!=null;){let n=O4(e);if(z7(n))return n;e=R4(e)}return null}function O4(t){return t?t.__lexicalEditor:null}function q_(t){return KSe(t)||t.isToken()}function ex(t){return q_(t)||t.isSegmented()}function ky(t){return t1(t)&&t.nodeType===AYt}function Wlt(t){return t1(t)&&t.nodeType===kYt}function sE(t){let e=t;for(;e!=null;){if(ky(e))return e;e=e.firstChild}return null}function k7(t,e,n){let r=vc[e];if(n!==null&&(t&r)==(n&r))return t;let o=t^r;return e==="subscript"?o&=~vc.superscript:e==="superscript"?o&=~vc.subscript:e==="lowercase"?(o&=~vc.uppercase,o&=~vc.capitalize):e==="uppercase"?(o&=~vc.lowercase,o&=~vc.capitalize):e==="capitalize"&&(o&=~vc.lowercase,o&=~vc.uppercase),o}function qZt(t){return Bt(t)||eE(t)||Ao(t)}function Hlt(t,e){let n=function(){let s=SSe;return SSe=null,s}();if((e=e||n&&n.__key)!=null)return void(t.__key=e);Qa(),Rlt();let r=wi(),o=lx(),i=""+Vlt++;o._nodeMap.set(i,t),Le(t)?r._dirtyElements.set(i,!0):r._dirtyLeaves.add(i),r._cloneNotNeeded.add(i),r._dirtyType=$at,t.__key=i}function G_(t){let e=t.getParent();if(e!==null){let n=t.getWritable(),r=e.getWritable(),o=t.getPreviousSibling(),i=t.getNextSibling(),s=i!==null?i.__key:null,a=o!==null?o.__key:null,l=o!==null?o.getWritable():null,c=i!==null?i.getWritable():null;o===null&&(r.__first=s),i===null&&(r.__last=a),l!==null&&(l.__next=s),c!==null&&(c.__prev=a),n.__prev=null,n.__next=null,n.__parent=null,r.__size--}}function M7(t){Rlt();let e=t.getLatest(),n=e.__parent,r=lx(),o=wi(),i=r._nodeMap,s=o._dirtyElements;n!==null&&function(l,c,u){let d=l;for(;d!==null;){if(u.has(d))return;let f=c.get(d);if(f===void 0)break;u.set(d,!1),d=f.__parent}}(n,i,s);let a=e.__key;o._dirtyType=$at,Le(t)?s.set(a,!0):o._dirtyLeaves.add(a)}function el(t){Qa();let e=wi(),n=e._compositionKey;if(t!==n){if(e._compositionKey=t,n!==null){let r=wa(n);r!==null&&r.getWritable()}if(t!==null){let r=wa(t);r!==null&&r.getWritable()}}}function K_(){return e1()?null:wi()._compositionKey}function wa(t,e){let n=(e||lx())._nodeMap.get(t);return n===void 0?null:n}function Klt(t,e){let n=j7(t,wi());return n!==void 0?wa(n,e):null}function j7(t,e){return t[`__lexicalKey_${e._key}`]}function V7(t,e){let n=t;for(;n!=null;){let r=Klt(n,e);if(r!==null)return r;n=R4(n)}return null}function qlt(t){let e=t._decorators,n=Object.assign({},e);return t._pendingDecorators=n,n}function Pat(t){return t.read(()=>md().getTextContent())}function md(){return Glt(lx())}function Glt(t){return t._nodeMap.get("root")}function hd(t){Qa();let e=lx();t!==null&&(t.dirty=!0,t.setCachedNodes(null)),e._selection=t}function DL(t){let e=wi(),n=function(r,o){let i=r;for(;i!=null;){let s=j7(i,o);if(s!==void 0)return s;i=R4(i)}return null}(t,e);return n===null?t===e.getRootElement()?wa("root"):null:wa(n)}function Ylt(t){return/[\uD800-\uDBFF][\uDC00-\uDFFF]/g.test(t)}function tTe(t){let e=[],n=t;for(;n!==null;)e.push(n),n=n._parentEditor;return e}function Zlt(){return Math.random().toString(36).replace(/[^a-z]+/g,"").substring(0,5)}function Jlt(t){return ky(t)?t.nodeValue:null}function nTe(t,e,n){let r=Ay(em(e));if(r===null)return;let o=r.anchorNode,{anchorOffset:i,focusOffset:s}=r;if(o!==null){let a=Jlt(o),l=V7(o);if(a!==null&&Bt(l)){if(a===L7&&n){let c=n.length;a=n,i=c,s=c}a!==null&&rTe(l,a,i,s,t)}}}function rTe(t,e,n,r,o){let i=t;if(i.isAttached()&&(o||!i.isDirty())){let s=i.isComposing(),a=e;(s||o)&&e[e.length-1]===L7&&(a=e.slice(0,-1));let l=i.getTextContent();if(o||a!==l){if(a===""){if(el(null),b4||BL||g7)i.remove();else{let h=wi();setTimeout(()=>{h.update(()=>{i.isAttached()&&i.remove()})},20)}return}let c=i.getParent(),u=lE(),d=i.getTextContentSize(),f=K_(),p=i.getKey();if(i.isToken()||f!==null&&p===f&&!s||dn(u)&&(c!==null&&!c.canInsertTextBefore()&&u.anchor.offset===0||u.anchor.key===t.__key&&u.anchor.offset===0&&!i.canInsertTextBefore()&&!s||u.focus.key===t.__key&&u.focus.offset===d&&!i.canInsertTextAfter()&&!s))return void i.markDirty();let m=Gr();if(!dn(m)||n===null||r===null)return void Eat(i,a,m);if(m.setTextNodeRange(i,n,i,r),i.isSegmented()){let h=Xa(i.getTextContent());i.replace(h),i=h}Eat(i,a,m)}}}function Eat(t,e,n){if(t.setTextContent(e),dn(n)){let r=t.getKey();for(let o of["anchor","focus"]){let i=n[o];i.type==="text"&&i.key===r&&(i.offset=Ph(t,i.offset,"clamp"))}}}function c7(t,e,n){let r=e[n]||!1;return r==="any"||r===t[n]}function Xlt(t,e){return c7(t,e,"altKey")&&c7(t,e,"ctrlKey")&&c7(t,e,"shiftKey")&&c7(t,e,"metaKey")}function ao(t,e,n){return Xlt(t,n)&&t.key.toLowerCase()===e.toLowerCase()}var Qv={ctrlKey:!Ey,metaKey:Ey},Aat={altKey:Ey,ctrlKey:!Ey};function kat(t){return t.key==="Backspace"}function Mat(t){return ao(t,"a",Qv)}function GZt(t){let e=md();if(dn(t)){let n=t.anchor,r=t.focus,o=n.getNode().getTopLevelElementOrThrow().getParentOrThrow();return n.set(o.getKey(),0,"element"),r.set(o.getKey(),o.getChildrenSize(),"element"),v7(t),t}{let n=e.select(0,e.getChildrenSize());return hd(v7(n)),n}}function UL(t,e){t.__lexicalClassNameCache===void 0&&(t.__lexicalClassNameCache={});let n=t.__lexicalClassNameCache,r=n[e];if(r!==void 0)return r;let o=t[e];if(typeof o=="string"){let i=y7(o);return n[e]=i,i}return o}function oTe(t,e,n,r,o){if(n.size===0)return;let i=r.__type,s=r.__key,a=e.get(i);a===void 0&&De(33,i);let l=a.klass,c=t.get(l);c===void 0&&(c=new Map,t.set(l,c));let u=c.get(s),d=u==="destroyed"&&o==="created";(u===void 0||d)&&c.set(s,d?"updated":o)}function YZt(t){let e=t.getType(),n=lx();if(n._readOnly){let i=PSe(n).get(e);return i?Array.from(i.values()):[]}let r=n._nodeMap,o=[];for(let[,i]of r)i instanceof t&&i.__type===e&&i.isAttached()&&o.push(i);return o}function Nat(t,e,n){let r=t.getParent(),o=n,i=t;return r!==null&&(e&&n===0?(o=i.getIndexWithinParent(),i=r):e||n!==i.getChildrenSize()||(o=i.getIndexWithinParent()+1,i=r)),i.getChildAtIndex(e?o-1:o)}function Qlt(t,e){let n=t.offset;if(t.type==="element")return Nat(t.getNode(),e,n);{let r=t.getNode();if(e&&n===0||!e&&n===r.getTextContentSize()){let o=e?r.getPreviousSibling():r.getNextSibling();return o===null?Nat(r.getParentOrThrow(),e,r.getIndexWithinParent()+(e?0:1)):o}}return null}function ect(t){let e=em(t).event,n=e&&e.inputType;return n==="insertFromPaste"||n==="insertFromPasteAsQuotation"}function Et(t,e,n){return function(r,o,i){let s=tTe(r);for(let a=4;a>=0;a--)for(let l=0;l<s.length;l++){let c=s[l],u=c._commands.get(o);if(u!==void 0){let d=u[a];if(d!==void 0){let f=Array.from(d),p=f.length,m=!1;if(wf(c,()=>{for(let h=0;h<p;h++)if(f[h](i,r))return void(m=!0)}),m)return m}}}return!1}(t,e,n)}function W7(t){return!fd(t)&&!t.isLastChild()&&!t.isInline()}function GL(t,e){let n=t._keyToDOMMap.get(e);return n===void 0&&De(75,e),n}function R4(t){let e=t.assignedSlot||t.parentElement;return sct(e)?e.host:e}function iTe(t){return Wlt(t)?t:pu(t)?t.ownerDocument:null}function ZZt(t){return wi()._updateTags.has(t)}function tct(t){Qa(),wi()._updateTags.add(t)}function nct(t){Qa(),wi()._deferred.push(t)}function N7(t,e){let n=t.getParent();for(;n!==null;){if(n.is(e))return!0;n=n.getParent()}return!1}function sTe(t){let e=iTe(t);return e?e.defaultView:null}function em(t){let e=t._window;return e===null&&De(78),e}function JZt(t){return Le(t)&&t.isInline()||Ao(t)&&t.isInline()}function rct(t){let e=t.getParentOrThrow();for(;e!==null;){if(Ah(e))return e;e=e.getParentOrThrow()}return e}function Ah(t){return fd(t)||Le(t)&&t.isShadowRoot()}function aTe(t){let e=t.constructor.clone(t);return Hlt(e,null),e.afterCloneFrom(t),e}function L4(t){let e=wi(),n=t.getType(),r=XSe(e,n);r===void 0&&De(200,t.constructor.name,n);let{replace:o,replaceWithKlass:i}=r;if(o!==null){let s=o(t),a=s.constructor;return i!==null?s instanceof i||De(201,i.name,i.getType(),a.name,a.getType(),t.constructor.name,n):s instanceof t.constructor&&a!==t.constructor||De(202,a.name,a.getType(),t.constructor.name,n),s.__key===t.__key&&De(203,t.constructor.name,n,a.name,a.getType()),s}return t}function eSe(t,e){!fd(t.getParent())||Le(e)||Ao(e)||De(99)}function oct(t){let e=wa(t);return e===null&&De(63,t),e}function tSe(t){return(Ao(t)||Le(t)&&!t.canBeEmpty())&&!t.isInline()}function TSe(t,e,n){n.style.removeProperty("caret-color"),e._blockCursorElement=null;let r=t.parentElement;r!==null&&r.removeChild(t)}function Ay(t){return kh?(t||window).getSelection():null}function ict(t){let e=sTe(t);return e?e.getSelection():null}function XZt(t,e){let n=t.getChildAtIndex(e);n==null&&(n=t),Ah(t)&&De(102);let r=s=>{let a=s.getParentOrThrow(),l=Ah(a),c=s!==n||l?aTe(s):s;if(l)return Le(s)&&Le(c)||De(133),s.insertAfter(c),[s,c,c];{let[u,d,f]=r(a),p=s.getNextSiblings();return f.append(c,...p),[u,d,c]}},[o,i]=r(n);return[o,i]}function QZt(t){return pu(t)&&t.tagName==="A"}function pu(t){return t1(t)&&t.nodeType===EYt}function t1(t){return typeof t=="object"&&t!==null&&"nodeType"in t&&typeof t.nodeType=="number"}function sct(t){return t1(t)&&t.nodeType===MYt}function act(t){let e=new RegExp(/^(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");return t.nodeName.match(e)!==null}function ISe(t){let e=new RegExp(/^(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");return t.nodeName.match(e)!==null}function rx(t){if(Ao(t)&&!t.isInline())return!0;if(!Le(t)||Ah(t))return!1;let e=t.getFirstChild(),n=e===null||eE(e)||Bt(e)||e.isInline();return!t.isInline()&&t.canBeEmpty()!==!1&&n}function nSe(t,e){let n=t;for(;n!==null&&n.getParent()!==null&&!e(n);)n=n.getParentOrThrow();return e(n)?n:null}function lTe(){return wi()}var Oat=new WeakMap,e7t=new Map;function PSe(t){if(!t._readOnly&&t.isEmpty())return e7t;t._readOnly||De(192);let e=Oat.get(t);return e||(e=function(n){let r=new Map;for(let[o,i]of n._nodeMap){let s=i.__type,a=r.get(s);a||(a=new Map,r.set(s,a)),a.set(o,i)}return r}(t),Oat.set(t,e)),e}function lct(t){let e=t.constructor.clone(t);return e.afterCloneFrom(t),e}function cct(t,e){let n=parseInt(t.style.paddingInlineStart,10)||0,r=Math.round(n/40);e.setIndent(r)}function t7t(t){t.__lexicalUnmanaged=!0}function uct(t){return t.__lexicalUnmanaged===!0}function p4(t,e){return function(n,r){return Object.prototype.hasOwnProperty.call(n,r)}(t,e)&&t[e]!==Z_[e]}function cTe(t){let e=qst in t.prototype?t.prototype[qst]():void 0,n=function(s){return s===k4||s===J_||s===Z_}(t),r=!n&&p4(t,"getType")?t.getType():void 0,o,i=r;if(e)if(r)o=e[r];else for(let[s,a]of Object.entries(e))i=s,o=a;if(!n&&i&&(p4(t,"getType")||(t.getType=()=>i),p4(t,"clone")||(t.clone=s=>(ZSe(s),new t)),p4(t,"importJSON")||(t.importJSON=o&&o.$importJSON||(s=>new t().updateFromJSON(s))),!p4(t,"importDOM")&&o)){let{importDOM:s}=o;s&&(t.importDOM=()=>s)}return{ownNodeConfig:o,ownNodeType:i}}function n7t(t){let e=lTe();return Qa(),new(e.resolveRegisteredNodeAfterReplacements(e.getRegisteredNode(t))).klass}var r7t={next:"previous",previous:"next"},YL=class{constructor(e){this.origin=e}[Symbol.iterator](){return fTe({hasNext:aE,initial:this.getAdjacentCaret(),map:e=>e,step:e=>e.getAdjacentCaret()})}getAdjacentCaret(){return rl(this.getNodeAtCaret(),this.direction)}getSiblingCaret(){return rl(this.origin,this.direction)}remove(){let e=this.getNodeAtCaret();return e&&e.remove(),this}replaceOrInsert(e,n){let r=this.getNodeAtCaret();return e.is(this.origin)||e.is(r)||(r===null?this.insert(e):r.replace(e,n)),this}splice(e,n,r="next"){let o=r===this.direction?n:Array.from(n).reverse(),i=this,s=this.getParentAtCaret(),a=new Map;for(let l=i.getAdjacentCaret();l!==null&&a.size<e;l=l.getAdjacentCaret()){let c=l.origin.getWritable();a.set(c.getKey(),c)}for(let l of o){if(a.size>0){let c=i.getNodeAtCaret();if(c){if(a.delete(c.getKey()),a.delete(l.getKey()),!(c.is(l)||i.origin.is(l))){let u=l.getParent();u&&u.is(s)&&l.remove(),c.replace(l)}}else c===null&&De(263,Array.from(a).join(" "))}else i.insert(l);i=rl(l,this.direction)}for(let l of a.values())l.remove();return this}},M4=class t extends YL{constructor(){super(...arguments);I(this,"type","child")}getLatest(){let n=this.origin.getLatest();return n===this.origin?this:ax(n,this.direction)}getParentCaret(n="root"){return rl(uTe(this.getParentAtCaret(),n),this.direction)}getFlipped(){let n=nS(this.direction);return rl(this.getNodeAtCaret(),n)||ax(this.origin,n)}getParentAtCaret(){return this.origin}getChildCaret(){return this}isSameNodeCaret(n){return n instanceof t&&this.direction===n.direction&&this.origin.is(n.origin)}isSamePointCaret(n){return this.isSameNodeCaret(n)}},o7t={root:fd,shadowRoot:Ah};function nS(t){return r7t[t]}function uTe(t,e="root"){return o7t[e](t)?null:t}var ZL=class t extends YL{constructor(){super(...arguments);I(this,"type","sibling")}getLatest(){let n=this.origin.getLatest();return n===this.origin?this:rl(n,this.direction)}getSiblingCaret(){return this}getParentAtCaret(){return this.origin.getParent()}getChildCaret(){return Le(this.origin)?ax(this.origin,this.direction):null}getParentCaret(n="root"){return rl(uTe(this.getParentAtCaret(),n),this.direction)}getFlipped(){let n=nS(this.direction);return rl(this.getNodeAtCaret(),n)||ax(this.origin.getParentOrThrow(),n)}isSamePointCaret(n){return n instanceof t&&this.direction===n.direction&&this.origin.is(n.origin)}isSameNodeCaret(n){return(n instanceof t||n instanceof JL)&&this.direction===n.direction&&this.origin.is(n.origin)}},JL=class t extends YL{constructor(n,r){super(n);I(this,"type","text");this.offset=r}getLatest(){let n=this.origin.getLatest();return n===this.origin?this:X_(n,this.direction,this.offset)}getParentAtCaret(){return this.origin.getParent()}getChildCaret(){return null}getParentCaret(n="root"){return rl(uTe(this.getParentAtCaret(),n),this.direction)}getFlipped(){return X_(this.origin,nS(this.direction),this.offset)}isSamePointCaret(n){return n instanceof t&&this.direction===n.direction&&this.origin.is(n.origin)&&this.offset===n.offset}isSameNodeCaret(n){return(n instanceof ZL||n instanceof t)&&this.direction===n.direction&&this.origin.is(n.origin)}getSiblingCaret(){return rl(this.origin,this.direction)}};function ix(t){return t instanceof JL}function i7t(t){return t instanceof YL}function aE(t){return t instanceof ZL}function Ih(t){return t instanceof M4}var s7t={next:class extends JL{constructor(){super(...arguments);I(this,"direction","next")}getNodeAtCaret(){return this.origin.getNextSibling()}insert(e){return this.origin.insertAfter(e),this}},previous:class extends JL{constructor(){super(...arguments);I(this,"direction","previous")}getNodeAtCaret(){return this.origin.getPreviousSibling()}insert(e){return this.origin.insertBefore(e),this}}},a7t={next:class extends ZL{constructor(){super(...arguments);I(this,"direction","next")}getNodeAtCaret(){return this.origin.getNextSibling()}insert(e){return this.origin.insertAfter(e),this}},previous:class extends ZL{constructor(){super(...arguments);I(this,"direction","previous")}getNodeAtCaret(){return this.origin.getPreviousSibling()}insert(e){return this.origin.insertBefore(e),this}}},l7t={next:class extends M4{constructor(){super(...arguments);I(this,"direction","next")}getNodeAtCaret(){return this.origin.getFirstChild()}insert(e){return this.origin.splice(0,0,[e]),this}},previous:class extends M4{constructor(){super(...arguments);I(this,"direction","previous")}getNodeAtCaret(){return this.origin.getLastChild()}insert(e){return this.origin.splice(this.origin.getChildrenSize(),0,[e]),this}}};function rl(t,e){return t?new a7t[e](t):null}function X_(t,e,n){return t?new s7t[e](t,Ph(t,n)):null}function Ph(t,e,n="error"){let r=t.getTextContentSize(),o=e==="next"?r:e==="previous"?0:e;return(o<0||o>r)&&(n!=="clamp"&&function(i,...s){let a=new URL("https://lexical.dev/docs/error"),l=new URLSearchParams;l.append("code",i);for(let c of s)l.append("v",c);a.search=l.toString(),console.warn(`Minified Lexical warning #${i}; visit ${a.toString()} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}(284,String(e),String(r),t.getKey()),o=o<0?0:r),o}function ESe(t,e){return new O7(t,e)}function ax(t,e){return Le(t)?new l7t[e](t):null}function dct(t){return t&&t.getChildCaret()||t}function XL(t){return t&&dct(t.getAdjacentCaret())}var ASe=class t{constructor(e,n,r){I(this,"type","node-caret-range");this.anchor=e,this.focus=n,this.direction=r}getLatest(){let e=this.anchor.getLatest(),n=this.focus.getLatest();return e===this.anchor&&n===this.focus?this:new t(e,n,this.direction)}isCollapsed(){return this.anchor.isSamePointCaret(this.focus)}getTextSlices(){let e=o=>{let i=this[o].getLatest();return ix(i)?function(s,a){let{direction:l,origin:c}=s,u=Ph(c,a==="focus"?nS(l):l);return ESe(s,u-s.offset)}(i,o):null},n=e("anchor"),r=e("focus");if(n&&r){let{caret:o}=n,{caret:i}=r;if(o.isSameNodeCaret(i))return[ESe(o,i.offset-o.offset),null]}return[n,r]}iterNodeCarets(e="root"){let n=ix(this.anchor)?this.anchor.getSiblingCaret():this.anchor.getLatest(),r=this.focus.getLatest(),o=ix(r),i=s=>s.isSameNodeCaret(r)?null:XL(s)||s.getParentCaret(e);return fTe({hasNext:s=>s!==null&&!(o&&r.isSameNodeCaret(s)),initial:n.isSameNodeCaret(r)?null:i(n),map:s=>s,step:i})}[Symbol.iterator](){return this.iterNodeCarets("root")}},O7=class{constructor(e,n){I(this,"type","slice");this.caret=e,this.distance=n}getSliceIndices(){let{distance:e,caret:{offset:n}}=this,r=n+e;return r<n?[r,n]:[n,r]}getTextContent(){let[e,n]=this.getSliceIndices();return this.caret.origin.getTextContent().slice(e,n)}getTextContentSize(){return Math.abs(this.distance)}removeTextSlice(){let{caret:{origin:e,direction:n}}=this,[r,o]=this.getSliceIndices(),i=e.getTextContent();return X_(e.setTextContent(i.slice(0,r)+i.slice(o)),n,r)}};function c7t(t){return t instanceof O7}function dTe(t){return Q_(t,rl(md(),t.direction))}function fct(t){return Q_(t,t)}function Q_(t,e){return t.direction!==e.direction&&De(265),new ASe(t,e,t.direction)}function fTe(t){let{initial:e,hasNext:n,step:r,map:o}=t,i=e;return{[Symbol.iterator](){return this},next(){if(!n(i))return{done:!0,value:void 0};let s={done:!1,value:o(i)};return i=r(i),s}}}function pTe(t,e){let n=v4(t.origin,e.origin);switch(n===null&&De(275,t.origin.getKey(),e.origin.getKey()),n.type){case"same":{let r=t.type==="text",o=e.type==="text";return r&&o?function(i,s){return Math.sign(i-s)}(t.offset,e.offset):t.type===e.type?0:r?-1:o?1:t.type==="child"?-1:1}case"ancestor":return t.type==="child"?-1:1;case"descendant":return e.type==="child"?1:-1;case"branch":return mTe(n)}}function mTe(t){let{a:e,b:n}=t,r=e.__key,o=n.__key,i=e,s=n;for(;i&&s;i=i.getNextSibling(),s=s.getNextSibling()){if(i.__key===o)return-1;if(s.__key===r)return 1}return i===null?1:-1}function u7(t,e){return e.is(t)}function Rat(t){return Le(t)?[t.getLatest(),null]:[t.getParent(),t.getLatest()]}function v4(t,e){if(t.is(e))return{commonAncestor:t,type:"same"};let n=new Map;for(let[r,o]=Rat(t);r;o=r,r=r.getParent())n.set(r,o);for(let[r,o]=Rat(e);r;o=r,r=r.getParent()){let i=n.get(r);if(i!==void 0)return i===null?(u7(t,r)||De(276),{commonAncestor:r,type:"ancestor"}):o===null?(u7(e,r)||De(277),{commonAncestor:r,type:"descendant"}):((Le(i)||u7(t,i))&&(Le(o)||u7(e,o))&&r.is(i.getParent())&&r.is(o.getParent())||De(278),{a:i,b:o,commonAncestor:r,type:"branch"})}return null}function eS(t,e){let{type:n,key:r,offset:o}=t,i=oct(t.key);return n==="text"?(Bt(i)||De(266,i.getType(),r),X_(i,e,o)):(Le(i)||De(267,i.getType(),r),gct(i,t.offset,e))}function QL(t,e){let{origin:n,direction:r}=e,o=r==="next";ix(e)?t.set(n.getKey(),e.offset,"text"):aE(e)?Bt(n)?t.set(n.getKey(),Ph(n,r),"text"):t.set(n.getParentOrThrow().getKey(),n.getIndexWithinParent()+(o?1:0),"element"):(Ih(e)&&Le(n)||De(268),t.set(n.getKey(),o?0:n.getChildrenSize(),"element"))}function pct(t){let e=Gr(),n=dn(e)?e:Nlt();return x4(n,t),hd(n),n}function x4(t,e){QL(t.anchor,e.anchor),QL(t.focus,e.focus)}function kSe(t){let{anchor:e,focus:n}=t,r=eS(e,"next"),o=eS(n,"next"),i=pTe(r,o)<=0?"next":"previous";return Q_(tS(r,i),tS(o,i))}function n1(t){let{direction:e,origin:n}=t,r=rl(n,nS(e)).getNodeAtCaret();return r?rl(r,e):ax(n.getParentOrThrow(),e)}function Lat(t,e="root"){let n=[t];for(let r=Ih(t)?t.getParentCaret(e):t.getSiblingCaret();r!==null;r=r.getParentCaret(e))n.push(n1(r));return n}function rSe(t){return!!t&&t.origin.isAttached()}function mct(t,e="removeEmptySlices"){if(t.isCollapsed())return t;let n="root",r="next",o=e,i=hTe(t,r),s=Lat(i.anchor,n),a=Lat(i.focus.getFlipped(),n),l=new Set,c=[];for(let m of i.iterNodeCarets(n))if(Ih(m))l.add(m.origin.getKey());else if(aE(m)){let{origin:h}=m;Le(h)&&!l.has(h.getKey())||c.push(h)}for(let m of c)m.remove();for(let m of i.getTextSlices()){if(!m)continue;let{origin:h}=m.caret,g=h.getTextContentSize(),y=n1(rl(h,r)),w=h.getMode();if(Math.abs(m.distance)===g&&o==="removeEmptySlices"||w==="token"&&m.distance!==0)y.remove();else if(m.distance!==0){o="removeEmptySlices";let v=m.removeTextSlice(),x=m.caret.origin;if(w==="segmented"){let b=v.origin,_=Xa(b.getTextContent()).setStyle(b.getStyle()).setFormat(b.getFormat());y.replaceOrInsert(_),v=X_(_,r,v.offset)}x.is(s[0].origin)&&(s[0]=v),x.is(a[0].origin)&&(a[0]=v.getFlipped())}}let u,d;for(let m of s)if(rSe(m)){u=Sh(m);break}for(let m of a)if(rSe(m)){d=Sh(m);break}let f=function(m,h,g){if(!m||!h)return null;let y=m.getParentAtCaret(),w=h.getParentAtCaret();if(!y||!w)return null;let v=y.getParents().reverse();v.push(y);let x=w.getParents().reverse();x.push(w);let b=Math.min(v.length,x.length),_;for(_=0;_<b&&v[_]===x[_];_++);let T=(A,O)=>{let D;for(let $=_;$<A.length;$++){let B=A[$];if(Ah(B))return;!D&&O(B)&&(D=B)}return D},S=T(v,rx),P=S&&T(x,A=>g.has(A.getKey())&&rx(A));return S&&P?[S,P]:null}(u,d,l);if(f){let[m,h]=f;ax(m,"previous").splice(0,h.getChildren()),h.remove()}let p=[u,d,...s,...a].find(rSe);if(p)return fct(tS(Sh(p),t.direction));De(269,JSON.stringify(s.map(m=>m.origin.__key)))}function Sh(t){let e=function(o){let i=o;for(;Ih(i);){let s=XL(i);if(!Ih(s))break;i=s}return i}(t.getLatest()),{direction:n}=e;if(Bt(e.origin))return ix(e)?e:X_(e.origin,n,n);let r=e.getAdjacentCaret();return aE(r)&&Bt(r.origin)?X_(r.origin,n,nS(n)):e}function hct(t){return ix(t)&&t.offset!==Ph(t.origin,t.direction)}function tS(t,e){return t.direction===e?t:t.getFlipped()}function hTe(t,e){return t.direction===e?t:Q_(tS(t.focus,e),tS(t.anchor,e))}function gct(t,e,n){let r=ax(t,"next");for(let o=0;o<e;o++){let i=r.getAdjacentCaret();if(i===null)break;r=i}return tS(r,n)}function u7t(t,e="root"){let n=0,r=t,o=XL(r);for(;o===null;){if(n--,o=r.getParentCaret(e),!o)return null;r=o,o=XL(r)}return o&&[o,n]}function d7t(t){let{origin:e,offset:n,direction:r}=t;if(n===Ph(e,r))return t.getSiblingCaret();if(n===Ph(e,nS(r)))return n1(t.getSiblingCaret());let[o]=e.splitText(n);return Bt(o)||De(281),tS(rl(o,"next"),r)}function f7t(t,e){return!0}function p7t(t,{$copyElementNode:e=aTe,$splitTextPointCaretNext:n=d7t,rootMode:r="shadowRoot",$shouldSplit:o=f7t}={}){if(ix(t))return n(t);let i=t.getParentCaret(r);if(i){let{origin:s}=i;if(Ih(t)&&(!s.canBeEmpty()||!o(s,"first")))return n1(i);let a=function(l){let c=[];for(let u=l.getAdjacentCaret();u;u=u.getAdjacentCaret())c.push(u.origin);return c}(t);(a.length>0||s.canBeEmpty()&&o(s,"last"))&&i.insert(e(s).splice(0,0,a))}return i}var ne=gTe,UDr=ne.$addUpdateTag,BDr=ne.$applyNodeReplacement,r1=ne.$caretFromPoint,yct=ne.$caretRangeFromSelection,rS=ne.$cloneWithProperties,zDr=ne.$comparePointCaretNext,jDr=ne.$copyNode,VDr=ne.$create,yTe=ne.$createLineBreakNode,WDr=ne.$createNodeSelection,cx=ne.$createParagraphNode,HDr=ne.$createPoint,H7=ne.$createRangeSelection,KDr=ne.$createRangeSelectionFromDom,wct=ne.$createTabNode,vf=ne.$createTextNode,vct=ne.$extendCaretToRange,D4=ne.$getAdjacentChildCaret,qDr=ne.$getAdjacentNode,GDr=ne.$getAdjacentSiblingOrParentSiblingCaret,wTe=ne.$getCaretInDirection,xct=ne.$getCaretRange,YDr=ne.$getCaretRangeInDirection,bct=ne.$getCharacterOffsets,oS=ne.$getChildCaret,ZDr=ne.$getChildCaretAtIndex,vTe=ne.$getChildCaretOrSelf,Cct=ne.$getCollapsedCaretRange,JDr=ne.$getCommonAncestor,XDr=ne.$getCommonAncestorResultBranchOrder,K7=ne.$getEditor,QDr=ne.$getNearestNodeFromDOMNode,e$r=ne.$getNearestRootOrShadowRoot,_ct=ne.$getNodeByKey,t$r=ne.$getNodeByKeyOrThrow,$4=ne.$getPreviousSelection,mr=ne.$getRoot,gn=ne.$getSelection,ux=ne.$getSiblingCaret,Sct=ne.$getState,n$r=ne.$getStateChange,r$r=ne.$getTextContent,o$r=ne.$getTextNodeOffset,i$r=ne.$getTextPointCaret,s$r=ne.$getTextPointCaretSlice,a$r=ne.$getWritableNodeState,Tct=ne.$hasAncestor,l$r=ne.$hasUpdateTag,c$r=ne.$insertNodes,q7=ne.$isBlockElementNode,F4=ne.$isChildCaret,G7=ne.$isDecoratorNode,lr=ne.$isElementNode,Ict=ne.$isExtendableTextPointCaret,u$r=ne.$isInlineElementOrDecoratorNode,Pct=ne.$isLeafNode,d$r=ne.$isLineBreakNode,f$r=ne.$isNodeCaret,p$r=ne.$isNodeSelection,Ect=ne.$isParagraphNode,jt=ne.$isRangeSelection,o1=ne.$isRootNode,cE=ne.$isRootOrShadowRoot,Act=ne.$isSiblingCaret,m$r=ne.$isTabNode,Mr=ne.$isTextNode,Y7=ne.$isTextPointCaret,h$r=ne.$isTextPointCaretSlice,xTe=ne.$isTokenOrSegmented,g$r=ne.$isTokenOrTab,y$r=ne.$nodesOfType,kct=ne.$normalizeCaret,w$r=ne.$normalizeSelection__EXPERIMENTAL,v$r=ne.$onUpdate,Mct=ne.$parseSerializedNode,x$r=ne.$removeTextFromCaretRange,Nct=ne.$rewindSiblingCaret,Z7=ne.$selectAll,b$r=ne.$setCompositionKey,C$r=ne.$setPointFromCaret,uE=ne.$setSelection,Oct=ne.$setSelectionFromCaretRange,Rct=ne.$setState,Lct=ne.$splitAtPointCaretNext,Dct=ne.$splitNode,_$r=ne.$updateRangeSelectionFromCaretRange,bTe=ne.ArtificialNode__DO_NOT_USE,$ct=ne.BLUR_COMMAND,U4=ne.CAN_REDO_COMMAND,B4=ne.CAN_UNDO_COMMAND,Fct=ne.CLEAR_EDITOR_COMMAND,Uct=ne.CLEAR_HISTORY_COMMAND,S$r=ne.CLICK_COMMAND,T$r=ne.COLLABORATION_TAG,J7=ne.COMMAND_PRIORITY_CRITICAL,zo=ne.COMMAND_PRIORITY_EDITOR,dx=ne.COMMAND_PRIORITY_HIGH,Bct=ne.COMMAND_PRIORITY_LOW,I$r=ne.COMMAND_PRIORITY_NORMAL,zct=ne.CONTROLLED_TEXT_INSERTION_COMMAND,X7=ne.COPY_COMMAND,jct=ne.CUT_COMMAND,i1=ne.DELETE_CHARACTER_COMMAND,Vct=ne.DELETE_LINE_COMMAND,Wct=ne.DELETE_WORD_COMMAND,P$r=ne.DRAGEND_COMMAND,E$r=ne.DRAGOVER_COMMAND,Hct=ne.DRAGSTART_COMMAND,Kct=ne.DROP_COMMAND,Q7=ne.DecoratorNode,A$r=ne.ElementNode,k$r=ne.FOCUS_COMMAND,M$r=ne.FORMAT_ELEMENT_COMMAND,N$r=ne.FORMAT_TEXT_COMMAND,eJ=ne.HISTORIC_TAG,s1=ne.HISTORY_MERGE_TAG,qct=ne.HISTORY_PUSH_TAG,O$r=ne.INDENT_CONTENT_COMMAND,CTe=ne.INSERT_LINE_BREAK_COMMAND,Gct=ne.INSERT_PARAGRAPH_COMMAND,R$r=ne.INSERT_TAB_COMMAND,z4=ne.INTERNAL_$isBlock,L$r=ne.IS_ALL_FORMATTING,D$r=ne.IS_BOLD,$$r=ne.IS_CODE,F$r=ne.IS_HIGHLIGHT,U$r=ne.IS_ITALIC,B$r=ne.IS_STRIKETHROUGH,z$r=ne.IS_SUBSCRIPT,j$r=ne.IS_SUPERSCRIPT,V$r=ne.IS_UNDERLINE,Yct=ne.KEY_ARROW_DOWN_COMMAND,Zct=ne.KEY_ARROW_LEFT_COMMAND,Jct=ne.KEY_ARROW_RIGHT_COMMAND,Xct=ne.KEY_ARROW_UP_COMMAND,Qct=ne.KEY_BACKSPACE_COMMAND,eut=ne.KEY_DELETE_COMMAND,W$r=ne.KEY_DOWN_COMMAND,a1=ne.KEY_ENTER_COMMAND,tut=ne.KEY_ESCAPE_COMMAND,H$r=ne.KEY_MODIFIER_COMMAND,K$r=ne.KEY_SPACE_COMMAND,nut=ne.KEY_TAB_COMMAND,q$r=ne.LineBreakNode,G$r=ne.MOVE_TO_END,Y$r=ne.MOVE_TO_START,Z$r=ne.NODE_STATE_KEY,J$r=ne.OUTDENT_CONTENT_COMMAND,tJ=ne.PASTE_COMMAND,rut=ne.PASTE_TAG,X$r=ne.ParagraphNode,out=ne.REDO_COMMAND,iut=ne.REMOVE_TEXT_COMMAND,Q$r=ne.RootNode,eFr=ne.SELECTION_CHANGE_COMMAND,sut=ne.SELECTION_INSERT_CLIPBOARD_NODES_COMMAND,aut=ne.SELECT_ALL_COMMAND,tFr=ne.SKIP_COLLAB_TAG,nFr=ne.SKIP_DOM_SELECTION_TAG,rFr=ne.SKIP_SCROLL_INTO_VIEW_TAG,oFr=ne.TEXT_TYPE_TO_FORMAT,iFr=ne.TabNode,My=ne.TextNode,lut=ne.UNDO_COMMAND,sFr=ne.buildImportMap,cut=ne.createCommand,uut=ne.createEditor,aFr=ne.createSharedNodeState,lFr=ne.createState,cFr=ne.flipDirection,uFr=ne.getDOMOwnerDocument,_Te=ne.getDOMSelection,dFr=ne.getDOMSelectionFromTarget,dut=ne.getDOMTextNode,fFr=ne.getEditorPropertyFromDOMNode,pFr=ne.getNearestEditorFromDOMNode,fut=ne.getRegisteredNode,mFr=ne.getRegisteredNodeOrThrow,put=ne.isBlockDomNode,hFr=ne.isCurrentlyReadOnlyMode,gFr=ne.isDOMDocumentNode,yFr=ne.isDOMNode,wFr=ne.isDOMTextNode,vFr=ne.isDOMUnmanaged,STe=ne.isDocumentFragment,xFr=ne.isExactShortcutMatch,mut=ne.isHTMLAnchorElement,nJ=ne.isHTMLElement,j4=ne.isInlineDomNode,bFr=ne.isLexicalEditor,CFr=ne.isModifierMatch,_Fr=ne.isSelectionCapturedInDecoratorInput,hut=ne.isSelectionWithinEditor,TTe=ne.makeStepwiseIterator,SFr=ne.removeFromParent,TFr=ne.resetRandomKey,IFr=ne.setDOMUnmanaged,PFr=ne.setNodeIndentFromDOM;var Mut=N(U());vt();var Aut=require("obsidian"),fn=N(U());rn();var rJ=N(U());JW();Kt();var m7t=$A("tw-inline-flex tw-items-center tw-rounded-md tw-px-2.5 tw-py-0.5 tw-text-ui-smaller tw-text-normal tw-transition-colors focus:tw-outline-none",{variants:{variant:{default:"tw-bg-primary-alt tw-shadow",secondary:"tw-bg-secondary-alt",destructive:"tw-bg-modifier-error tw-shadow",outline:"tw-border tw-border-solid tw-border-border"}},defaultVariants:{variant:"default"}}),ro=rJ.forwardRef(({className:t,variant:e,...n},r)=>rJ.createElement("div",{ref:r,className:oe(m7t({variant:e}),t),...n}));ro.displayName="Badge";var On=N(U());vt();var l1=N(U());Kt();var oJ=N(U()),h7t=2;function g7t(t,e){return e&&e>1?t.current?t.current.offsetHeight<t.current.scrollHeight:!1:(t.current&&t.current?.offsetWidth+h7t<t.current?.scrollWidth)??!1}function y7t(t){switch(t){case 2:return"tw-line-clamp-2";case 3:return"tw-line-clamp-3";default:return""}}var go=({children:t,className:e,lineClamp:n,tooltipContent:r,alwaysShowTooltip:o=!1,...i})=>{let s=(0,oJ.useRef)(null),[a,l]=(0,oJ.useState)(!1);return l1.default.createElement(uu,{delayDuration:0},l1.default.createElement(cn,{open:a,onOpenChange:u=>{l(u&&(o||g7t(s,n)))}},l1.default.createElement(un,{asChild:!0},l1.default.createElement("div",{...i,ref:s,className:oe("tw-max-w-full tw-text-normal",(!n||n<=1)&&"tw-truncate",n&&y7t(n),e),"data-testid":"truncatedText"},t)),l1.default.createElement(on,{className:"tw-max-w-64 tw-text-wrap tw-break-words"},r??t)))};qe();Kt();var c1=N(U());vt();Kt();function Ny({children:t,icon:e,onRemove:n,className:r,isClickable:o=!1,...i}){return c1.default.createElement(ro,{variant:"default",tabIndex:n?0:void 0,className:oe("tw-group/badge tw-items-center tw-gap-1 tw-border tw-border-solid tw-border-border tw-py-1 tw-pl-1.5 tw-pr-2 tw-text-xs",o&&"tw-cursor-pointer hover:tw-bg-interactive-hover",r),onKeyDown:n?s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),s.stopPropagation(),n())}:void 0,...i},c1.default.createElement("span",{className:"tw-relative tw-size-4 tw-shrink-0"},c1.default.createElement("span",{className:oe("tw-flex tw-size-full tw-items-center tw-justify-center",n&&"context-badge-icon-removable group-focus-within/badge:tw-invisible group-hover/badge:tw-invisible")},e),n&&c1.default.createElement("div",{"aria-hidden":"true",className:"context-badge-close tw-invisible tw-absolute tw-inset-0 tw-flex tw-items-center tw-justify-center tw-text-muted group-focus-within/badge:tw-visible group-hover/badge:tw-visible",onClick:s=>{s.stopPropagation(),n()}},c1.default.createElement(Sn,{className:"tw-size-3"}))),t)}function iJ(t){return t.sourceType==="web"}function w7t({faviconUrl:t,className:e}){let[n,r]=On.default.useState(!1);return n?On.default.createElement(Br,{className:e}):On.default.createElement("img",{src:t,alt:"",referrerPolicy:"no-referrer",loading:"lazy",decoding:"async",className:oe(e,"tw-rounded-sm"),onError:()=>r(!0)})}function V4({faviconUrl:t,isLoaded:e=!0,className:n="tw-size-3"}){return e?t?On.default.createElement(w7t,{key:t,faviconUrl:t,className:n}):On.default.createElement(Br,{className:n}):On.default.createElement(nw,{className:oe(n,"tw-text-muted")})}function gut({currentActiveFile:t,onRemove:e,onClick:n}){if(!t)return null;let r=On.default.createElement("div",{className:"tw-text-left"},t.path),o=t.extension==="pdf",i=t.extension==="canvas";return On.default.createElement(Ny,{icon:On.default.createElement(Ur,{className:"tw-size-3"}),onRemove:e,isClickable:!!n,onClick:n},On.default.createElement(go,{className:"tw-max-w-40",tooltipContent:r,alwaysShowTooltip:!0},t.basename),On.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Current"),o&&On.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"pdf"),i&&On.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"canvas"))}function yut({activeWebTab:t,onRemove:e,onClick:n}){if(!t)return null;let r=Xy(t.url),o=t.title||r||t.url||"Untitled",i=On.default.createElement("div",{className:"tw-text-left"},t.url);return On.default.createElement(Ny,{icon:On.default.createElement(V4,{faviconUrl:t.faviconUrl}),onRemove:e,isClickable:!!n,onClick:n},On.default.createElement(go,{className:"tw-max-w-40",tooltipContent:i,alwaysShowTooltip:!0},o),On.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Current"))}function sJ({note:t,onRemove:e,onClick:n}){let r=On.default.createElement("div",{className:"tw-text-left"},t.path),o=t.extension==="pdf",i=t.extension==="canvas";return On.default.createElement(Ny,{icon:On.default.createElement(Ur,{className:"tw-size-3"}),onRemove:e,isClickable:!!n,onClick:n},On.default.createElement(go,{className:"tw-max-w-40",tooltipContent:r,alwaysShowTooltip:!0},t.basename),o&&On.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"pdf"),i&&On.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"canvas"))}function aJ({url:t,onRemove:e}){return On.default.createElement(Ny,{icon:On.default.createElement(rw,{className:"tw-size-3"}),onRemove:e},On.default.createElement(go,{className:"tw-max-w-40",tooltipContent:t},Xy(t)))}function lJ({webTab:t,onRemove:e,onClick:n}){let r=t.isLoaded!==!1,o=Xy(t.url),i=t.title||o||t.url||"Untitled",s=r?t.url:"Tab not loaded - switch to this tab to load content";return On.default.createElement(Ny,{icon:On.default.createElement(V4,{faviconUrl:t.faviconUrl,isLoaded:r}),onRemove:e,isClickable:!!n,onClick:n,className:oe(!r&&"tw-opacity-60")},On.default.createElement(go,{className:oe("tw-max-w-40",!r&&"tw-italic"),tooltipContent:s},i),!r&&On.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"(not loaded)"))}function wut({tag:t,onRemove:e}){let n=t.startsWith("#")?t.slice(1):t;return On.default.createElement(Ny,{icon:On.default.createElement(cg,{className:"tw-size-3"}),onRemove:e},On.default.createElement(go,{className:"tw-max-w-40",tooltipContent:t},n))}function cJ({folder:t,onRemove:e}){return On.default.createElement(Ny,{icon:On.default.createElement(es,{className:"tw-size-3"}),onRemove:e},On.default.createElement(go,{className:"tw-max-w-40",tooltipContent:t,alwaysShowTooltip:!0},t))}function vut({selectedText:t,onRemove:e}){if(iJ(t)){let o=Xy(t.url),i=On.default.createElement("div",{className:"tw-text-left"},t.url);return On.default.createElement(Ny,{icon:On.default.createElement(V4,{faviconUrl:t.faviconUrl}),onRemove:e},On.default.createElement(go,{className:"tw-max-w-40",tooltipContent:i,alwaysShowTooltip:!0},t.title||o),On.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Selection"))}let n=t.startLine===t.endLine?`L${t.startLine}`:`L${t.startLine}-${t.endLine}`,r=On.default.createElement("div",{className:"tw-text-left"},t.notePath," (",n,")");return On.default.createElement(Ny,{icon:On.default.createElement(Ur,{className:"tw-size-3"}),onRemove:e},On.default.createElement(go,{className:"tw-max-w-40",tooltipContent:r,alwaysShowTooltip:!0},t.noteTitle),On.default.createElement("span",{className:"tw-text-xs tw-text-faint"},n))}Qi();Ir();qe();fL();var xf=N(U());var xut=N(U());var bo=N(U());vt();Kt();var v7t=120,x7t=240;function uJ({options:t,selectedIndex:e,onSelect:n,onHighlight:r,query:o="",mode:i="search",showPreview:s=!1,searchBarMode:a=!1,searchQuery:l="",onSearchChange:c,onKeyDown:u,className:d,width:f}){let p=(0,bo.useRef)(null),m=(0,bo.useRef)(null),[h,g]=bo.default.useState(null),[y,w]=bo.default.useState(e);e!==y&&(w(e),g(null)),(0,bo.useEffect)(()=>{p.current&&p.current.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[e]);let v=_=>{let T=_.target.value;c?.(T)},x=_=>{(_.key==="ArrowDown"||_.key==="ArrowUp"||_.key==="Enter"||_.key==="Tab"||_.key==="Escape")&&(_.preventDefault(),u?.(_))},b=s&&t[e]?.content;return bo.default.createElement("div",{className:oe("tw-flex tw-flex-col",d)},b&&bo.default.createElement("div",{className:"tw-mb-2 tw-overflow-hidden tw-rounded-md tw-bg-primary tw-p-3 tw-text-sm tw-shadow-xl",style:{minHeight:v7t,maxHeight:x7t,...f&&{width:f}}},bo.default.createElement("div",{className:"tw-mb-1 tw-text-xs tw-text-muted"},"Preview"),t[e].subtitle&&bo.default.createElement("div",{className:"tw-mb-2 tw-text-xs tw-text-muted"},t[e].subtitle),bo.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-normal"},t[e].content)),bo.default.createElement("div",{className:"tw-overflow-hidden tw-rounded-lg tw-bg-primary",style:{...f&&{width:f}}},bo.default.createElement("div",{className:"tw-overflow-y-auto",style:{minHeight:Math.min(t.length*44+16,100),maxHeight:240}},bo.default.createElement("div",{className:"tw-p-2 tw-text-normal"},t.map((_,T)=>{let S=T===e,P=T===h,A=_.disabled??!1,O=(S||P)&&!A,D=i==="category"&&!o&&_.icon&&!("data"in _);return bo.default.createElement("div",{key:_.key,ref:S?p:void 0,className:oe("tw-flex tw-items-center tw-rounded-md tw-px-3 tw-py-2 tw-text-sm",A?"tw-cursor-not-allowed tw-text-muted tw-opacity-50":"tw-cursor-pointer tw-text-normal",O&&"tw-bg-modifier-hover"),title:A?_.disabledReason:void 0,onMouseDown:$=>{$.preventDefault(),!A&&n(_)},onMouseEnter:()=>{A||(g(T),r(T))},onMouseLeave:()=>g(null)},D?bo.default.createElement("div",{className:"tw-flex tw-w-full tw-items-center tw-justify-between"},bo.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},_.icon,bo.default.createElement("span",{className:"tw-font-medium"},_.title)),bo.default.createElement(Di,{className:"tw-size-4 tw-text-muted"})):bo.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-center tw-gap-2"},_.icon&&bo.default.createElement("div",{className:"tw-flex tw-h-full tw-shrink-0 tw-items-center"},_.icon),bo.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col tw-gap-0.5"},bo.default.createElement("div",{className:"tw-truncate tw-font-medium tw-text-normal"},_.title),_.subtitle&&bo.default.createElement("div",{className:"tw-truncate tw-text-xs tw-text-muted"},_.subtitle))))}))),a&&bo.default.createElement("div",{className:"tw-border-t tw-border-solid tw-border-border tw-p-0.5"},bo.default.createElement("input",{ref:m,type:"text",value:l,onChange:v,onKeyDown:x,placeholder:"Search...",autoFocus:!0,className:"tw-w-full tw-rounded-md !tw-border-none !tw-bg-transparent tw-px-1 tw-py-0 tw-text-sm tw-text-normal placeholder:tw-text-muted focus:!tw-shadow-none"}))))}function but({options:t,selectedIndex:e,onSelect:n,onHighlight:r,query:o="",mode:i="search",showPreview:s=!1,searchBarMode:a=!1,searchQuery:l="",onSearchChange:c,onKeyDown:u}){return xut.default.createElement(uJ,{options:t,selectedIndex:e,onSelect:n,onHighlight:r,query:o,mode:i,showPreview:s,searchBarMode:a,searchQuery:l,onSearchChange:c,onKeyDown:u})}var dE=N(U()),Cut=require("obsidian");vt();var b7t=[{key:"notes",title:"Notes",subtitle:"Reference notes in your vault",category:"notes",icon:dE.default.createElement(Ur,{className:"tw-size-4"})},{key:"webTabs",title:"Web Tabs",subtitle:"Reference open browser tabs",category:"webTabs",icon:dE.default.createElement(Br,{className:"tw-size-4"})},{key:"tools",title:"Tools",subtitle:"AI tools and commands",category:"tools",icon:dE.default.createElement(Nd,{className:"tw-size-4"})},{key:"folders",title:"Folders",subtitle:"Reference vault folders",category:"folders",icon:dE.default.createElement(es,{className:"tw-size-4"})}];function dJ(t=!1){return(0,dE.useMemo)(()=>b7t.filter(e=>e.category==="tools"?t:e.category==="webTabs"?Cut.Platform.isDesktopApp:!0),[t])}var xc=N(U()),MTe=require("obsidian");vt();var NTe=N(W4());var Sut=N(U());Id();Id();var Mh=require("obsidian");Hx();Se();qe();ye();var pJ=250,ITe=Oo([]),PTe=Oo([]),ETe=Oo([]),ATe=Oo([]),fE=class fE{constructor(){this.initialized=!1;this.handleFileCreate=e=>{e instanceof Mh.TFile?tg(e)&&(this.debouncedRefreshNotes(),this.debouncedRefreshTagsFrontmatter(),this.debouncedRefreshTagsAll()):e instanceof Mh.TFolder&&this.debouncedRefreshFolders()};this.handleFileDelete=e=>{e instanceof Mh.TFile?tg(e)&&(this.debouncedRefreshNotes(),this.debouncedRefreshTagsFrontmatter(),this.debouncedRefreshTagsAll()):e instanceof Mh.TFolder&&this.debouncedRefreshFolders()};this.handleFileRename=(e,n)=>{e instanceof Mh.TFile?tg(e)&&(this.debouncedRefreshNotes(),this.debouncedRefreshTagsFrontmatter(),this.debouncedRefreshTagsAll()):e instanceof Mh.TFolder&&this.debouncedRefreshFolders()};this.handleFileModify=e=>{e instanceof Mh.TFile&&e.extension==="md"&&this.debouncedRefreshTagsAll()};this.handleMetadataChange=e=>{e.extension==="md"&&(this.debouncedRefreshTagsFrontmatter(),this.debouncedRefreshTagsAll())};this.debouncedRefreshNotes=Li(()=>this.refreshNotes(),pJ,{leading:!0,trailing:!0});this.debouncedRefreshFolders=Li(()=>this.refreshFolders(),pJ,{leading:!0,trailing:!0});this.debouncedRefreshTagsFrontmatter=Li(()=>this.refreshTagsFrontmatter(),pJ,{leading:!0,trailing:!0});this.debouncedRefreshTagsAll=Li(()=>this.refreshTagsAll(),pJ,{leading:!0,trailing:!0});this.refreshNotes=()=>{if(!app?.vault)return;let n=app.vault.getFiles().filter(r=>r instanceof Mh.TFile&&tg(r));Kn.set(ITe,n)};this.refreshFolders=()=>{if(!app?.vault)return;let e=app.vault.getAllLoadedFiles().filter(n=>n instanceof Mh.TFolder);Kn.set(PTe,e)};this.refreshTagsFrontmatter=()=>{if(!app?.vault||!app?.metadataCache)return;let e=new Set;app.vault.getMarkdownFiles().forEach(r=>{eg(r,!0).forEach(i=>{let s=i.startsWith("#")?i:`#${i}`;e.add(s)})});let n=Array.from(e).sort();Kn.set(ETe,n)};this.refreshTagsAll=()=>{if(!app?.vault||!app?.metadataCache)return;let e=new Set;app.vault.getMarkdownFiles().forEach(r=>{eg(r,!1).forEach(i=>{let s=i.startsWith("#")?i:`#${i}`;e.add(s)})});let n=Array.from(e).sort();Kn.set(ATe,n)}}static getInstance(){return fE.instance||(fE.instance=new fE),fE.instance}initialize(){if(this.initialized){k("VaultDataManager: Already initialized, skipping");return}if(!app?.vault){k("VaultDataManager: app.vault not available, deferring initialization");return}k("VaultDataManager: Initializing with vault event listeners"),this.refreshNotes(),this.refreshFolders(),this.refreshTagsFrontmatter(),this.refreshTagsAll(),app.vault.on("create",this.handleFileCreate),app.vault.on("delete",this.handleFileDelete),app.vault.on("rename",this.handleFileRename),app.vault.on("modify",this.handleFileModify),app.metadataCache.on("changed",this.handleMetadataChange),this.initialized=!0}cleanup(){this.initialized&&(k("VaultDataManager: Cleaning up event listeners"),this.debouncedRefreshNotes.cancel(),this.debouncedRefreshFolders.cancel(),this.debouncedRefreshTagsFrontmatter.cancel(),this.debouncedRefreshTagsAll.cancel(),app?.vault&&(app.vault.off("create",this.handleFileCreate),app.vault.off("delete",this.handleFileDelete),app.vault.off("rename",this.handleFileRename),app.vault.off("modify",this.handleFileModify)),app?.metadataCache&&app.metadataCache.off("changed",this.handleMetadataChange),this.initialized=!1)}unload(){this.cleanup()}};fE.instance=null;var H4=fE;Se();function mJ(t=!1){let e=Wl(ITe,{store:Kn});return(0,Sut.useMemo)(()=>{let n;return t?n=[...e]:n=e.filter(r=>r.extension==="md"||r.extension==="canvas"),n.sort((r,o)=>o.stat.ctime-r.stat.ctime)},[e,t])}Id();Se();function Tut(){return Wl(PTe,{store:Kn})}var u1=N(U()),Iut=require("obsidian");bi();FP();var C7t=6e3;function _7t(t){try{let e=ls(t),n=e.getLeaves(),r=[];for(let o of n){let i=e.getPageInfo(o),s=o.view,a=!!i.url?.trim(),l=!!i.title?.trim();if(!a&&!l)continue;let c=s.webviewMounted===void 0||s.webviewFirstLoadFinished===void 0?!0:!!(s.webviewMounted&&s.webviewFirstLoadFinished),u=a&&c;r.push({url:i.url||"",title:i.title||void 0,faviconUrl:i.faviconUrl||void 0,isLoaded:u})}return r.sort((o,i)=>{if(o.isLoaded!==i.isLoaded)return o.isLoaded?-1:1;let s=o.url||o.title||"",a=i.url||i.title||"";return s.localeCompare(a)}),r}catch{return[]}}function S7t(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++){let r=t[n],o=e[n];if(r.url!==o.url||r.title!==o.title||r.faviconUrl!==o.faviconUrl||r.isLoaded!==o.isLoaded)return!1}return!0}function Put(t={}){let e=tr(),{enabled:n=!0}=t,[r,o]=(0,u1.useState)([]),i=(0,u1.useRef)(null);return(0,u1.useEffect)(()=>{if(!n){o([]);return}if(!Iut.Platform.isDesktopApp){o([]);return}let s=!1,a=()=>{if(s)return;let m=_7t(e);o(h=>S7t(h,m)?h:m)},l=()=>{s||i.current===null&&(i.current=window.requestAnimationFrame(()=>{i.current=null,a()}))};a();let u=ls(e).subscribeToWebviewLoad(l),d=e.workspace.on("layout-change",l),f=e.workspace.on("active-leaf-change",l),p=window.setInterval(l,C7t);return()=>{s=!0,i.current!==null&&(window.cancelAnimationFrame(i.current),i.current=null),window.clearInterval(p),e.workspace.offref(d),e.workspace.offref(f),u()}},[e,n]),r}var gJ=N(U()),kTe=require("obsidian");bi();FP();var hJ={activeWebTabForMentions:null,activeOrLastWebTab:null};function iS(){let t=tr(),[e,n]=(0,gJ.useState)(()=>{if(!kTe.Platform.isDesktopApp)return hJ;try{return ls(t).getActiveWebTabState()}catch{return hJ}});return(0,gJ.useEffect)(()=>{if(!kTe.Platform.isDesktopApp){n(hJ);return}let r;try{let o=ls(t);n(o.getActiveWebTabState()),r=o.subscribeActiveWebTabState(n)}catch{n(hJ)}return()=>{r?.()}},[t]),e}Se();var K4=30;function yJ(t,e,n,r,o,i=null){let s=mJ(r),a=Tut(),l=MTe.Platform.isDesktopApp&&(e==="category"&&t.trim().length>0||e==="search"&&n==="webTabs"),c=Put({enabled:l}),{activeWebTabForMentions:u}=iS(),d=(0,xc.useMemo)(()=>s.map((h,g)=>({key:`note-${h.basename}-${g}`,title:h.basename,subtitle:h.path,category:"notes",data:h,content:void 0,icon:xc.default.createElement(Ur,{className:"tw-size-4"}),searchKeyword:h.path})),[s]),f=(0,xc.useMemo)(()=>r?oR.map(h=>({key:`tool-${h}`,title:h,subtitle:txe(h),category:"tools",data:h,content:txe(h),icon:xc.default.createElement(Nd,{className:"tw-size-4"})})):[],[r]),p=(0,xc.useMemo)(()=>a.map(h=>({key:`folder-${h.path}`,title:h.name,subtitle:h.path,category:"folders",data:h,content:void 0,icon:xc.default.createElement(es,{className:"tw-size-4"}),searchKeyword:h.path})),[a]),m=(0,xc.useMemo)(()=>MTe.Platform.isDesktopApp?c.map((h,g)=>{let y=h.isLoaded!==!1;return{key:`webtab-${h.url||h.title||g}-${g}`,title:h.title||"Untitled",subtitle:y?h.url:"Tab not loaded",category:"webTabs",data:h,content:void 0,disabled:!y,disabledReason:"Switch to this tab to load it first",icon:y?xc.default.createElement(Br,{className:"tw-size-4"}):xc.default.createElement(nw,{className:"tw-size-4 tw-text-muted"}),searchKeyword:`${h.title||""} ${h.url||""}`}}):[],[c]);return(0,xc.useMemo)(()=>{if(e==="category"){if(!t){let A=o.map(D=>({...D,content:void 0})),O=[];return u&&O.push({key:"active-web-tab",title:"Active Web Tab",subtitle:void 0,category:"activeWebTab",data:u,content:void 0,icon:xc.default.createElement(Br,{className:"tw-size-4"})}),i&&O.push({key:`active-note-${i.path}`,title:"Active Note",subtitle:void 0,category:"activeNote",data:i,content:void 0,icon:xc.default.createElement(iw,{className:"tw-size-4"})}),O.length>0?[...O,...A]:A}let h=t.toLowerCase(),g=f.filter(A=>A.title.toLowerCase().includes(h)),v="active note".includes(h)&&i?{key:`active-note-${i.path}`,title:"Active Note",subtitle:void 0,category:"activeNote",data:i,content:void 0,icon:xc.default.createElement(iw,{className:"tw-size-4"})}:null,_="active web tab".includes(h)&&u?{key:"active-web-tab",title:"Active Web Tab",subtitle:void 0,category:"activeWebTab",data:u,content:void 0,icon:xc.default.createElement(Br,{className:"tw-size-4"})}:null,T=[...d,...p,...m],P=NTe.default.go(t,T,{keys:["searchKeyword"],limit:K4,threshold:-1e4}).map(A=>A.obj);return[...g,..._?[_]:[],...v?[v]:[],...P].slice(0,K4)}else{let h=[];switch(n){case"notes":h=d;break;case"tools":h=f;break;case"folders":h=p;break;case"webTabs":h=m;break}if(!t){if(n==="notes"){let y=q().customPromptsFolder,w=h.filter(x=>!(typeof x.data=="object"&&"path"in x.data&&typeof x.data.path=="string"&&x.data.path.startsWith(y+"/"))),v=h.filter(x=>typeof x.data=="object"&&"path"in x.data&&typeof x.data.path=="string"&&x.data.path.startsWith(y+"/"));return[...w,...v].slice(0,K4)}return h.slice(0,K4)}return NTe.default.go(t,h,{keys:["title","subtitle"],limit:K4,threshold:-1e4}).map(y=>y.obj)}},[e,t,n,d,f,p,m,o,u,i])}function T7t(t){return"data"in t}function I7t(t){return"icon"in t&&!("data"in t)}function Eut({isOpen:t,onClose:e,onSelect:n,isCopilotPlus:r=!1,currentActiveFile:o=null}){let[i,s]=(0,xf.useState)(""),[a,l]=(0,xf.useState)(0),[c,u]=(0,xf.useState)({mode:"category"}),[d,f]=(0,xf.useState)(t),[p,m]=(0,xf.useState)(0),h=dJ(r),g=yJ(i,c.mode,c.selectedCategory,r,h,o),y=(0,xf.useCallback)(b=>{if(!b?.disabled){if(c.mode==="category"&&I7t(b)&&!i){u(_=>({..._,mode:"search",selectedCategory:b.category})),s(""),l(0);return}T7t(b)&&(n(b.category,b.data),e())}},[c.mode,i,n,e]),w=(0,xf.useCallback)(b=>{l(b)},[]),v=(0,xf.useCallback)(b=>{s(b),l(0)},[]),x=(0,xf.useCallback)(b=>{switch(b.key){case"ArrowDown":{b.preventDefault();let _=a+1;for(;_<g.length&&g[_]?.disabled;)_++;_>=g.length&&(_=a),l(_);break}case"ArrowUp":{b.preventDefault();let _=a-1;for(;_>=0&&g[_]?.disabled;)_--;_<0&&(_=a),l(_);break}case"Enter":case"Tab":{b.preventDefault();let _=g[a];if(_?.disabled)break;_&&y(_);break}case"Escape":{b.preventDefault(),e();break}case"Backspace":{c.mode==="search"&&!i&&(b.preventDefault(),u({mode:"category",selectedCategory:void 0}),l(0));break}}},[a,g,y,e,c.mode,i]);return t!==d&&(f(t),t||(s(""),l(0),u({mode:"category",selectedCategory:void 0}))),g.length!==p&&(m(g.length),l(0)),t?xf.default.createElement(but,{options:g,selectedIndex:a,onSelect:y,onHighlight:w,query:i,mode:c.mode,showPreview:!1,searchBarMode:!0,searchQuery:i,onSearchChange:v,onKeyDown:x}):null}var P7t=[];function E7t({selectedText:t,onRemoveContext:e}){if(iJ(t)){let r=Xy(t.url);return fn.default.createElement(ro,{className:"tw-items-center tw-py-0 tw-pl-2 tw-pr-0.5 tw-text-xs"},fn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},fn.default.createElement(V4,{faviconUrl:t.faviconUrl}),fn.default.createElement("span",{className:"tw-max-w-40 tw-truncate"},t.title||r),fn.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Selection")),fn.default.createElement(X,{variant:"ghost2",size:"fit",onClick:()=>e("selectedText",t.id),"aria-label":"Remove from context",className:"tw-text-muted"},fn.default.createElement(Sn,{className:"tw-size-4"})))}let n=t.startLine===t.endLine?`L${t.startLine}`:`L${t.startLine}-${t.endLine}`;return fn.default.createElement(ro,{className:"tw-items-center tw-py-0 tw-pl-2 tw-pr-0.5 tw-text-xs"},fn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},fn.default.createElement(Ur,{className:"tw-size-3"}),fn.default.createElement("span",{className:"tw-max-w-40 tw-truncate"},t.noteTitle),fn.default.createElement("span",{className:"tw-text-xs tw-text-faint"},n)),fn.default.createElement(X,{variant:"ghost2",size:"fit",onClick:()=>e("selectedText",t.id),"aria-label":"Remove from context",className:"tw-text-muted"},fn.default.createElement(Sn,{className:"tw-size-4"})))}var kut=({includeActiveNote:t,currentActiveFile:e,includeActiveWebTab:n,activeWebTab:r,contextNotes:o,contextUrls:i,contextFolders:s,contextWebTabs:a,selectedTextContexts:l=P7t,onRemoveContext:c,showProgressCard:u,showIndexingCard:d,onTypeaheadSelect:f,lexicalEditorRef:p})=>{let[m]=kd(),h=_Z(),[g]=DA(),[y,w]=(0,fn.useState)(!1),v=(0,fn.useRef)(null),x=Mc(m),b=()=>{w(!1)},_=(F,Z)=>{f(F,Z),window.setTimeout(()=>{p?.current&&p.current.focus()},100)},T=F=>{VAe(F)},S=fn.default.useMemo(()=>{let F=new Map(o.map(Z=>[Z.path,Z]));return Array.from(F.values())},[o]),P=fn.default.useMemo(()=>Array.from(new Set(i)),[i]),A=fn.default.useMemo(()=>$P(a),[a]),O=l.length>0,D=t&&!O&&!!e,$=n&&!O&&!!r&&Aut.Platform.isDesktopApp,B=S.length>0||P.length>0||l.length>0||s.length>0||A.length>0||D||$,W=()=>{switch(h){case"success":return fn.default.createElement(Pu,{className:"tw-size-4 tw-text-success"});case"loading":return fn.default.createElement(Pr,{className:"tw-size-4 tw-animate-spin tw-text-loading"});case"error":return fn.default.createElement(Fs,{className:"tw-size-4 tw-text-error"});case"initial":return fn.default.createElement(nw,{className:"tw-size-4 tw-text-faint"})}};return fn.default.createElement("div",{className:"tw-flex tw-w-full tw-items-start tw-gap-1"},fn.default.createElement("div",{className:"tw-flex tw-h-full tw-items-start"},fn.default.createElement(R_,{open:y,onOpenChange:w},fn.default.createElement(L_,{asChild:!0},fn.default.createElement(X,{ref:v,variant:"ghost2",size:"fit",className:"tw-ml-1 tw-rounded-sm tw-border tw-border-solid tw-border-border tw-text-muted"},fn.default.createElement("span",{className:"tw-text-base tw-font-medium tw-leading-none"},"@"),!B&&fn.default.createElement("span",{className:"tw-pr-1 tw-text-sm tw-leading-4"},"Add context"))),fn.default.createElement(Kv,{className:"tw-w-[400px] tw-p-0",align:"start",side:"top",sideOffset:4},fn.default.createElement(Eut,{isOpen:y,onClose:b,onSelect:_,isCopilotPlus:x,currentActiveFile:e})))),fn.default.createElement("div",{className:"tw-flex tw-flex-1 tw-flex-wrap tw-gap-1"},D&&e&&fn.default.createElement(gut,{currentActiveFile:e,onRemove:()=>c("activeNote",""),onClick:()=>T(e)}),$&&r&&fn.default.createElement(yut,{activeWebTab:r,onRemove:()=>c("activeWebTab","")}),S.map(F=>fn.default.createElement(sJ,{key:F.path,note:F,onRemove:()=>c("notes",F.path),onClick:()=>T(F)})),P.map(F=>fn.default.createElement(aJ,{key:F,url:F,onRemove:()=>c("urls",F)})),s.map(F=>fn.default.createElement(cJ,{key:F,folder:F,onRemove:()=>c("folders",F)})),A.map(F=>fn.default.createElement(lJ,{key:F.url,webTab:F,onRemove:()=>c("webTabs",F.url)})),l.map(F=>fn.default.createElement(E7t,{key:F.id,selectedText:F,onRemoveContext:c}))),m==="project"&&fn.default.createElement(fn.default.Fragment,null,fn.default.createElement(Jp,{orientation:"vertical"}),fn.default.createElement("div",{className:""},fn.default.createElement(X,{variant:"ghost2",size:"fit",className:"tw-text-muted",onClick:()=>u()},W()))),m!=="project"&&g.isActive&&d&&fn.default.createElement(fn.default.Fragment,null,fn.default.createElement(Jp,{orientation:"vertical"}),fn.default.createElement(X,{variant:"ghost2",size:"fit",className:"tw-text-muted",onClick:d},fn.default.createElement(Pr,{className:"tw-size-3 tw-animate-spin"}),fn.default.createElement("span",{className:"tw-text-xs"},"Indexing..."))))};var Nut=({contextNotes:t,includeActiveNote:e,activeNote:n,includeActiveWebTab:r,activeWebTab:o,contextUrls:i,contextFolders:s,contextWebTabs:a,selectedTextContexts:l,showProgressCard:c,showIndexingCard:u,lexicalEditorRef:d,onAddToContext:f,onRemoveFromContext:p})=>Mut.default.createElement(kut,{includeActiveNote:e,currentActiveFile:n,includeActiveWebTab:r,activeWebTab:o,contextNotes:t,onRemoveContext:(g,y)=>{p(g,y)},contextUrls:i,contextFolders:s,contextWebTabs:a,selectedTextContexts:l,showProgressCard:c,showIndexingCard:u,onTypeaheadSelect:(g,y)=>{f(g,y)},lexicalEditorRef:d});var sS=N(U());var Rut=N(U());var Out=N(U());Kt();function Ol({children:t,className:e,...n}){return Out.default.createElement(ro,{variant:"secondary",className:oe("tw-mx-0.5 tw-inline-flex tw-items-center tw-gap-1 tw-border tw-border-solid tw-border-border tw-px-2 tw-py-0 tw-align-middle tw-text-xs",e),...n},t)}function va(t){return t.getRootElement()?.doc??activeDocument}var bc=class extends Q7{constructor(e,n){super(n),this.__value=e}updateDOM(){return!1}isInline(){return!0}canInsertTextBefore(){return!0}canInsertTextAfter(){return!0}canBeEmpty(){return!1}isKeyboardSelectable(){return!0}isIsolated(){return!0}isPill(){return!0}getValue(){return this.__value}setValue(e){let n=this.getWritable();n.__value=e}getTextContent(){return this.__value}createDOM(e,n){let r=va(n).createElement("span");return r.className=this.getClassName(),r}exportDOM(e){let n=va(e).createElement("span");return n.setAttribute(this.getDataAttribute(),""),n.setAttribute("data-pill-value",this.__value),n.textContent=this.__value,{element:n}}exportJSON(){return{...super.exportJSON(),value:this.__value,type:this.getType(),version:1}}decorate(){return Rut.default.createElement(Ol,null,this.__value)}};var bf=N(U());Kt();function Oy({content:t,openBracket:e,closeBracket:n,className:r,maxWidth:o="tw-max-w-40",tooltipContent:i}){let s=(0,bf.useRef)(null),[a,l]=(0,bf.useState)(!1);return bf.default.createElement(uu,{delayDuration:300},bf.default.createElement(cn,{open:a,onOpenChange:u=>{let d=s.current?s.current.offsetWidth<s.current.scrollWidth:!1;l(u&&d)}},bf.default.createElement(un,{asChild:!0},bf.default.createElement("span",{className:oe("tw-inline-flex tw-items-center",o,r)},bf.default.createElement("span",{className:"tw-shrink-0"},e),bf.default.createElement("span",{ref:s,className:"tw-min-w-0 tw-truncate"},t),bf.default.createElement("span",{className:"tw-shrink-0"},n))),bf.default.createElement(on,{className:"tw-max-w-64 tw-text-wrap tw-break-words"},i||`${e}${t}${n}`)))}var aS=class t extends bc{static getType(){return"note-pill"}static clone(e){return new t(e.__noteTitle,e.__notePath,e.__key)}constructor(e,n,r){super(e,r),this.__noteTitle=e,this.__notePath=n}getClassName(){return"note-pill-wrapper"}getDataAttribute(){return"data-lexical-note-pill"}createDOM(e,n){let r=va(n).createElement("span");return r.className="note-pill-wrapper",r}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-note-pill")?{conversion:A7t,priority:1}:null}}static importJSON(e){let{noteTitle:n,notePath:r}=e;return q4(n,r)}exportJSON(){return{...super.exportJSON(),noteTitle:this.__noteTitle,notePath:this.__notePath,type:"note-pill",version:1}}exportDOM(e){let n=va(e).createElement("span");n.setAttribute("data-lexical-note-pill","true"),n.setAttribute("data-note-title",this.__noteTitle),n.setAttribute("data-note-path",this.__notePath);let r=this.__notePath.toLowerCase(),o=r.endsWith(".pdf")?`${this.__noteTitle}.pdf`:r.endsWith(".canvas")?`${this.__noteTitle}.canvas`:this.__noteTitle;return n.textContent=`[[${o}]]`,{element:n}}getTextContent(){let e=this.__notePath.toLowerCase();return`[[${e.endsWith(".pdf")?`${this.__noteTitle}.pdf`:e.endsWith(".canvas")?`${this.__noteTitle}.canvas`:this.__noteTitle}]]`}getNoteTitle(){return this.__noteTitle}getNotePath(){return this.__notePath}decorate(){return sS.default.createElement(k7t,{node:this})}};function A7t(t){let e=t.getAttribute("data-note-title"),n=t.getAttribute("data-note-path");return e&&n?{node:q4(e,n)}:null}function k7t({node:t}){let e=t.getNoteTitle(),n=t.getNotePath(),r=n.toLowerCase(),o=r.endsWith(".pdf"),i=r.endsWith(".canvas");return sS.default.createElement(Ol,null,sS.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},sS.default.createElement(Oy,{content:e,openBracket:"[[",closeBracket:"]]",tooltipContent:sS.default.createElement("div",{className:"tw-text-left"},n)}),o&&sS.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"pdf"),i&&sS.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"canvas")))}function q4(t,e){return new aS(t,e)}function OTe(t){return t instanceof aS}function Lut(t){let e=mr(),n=0;function r(o){if(OTe(o)&&o.getNotePath()===t)o.remove(),n++;else if("getChildren"in o&&typeof o.getChildren=="function"){let i=o.getChildren();for(let s of i)r(s)}}return r(e),n}var tm=N(U());var lS=N(U()),Dut=(0,lS.createContext)(void 0);function $ut(){let t=(0,lS.useContext)(Dut);return t===void 0?null:t.currentActiveFile}function wJ({currentActiveFile:t,children:e}){let n=(0,lS.useMemo)(()=>({currentActiveFile:t}),[t]);return lS.default.createElement(Dut.Provider,{value:n},e)}var cS=class t extends bc{static getType(){return"active-note-pill"}static clone(e){return new t(e.__key)}constructor(e){super("Current Note",e)}getClassName(){return"active-note-pill-wrapper"}getDataAttribute(){return"data-lexical-active-note-pill"}createDOM(e,n){let r=va(n).createElement("span");return r.className="active-note-pill-wrapper",r}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-active-note-pill")?{conversion:M7t,priority:2}:null}}static importJSON(e){return G4()}exportJSON(){return{...super.exportJSON(),type:"active-note-pill",version:1}}exportDOM(e){let n=va(e).createElement("span");return n.setAttribute("data-lexical-active-note-pill","true"),n.textContent="{activeNote}",{element:n}}getTextContent(){return"{activeNote}"}decorate(){return tm.default.createElement(N7t,null)}};function M7t(t){return{node:G4()}}function N7t(){let t=$ut();if(!t)return tm.default.createElement(Ol,null,tm.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},tm.default.createElement(Oy,{content:"activeNote",openBracket:"{",closeBracket:"}",tooltipContent:tm.default.createElement("div",{className:"tw-text-left"},"Will use the active note at the time the message is sent")})));let e=t.basename,n=t.path,r=n.toLowerCase().endsWith(".pdf");return tm.default.createElement(Ol,null,tm.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},tm.default.createElement(Oy,{content:e,openBracket:"[[",closeBracket:"]]",tooltipContent:tm.default.createElement("div",{className:"tw-text-left"},n)}),tm.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Current"),r&&tm.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"pdf")))}function G4(){return new cS}function RTe(t){return t instanceof cS}function Fut(){let t=mr(),e=0;function n(r){if(RTe(r))r.remove(),e++;else if("getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}var Y4=N(U());var pE=class t extends bc{static getType(){return"url-pill"}static clone(e){return new t(e.__url,e.__title,e.__isActive,e.__key)}constructor(e,n,r=!1,o){super(e,o),this.__url=e,this.__title=n,this.__isActive=r}getClassName(){return"url-pill-wrapper"}getDataAttribute(){return"data-lexical-url-pill"}createDOM(e,n){let r=va(n).createElement("span");return r.className="url-pill-wrapper",r}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-url-pill")?{conversion:O7t,priority:1}:null}}static importJSON(e){let{url:n,title:r,isActive:o}=e;return vJ(n,r,o)}exportJSON(){return{...super.exportJSON(),url:this.__url,title:this.__title,isActive:this.__isActive,type:"url-pill",version:1}}exportDOM(e){let n=va(e).createElement("span");return n.setAttribute("data-lexical-url-pill","true"),n.setAttribute("data-url",this.__url),this.__title&&n.setAttribute("data-title",this.__title),n.textContent=this.__url,{element:n}}getTextContent(){return this.__url}getURL(){return this.__url}setURL(e){let n=this.getWritable();n.__url=e}getTitle(){return this.__title}setTitle(e){let n=this.getWritable();n.__title=e}setActive(e){let n=this.getWritable();n.__isActive=e}getActive(){return this.__isActive}decorate(){let e=this.__title||this.__url;return Y4.default.createElement(Ol,{className:"tw-whitespace-nowrap"},Y4.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Y4.default.createElement("span",{className:"tw-max-w-40 tw-truncate"},e),this.__isActive&&Y4.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Active")))}};function O7t(t){let e=t.getAttribute("data-url"),n=t.getAttribute("data-title");return e!==null?{node:vJ(e,n||void 0)}:null}function vJ(t,e,n=!1){return new pE(t,e,n)}function R7t(){let t=mr(),e=[];function n(r){if(r instanceof pE&&e.push(r),"getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}function Uut(t){let e=R7t();for(let n of e)n.getURL()===t&&n.remove()}function But(t){return t instanceof pE}var xJ=N(U());var fx=class t extends bc{static getType(){return"folder-pill"}static clone(e){return new t(e.__value,e.__key)}constructor(e,n){super(e,n)}getClassName(){return"folder-pill-wrapper"}getDataAttribute(){return"data-lexical-folder-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-folder-pill")?{conversion:L7t,priority:1}:null}}static importJSON(e){let{value:n}=e;return Z4(n)}exportJSON(){return{...super.exportJSON(),type:"folder-pill"}}decorate(){let e=xJ.default.createElement("div",{className:"tw-text-left"},this.getFolderPath());return xJ.default.createElement(Ol,null,xJ.default.createElement(Oy,{content:this.getFolderPath(),openBracket:"{",closeBracket:"}",tooltipContent:e}))}getTextContent(){return`{${this.getFolderPath()}}`}exportDOM(e){let n=va(e).createElement("span");return n.setAttribute(this.getDataAttribute(),""),n.setAttribute("data-pill-value",this.__value),n.textContent=`{${this.getFolderPath()}}`,{element:n}}getFolderPath(){return this.getValue()}};function L7t(t){let e=t.getAttribute("data-pill-value");return e!==null?{node:Z4(e)}:null}function Z4(t){return new fx(t)}function zut(t){return t instanceof fx}function D7t(){let t=mr(),e=[];function n(r){if(r instanceof fx&&e.push(r),"getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}function jut(t){let e=D7t();for(let n of e)n.getValue()===t&&n.remove()}var mE=class t extends bc{static getType(){return"tool-pill"}static clone(e){return new t(e.__value,e.__key)}constructor(e,n){super(e,n)}getClassName(){return"tool-pill-wrapper"}getDataAttribute(){return"data-lexical-tool-pill"}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-tool-pill")?{conversion:$7t,priority:1}:null}}static importJSON(e){let{value:n}=e;return hE(n)}exportJSON(){return{...super.exportJSON(),type:"tool-pill"}}getToolName(){return this.getValue()}};function $7t(t){let e=t.getAttribute("data-pill-value");return e!==null?{node:hE(e)}:null}function hE(t){return new mE(t)}function Vut(t){return t instanceof mE}function F7t(){let t=mr(),e=[];function n(r){if(r instanceof mE&&e.push(r),"getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}function J4(t){let e=F7t();for(let n of e)n.getValue()===t&&n.remove()}var Rl=N(U());vt();var Wut=require("obsidian");It();var uS=class t extends bc{static getType(){return"active-web-tab-pill"}static clone(e){return new t(e.__key)}constructor(e){super("Current Web Tab",e)}getClassName(){return"active-web-tab-pill-wrapper"}getDataAttribute(){return"data-lexical-active-web-tab-pill"}createDOM(e,n){let r=va(n).createElement("span");return r.className="active-web-tab-pill-wrapper",r}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-active-web-tab-pill")?{conversion:U7t,priority:2}:null}}static importJSON(e){return bJ()}exportJSON(){return{...super.exportJSON(),type:"active-web-tab-pill",version:1}}exportDOM(e){let n=va(e).createElement("span");return n.setAttribute("data-lexical-active-web-tab-pill","true"),n.textContent=lD,{element:n}}getTextContent(){return lD}decorate(){return Rl.default.createElement(B7t,null)}};function U7t(t){return{node:bJ()}}function B7t(){let{activeWebTabForMentions:t}=iS();return Wut.Platform.isDesktopApp?t?Rl.default.createElement(Ol,null,Rl.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Rl.default.createElement(Br,{className:"tw-size-3"}),Rl.default.createElement("span",{className:"tw-max-w-40 tw-truncate",title:t.url},t.title??"Untitled"),Rl.default.createElement("span",{className:"tw-text-xs tw-text-faint"},"Current"))):Rl.default.createElement(Ol,null,Rl.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Rl.default.createElement(Br,{className:"tw-size-3"}),Rl.default.createElement(Oy,{content:"activeWebTab",openBracket:"{",closeBracket:"}",tooltipContent:Rl.default.createElement("div",{className:"tw-text-left"},"Will use the active web tab at the time the message is sent")}))):Rl.default.createElement(Ol,null,Rl.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Rl.default.createElement(Br,{className:"tw-size-3"}),Rl.default.createElement(Oy,{content:"activeWebTab",openBracket:"{",closeBracket:"}",tooltipContent:Rl.default.createElement("div",{className:"tw-text-left"},"Web Viewer not supported on mobile")})))}function bJ(){return new uS}function LTe(t){return t instanceof uS}function Hut(){let t=mr(),e=0;function n(r){if(LTe(r))r.remove(),e++;else if("getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}var X4=N(U());vt();qe();function Kut(t,e){return`[\u{1F310}: ${e?.trim()||Xy(t)||"Untitled"}]`}var px=class t extends bc{static getType(){return"web-tab-pill"}static clone(e){return new t(e.__url,e.__title,e.__faviconUrl,e.__key)}constructor(e,n,r,o){super(e,o),this.__url=e,this.__title=n,this.__faviconUrl=r}getClassName(){return"web-tab-pill-wrapper"}getDataAttribute(){return"data-lexical-web-tab-pill"}createDOM(e,n){let r=va(n).createElement("span");return r.className="web-tab-pill-wrapper",r}static importDOM(){return{span:e=>e.hasAttribute("data-lexical-web-tab-pill")?{conversion:z7t,priority:1}:null}}static importJSON(e){let{url:n,title:r,faviconUrl:o}=e;return CJ(n,r,o)}exportJSON(){return{...super.exportJSON(),url:this.__url,title:this.__title,faviconUrl:this.__faviconUrl,type:"web-tab-pill",version:1}}exportDOM(e){let n=va(e).createElement("span");return n.setAttribute("data-lexical-web-tab-pill","true"),n.setAttribute("data-url",this.__url),this.__title&&n.setAttribute("data-title",this.__title),this.__faviconUrl&&n.setAttribute("data-favicon-url",this.__faviconUrl),n.textContent=Kut(this.__url,this.__title),{element:n}}getTextContent(){return Kut(this.__url,this.__title)}getURL(){return this.__url}getTitle(){return this.__title}getFaviconUrl(){return this.__faviconUrl}setTitle(e){let n=this.getWritable();n.__title=e}setFaviconUrl(e){let n=this.getWritable();n.__faviconUrl=e}decorate(){let e=this.__title||this.__url;return X4.default.createElement(Ol,{className:"tw-whitespace-nowrap"},X4.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},X4.default.createElement(Br,{className:"tw-size-3"}),X4.default.createElement("span",{className:"tw-max-w-40 tw-truncate"},e)))}};function z7t(t){let e=t.getAttribute("data-url"),n=t.getAttribute("data-title"),r=t.getAttribute("data-favicon-url");return e!==null?{node:CJ(e,n||void 0,r||void 0)}:null}function CJ(t,e,n){return new px(t,e,n)}function qut(t){return t instanceof px}function DTe(){let t=mr(),e=[];function n(r){if(r instanceof px&&e.push(r),"getChildren"in r&&typeof r.getChildren=="function"){let o=r.getChildren();for(let i of o)n(i)}}return n(t),e}function Gut(t){let e=DTe();for(let n of e)n.getURL()===t&&n.remove()}var Nr=N(U());var $Te={};zn($Te,{LexicalComposerContext:()=>Yut,createLexicalComposerContext:()=>j7t,useLexicalComposerContext:()=>V7t});var _J=N(U(),1),Yut=(0,_J.createContext)(null);function j7t(t,e){let n=null;return t!=null&&(n=t[1]),{getTheme:function(){return e??(n!=null?n.getTheme():null)}}}function V7t(){let t=(0,_J.useContext)(Yut);return t==null&&function(e,...n){let r=new URL("https://lexical.dev/docs/error"),o=new URLSearchParams;o.append("code",e);for(let i of n)o.append("v",i);throw r.search=o.toString(),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.`)}(8),t}var FTe=$Te,Zut=FTe.LexicalComposerContext,Jut=FTe.createLexicalComposerContext,vr=FTe.useLexicalComposerContext;var UTe={};zn(UTe,{LexicalComposer:()=>H7t});var d1=N(U(),1),Xut=N(Ve(),1),Qut=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,W7t=Qut?d1.useLayoutEffect:d1.useEffect,SJ={tag:s1};function H7t({initialConfig:t,children:e}){let n=(0,d1.useMemo)(()=>{let{theme:r,namespace:o,nodes:i,onError:s,editorState:a,html:l}=t,c=Jut(null,r),u=uut({editable:t.editable,html:l,namespace:o,nodes:i,onError:d=>s(d,u),theme:r});return function(d,f){if(f!==null){if(f===void 0)d.update(()=>{let p=mr();if(p.isEmpty()){let m=cx();p.append(m);let h=Qut?document.activeElement:null;(gn()!==null||h!==null&&h===d.getRootElement())&&m.select()}},SJ);else if(f!==null)switch(typeof f){case"string":{let p=d.parseEditorState(f);d.setEditorState(p,SJ);break}case"object":d.setEditorState(f,SJ);break;case"function":d.update(()=>{mr().isEmpty()&&f(d)},SJ)}}}(u,a),[u,c]},[]);return W7t(()=>{let r=t.editable,[o]=n;o.setEditable(r===void 0||r)},[]),(0,Xut.jsx)(Zut.Provider,{value:n,children:e})}var K7t=UTe,TJ=K7t.LexicalComposer;var BTe={};zn(BTe,{useLexicalEditable:()=>Y7t});var Ry=N(U(),1),q7t=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0?Ry.useLayoutEffect:Ry.useEffect;function G7t(t){return{initialValueFn:()=>t.isEditable(),subscribe:e=>t.registerEditableListener(e)}}function Y7t(){return function(t){let[e]=vr(),n=(0,Ry.useMemo)(()=>t(e),[e,t]),[r,o]=(0,Ry.useState)(()=>n.initialValueFn()),i=(0,Ry.useRef)(r);return q7t(()=>{let{initialValueFn:s,subscribe:a}=n,l=s();return i.current!==l&&(i.current=l,o(l)),a(c=>{i.current=c,o(c)})},[n,t]),r}(G7t)}var Z7t=BTe,edt=Z7t.useLexicalEditable;var jTe={};zn(jTe,{$canShowPlaceholder:()=>ndt,$canShowPlaceholderCurry:()=>X7t,$findTextIntersectionFromCharacters:()=>Q7t,$isRootTextContentEmpty:()=>zTe,$isRootTextContentEmptyCurry:()=>J7t,$rootTextContent:()=>tdt,registerLexicalTextEntity:()=>tJt});function tdt(){return mr().getTextContent()}function zTe(t,e=!0){if(t)return!1;let n=tdt();return e&&(n=n.trim()),n===""}function J7t(t,e){return()=>zTe(t,e)}function ndt(t){if(!zTe(t,!1))return!1;let e=mr().getChildren(),n=e.length;if(n>1)return!1;for(let r=0;r<n;r++){let o=e[r];if(G7(o))return!1;if(lr(o)){if(!Ect(o)||o.__indent!==0)return!1;let i=o.getChildren(),s=i.length;for(let a=0;a<s;a++){let l=i[r];if(!Mr(l))return!1}}}return!0}function X7t(t){return()=>ndt(t)}function Q7t(t,e){let n=t.getFirstChild(),r=0;e:for(;n!==null;){if(lr(n)){let s=n.getFirstChild();if(s!==null){n=s;continue}}else if(Mr(n)){let s=n.getTextContentSize();if(r+s>e)return{node:n,offset:e-r};r+=s}let o=n.getNextSibling();if(o!==null){n=o;continue}let i=n.getParent();for(;i!==null;){let s=i.getNextSibling();if(s!==null){n=s;continue e}i=i.getParent()}break}return null}function eJt(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),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 tJt(t,e,n,r){let o=s=>s instanceof n,i=s=>{let a=vf(s.getTextContent());a.setFormat(s.getFormat()),s.replace(a)};return[t.registerNodeTransform(My,s=>{if(!s.isSimpleText())return;let a,l=s.getPreviousSibling(),c=s.getTextContent(),u=s;if(Mr(l)){let f=l.getTextContent(),p=e(f+c);if(o(l)){if(p===null||(m=>m.getLatest().__mode)(l)!==0)return void i(l);{let m=p.end-f.length;if(m>0){let h=f+c.slice(0,m);if(l.select(),l.setTextContent(h),m===c.length)s.remove();else{let g=c.slice(m);s.setTextContent(g)}return}}}else if(p===null||p.start<f.length)return}let d=0;for(;;){a=e(c);let f,p=a===null?"":c.slice(a.end);if(c=p,p===""){let h=u.getNextSibling();if(Mr(h)){p=u.getTextContent()+h.getTextContent();let g=e(p);if(g===null)return void(o(h)?i(h):h.markDirty());if(g.start!==0)return}}if(a===null)return;if(a.start===0&&Mr(l)&&l.isTextEntity()){d+=a.end;continue}a.start===0?[f,u]=u.splitText(a.end):[,f,u]=u.splitText(a.start+d,a.end+d),f===void 0&&eJt(165,"nodeToReplace");let m=r(f);if(m.setFormat(f.getFormat()),f.replace(m),u==null)return;d=0,l=m}}),t.registerNodeTransform(n,s=>{let a=s.getTextContent(),l=e(a);if(l===null||l.start!==0)return void i(s);if(a.length>l.end)return void s.splitText(l.end);let c=s.getPreviousSibling();Mr(c)&&c.isTextEntity()&&(i(c),i(s));let u=s.getNextSibling();Mr(u)&&u.isTextEntity()&&(i(u),o(s)&&i(s))})]}var gE=jTe,hzr=gE.$canShowPlaceholder,IJ=gE.$canShowPlaceholderCurry,gzr=gE.$findTextIntersectionFromCharacters,yzr=gE.$isRootTextContentEmpty,wzr=gE.$isRootTextContentEmptyCurry,vzr=gE.$rootTextContent,xzr=gE.registerLexicalTextEntity;var GTe={};zn(GTe,{$addNodeStyle:()=>sJt,$cloneWithProperties:()=>rS,$copyBlockFormatIndent:()=>ddt,$ensureForwardRangeSelection:()=>udt,$forEachSelectedTextNode:()=>cdt,$getSelectionStyleValueForProperty:()=>mJt,$isAtNodeEnd:()=>iJt,$isParentElementRTL:()=>qTe,$moveCaretSelection:()=>pdt,$moveCharacter:()=>fJt,$patchStyleText:()=>aJt,$selectAll:()=>Z7,$setBlocksType:()=>lJt,$shouldOverrideDefaultCharacterSelection:()=>dJt,$sliceSelectedTextNodeContent:()=>oJt,$trimTextContentFromAnchor:()=>ldt,$wrapNodes:()=>uJt,createDOMRange:()=>nJt,createRectsFromDOMRange:()=>rJt,getCSSFromStyleObject:()=>adt,getStyleObjectFromCSS:()=>EJ,trimTextContentFromAnchor:()=>hJt});function KTe(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),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.`)}var PJ=new Map;function rdt(t){let e=t;for(;e!=null;){if(e.nodeType===Node.TEXT_NODE)return e;e=e.firstChild}return null}function odt(t){let e=t.parentNode;if(e==null)throw new Error("Should never happen");return[e,Array.from(e.childNodes).indexOf(t)]}function nJt(t,e,n,r,o){let i=e.getKey(),s=r.getKey(),a=document.createRange(),l=t.getElementByKey(i),c=t.getElementByKey(s),u=n,d=o;if(Mr(e)&&(l=rdt(l)),Mr(r)&&(c=rdt(c)),e===void 0||r===void 0||l===null||c===null)return null;l.nodeName==="BR"&&([l,u]=odt(l)),c.nodeName==="BR"&&([c,d]=odt(c));let f=l.firstChild;l===c&&f!=null&&f.nodeName==="BR"&&u===0&&d===0&&(d=1);try{a.setStart(l,u),a.setEnd(c,d)}catch{return null}return!a.collapsed||u===d&&i===s||(a.setStart(c,d),a.setEnd(l,u)),a}function rJt(t,e){let n=t.getRootElement();if(n===null)return[];let r=n.getBoundingClientRect(),o=getComputedStyle(n),i=parseFloat(o.paddingLeft)+parseFloat(o.paddingRight),s=Array.from(e.getClientRects()),a,l=s.length;s.sort((c,u)=>{let d=c.top-u.top;return Math.abs(d)<=3?c.left-u.left:d});for(let c=0;c<l;c++){let u=s[c],d=a&&a.top<=u.top&&a.top+a.height>u.top&&a.left+a.width>u.left,f=u.width+i===r.width;d||f?(s.splice(c--,1),l--):a=u}return s}function sdt(t){let e={};if(!t)return e;let n=t.split(";");for(let r of n)if(r!==""){let[o,i]=r.split(/:([^]+)/);o&&i&&(e[o.trim()]=i.trim())}return e}function EJ(t){let e=PJ.get(t);return e===void 0&&(e=sdt(t),PJ.set(t,e)),e}function adt(t){let e="";for(let n in t)n&&(e+=`${n}: ${t[n]};`);return e}function oJt(t,e){let n=t.getStartEndPoints();if(e.isSelected(t)&&!xTe(e)&&n!==null){let[r,o]=n,i=t.isBackward(),s=r.getNode(),a=o.getNode(),l=e.is(s),c=e.is(a);if(l||c){let[u,d]=bct(t),f=s.is(a),p=e.is(i?a:s),m=e.is(i?s:a),h,g=0;f?(g=u>d?d:u,h=u>d?u:d):p?(g=i?d:u,h=void 0):m&&(g=0,h=i?u:d),e.__text=e.__text.slice(g,h)}}return e}function iJt(t){if(t.type==="text")return t.offset===t.getNode().getTextContentSize();let e=t.getNode();return lr(e)||KTe(177),t.offset===e.getChildrenSize()}function ldt(t,e,n){let r=e.getNode(),o=n;if(lr(r)){let i=r.getDescendantByIndex(e.offset);i!==null&&(r=i)}for(;o>0&&r!==null;){if(lr(r)){let c=r.getLastDescendant();c!==null&&(r=c)}let i=r.getPreviousSibling(),s=0;if(i===null){let c=r.getParentOrThrow(),u=c.getPreviousSibling();for(;u===null;){if(c=c.getParent(),c===null){i=null;break}u=c.getPreviousSibling()}c!==null&&(s=c.isInline()?0:2,i=u)}let a=r.getTextContent();a===""&&lr(r)&&!r.isInline()&&(a=`

`);let l=a.length;if(!Mr(r)||o>=l){let c=r.getParent();r.remove(),c==null||c.getChildrenSize()!==0||o1(c)||c.remove(),o-=l+s,r=i}else{let c=r.getKey(),u=t.getEditorState().read(()=>{let p=_ct(c);return Mr(p)&&p.isSimpleText()?p.getTextContent():null}),d=l-o,f=a.slice(0,d);if(u!==null&&u!==a){let p=$4(),m=r;if(r.isSimpleText())r.setTextContent(u);else{let h=vf(u);r.replace(h),m=h}if(jt(p)&&p.isCollapsed()){let h=p.anchor.offset;m.select(h,h)}}else if(r.isSimpleText()){let p=e.key===c,m=e.offset;m<o&&(m=l);let h=p?m-o:0,g=p?m:d;if(p&&h===0){let[y]=r.splitText(h,g);y.remove()}else{let[,y]=r.splitText(h,g);y.remove()}}else{let p=vf(f);r.replace(p)}o=0}}}function sJt(t){let e=t.getStyle(),n=sdt(e);PJ.set(e,n)}function VTe(t,e){(jt(t)?t.isCollapsed():Mr(t)||lr(t))||KTe(280);let n=EJ(jt(t)?t.style:Mr(t)?t.getStyle():t.getTextStyle()),r=Object.entries(e).reduce((i,[s,a])=>(typeof a=="function"?i[s]=a(n[s],t):a===null?delete i[s]:i[s]=a,i),{...n}),o=adt(r);jt(t)||Mr(t)?t.setStyle(o):t.setTextStyle(o),PJ.set(o,r)}function aJt(t,e){if(jt(t)&&t.isCollapsed()){VTe(t,e);let n=t.anchor.getNode();lr(n)&&n.isEmpty()&&VTe(n,e)}cdt(n=>{VTe(n,e)})}function cdt(t){let e=gn();if(!e)return;let n=new Map;if(jt(e))for(let i of yct(e).getTextSlices())i&&n.set(i.caret.origin.getKey(),i.getSliceIndices());let r=e.getNodes();for(let i of r){if(!Mr(i)||!i.canHaveFormat())continue;let[s,a]=(o=i,n.get(o.getKey())||[0,o.getTextContentSize()]);a!==s&&(xTe(i)||s===0&&a===i.getTextContentSize()?t(i):t(i.splitText(s,a)[s===0?0:1]))}var o;jt(e)&&e.anchor.type==="text"&&e.focus.type==="text"&&e.anchor.key===e.focus.key&&udt(e)}function udt(t){if(t.isBackward()){let{anchor:e,focus:n}=t,{key:r,offset:o,type:i}=e;e.set(n.key,n.offset,n.type),n.set(r,o,i)}}function ddt(t,e){let n=t.getFormatType(),r=t.getIndent();n!==e.getFormatType()&&e.setFormat(n),r!==e.getIndent()&&e.setIndent(r)}function lJt(t,e,n=ddt){if(t===null)return;let r=t.getStartEndPoints(),o=new Map,i=null;if(r){let[s,a]=r;i=H7(),i.anchor.set(s.key,s.offset,s.type),i.focus.set(a.key,a.offset,a.type);let l=HTe(s.getNode(),z4),c=HTe(a.getNode(),z4);lr(l)&&o.set(l.getKey(),l),lr(c)&&o.set(c.getKey(),c)}for(let s of t.getNodes())if(lr(s)&&z4(s))o.set(s.getKey(),s);else if(r===null){let a=HTe(s,z4);lr(a)&&o.set(a.getKey(),a)}for(let[s,a]of o){let l=e();n(a,l),a.replace(l,!0),i&&(s===i.anchor.key&&i.anchor.set(l.getKey(),i.anchor.offset,i.anchor.type),s===i.focus.key&&i.focus.set(l.getKey(),i.focus.offset,i.focus.type))}i&&t.is(gn())&&uE(i)}function idt(t){return t.getNode().isAttached()}function cJt(t){let e=t;for(;e!==null&&!cE(e);){let n=e.getLatest(),r=e.getParent();n.getChildrenSize()===0&&e.remove(!0),e=r}}function uJt(t,e,n=null){let r=t.getStartEndPoints(),o=r?r[0]:null,i=t.getNodes(),s=i.length;if(o!==null&&(s===0||s===1&&o.type==="element"&&o.getNode().getChildrenSize()===0)){let c=o.type==="text"?o.getNode().getParentOrThrow():o.getNode(),u=c.getChildren(),d=e();return d.setFormat(c.getFormatType()),d.setIndent(c.getIndent()),u.forEach(f=>d.append(f)),n&&(d=n.append(d)),void c.replace(d)}let a=null,l=[];for(let c=0;c<s;c++){let u=i[c];cE(u)?(WTe(t,l,l.length,e,n),l=[],a=u):a===null||a!==null&&Tct(u,a)?l.push(u):(WTe(t,l,l.length,e,n),l=[u])}WTe(t,l,l.length,e,n)}function WTe(t,e,n,r,o=null){if(e.length===0)return;let i=e[0],s=new Map,a=[],l=lr(i)?i:i.getParentOrThrow();l.isInline()&&(l=l.getParentOrThrow());let c=!1;for(;l!==null;){let m=l.getPreviousSibling();if(m!==null){l=m,c=!0;break}if(l=l.getParentOrThrow(),cE(l))break}let u=new Set;for(let m=0;m<n;m++){let h=e[m];lr(h)&&h.getChildrenSize()===0&&u.add(h.getKey())}let d=new Set;for(let m=0;m<n;m++){let h=e[m],g=h.getParent();if(g!==null&&g.isInline()&&(g=g.getParent()),g!==null&&Pct(h)&&!d.has(h.getKey())){let y=g.getKey();if(s.get(y)===void 0){let w=r();w.setFormat(g.getFormatType()),w.setIndent(g.getIndent()),a.push(w),s.set(y,w),g.getChildren().forEach(v=>{w.append(v),d.add(v.getKey()),lr(v)&&v.getChildrenKeys().forEach(x=>d.add(x))}),cJt(g)}}else if(u.has(h.getKey())){lr(h)||KTe(179);let y=r();y.setFormat(h.getFormatType()),y.setIndent(h.getIndent()),a.push(y),h.remove(!0)}}if(o!==null)for(let m=0;m<a.length;m++){let h=a[m];o.append(h)}let f=null;if(cE(l))if(c)if(o!==null)l.insertAfter(o);else for(let m=a.length-1;m>=0;m--){let h=a[m];l.insertAfter(h)}else{let m=l.getFirstChild();if(lr(m)&&(l=m),m===null)if(o)l.append(o);else for(let h=0;h<a.length;h++){let g=a[h];l.append(g),f=g}else if(o!==null)m.insertBefore(o);else for(let h=0;h<a.length;h++){let g=a[h];m.insertBefore(g),f=g}}else if(o)l.insertAfter(o);else for(let m=a.length-1;m>=0;m--){let h=a[m];l.insertAfter(h),f=h}let p=$4();jt(p)&&idt(p.anchor)&&idt(p.focus)?uE(p.clone()):f!==null?f.selectEnd():t.dirty=!0}function fdt(t){let e=t.anchor.getNode(),n=o1(e)?e:e.getParentOrThrow(),r=K7().getElementByKey(n.getKey());if(r===null)return!1;let o=r.ownerDocument.defaultView;return o===null?!1:o.getComputedStyle(r).writingMode==="vertical-rl"}function dJt(t,e){let n=fdt(t)?!e:e;qTe(t)&&(n=!n);let r=r1(t.focus,n?"previous":"next");if(Ict(r))return!1;for(let o of vct(r)){if(F4(o))return!o.origin.isInline();if(!lr(o.origin)){if(G7(o.origin))return!0;break}}return!1}function pdt(t,e,n,r){t.modify(e?"extend":"move",n,r)}function qTe(t){let e=t.anchor.getNode();return(o1(e)?e:e.getParentOrThrow()).getDirection()==="rtl"}function fJt(t,e,n){let r=qTe(t),o;o=fdt(t)||r?!n:n,pdt(t,e,o,"character")}function pJt(t,e,n){let r=EJ(t.getStyle());return r!==null&&r[e]||n}function mJt(t,e,n=""){let r=null,o=t.getNodes(),i=t.anchor,s=t.focus,a=t.isBackward(),l=a?s.offset:i.offset,c=a?s.getNode():i.getNode();if(jt(t)&&t.isCollapsed()&&t.style!==""){let u=EJ(t.style);if(u!==null&&e in u)return u[e]}for(let u=0;u<o.length;u++){let d=o[u];if((u===0||l!==0||!d.is(c))&&Mr(d)){let f=pJt(d,e,n);if(r===null)r=f;else if(r!==f){r="";break}}}return r===null?n:r}function HTe(t,e){let n=t;for(;n!==null&&n.getParent()!==null&&!e(n);)n=n.getParentOrThrow();return e(n)?n:null}var hJt=ldt;var Gi=GTe,mdt=Gi.$addNodeStyle,Szr=Gi.$cloneWithProperties,Tzr=Gi.$copyBlockFormatIndent,Izr=Gi.$ensureForwardRangeSelection,Pzr=Gi.$forEachSelectedTextNode,Ezr=Gi.$getSelectionStyleValueForProperty,Azr=Gi.$isAtNodeEnd,kzr=Gi.$isParentElementRTL,Mzr=Gi.$moveCaretSelection,YTe=Gi.$moveCharacter,Nzr=Gi.$patchStyleText,Ozr=Gi.$selectAll,Rzr=Gi.$setBlocksType,ZTe=Gi.$shouldOverrideDefaultCharacterSelection,AJ=Gi.$sliceSelectedTextNodeContent,Lzr=Gi.$trimTextContentFromAnchor,Dzr=Gi.$wrapNodes,$zr=Gi.createDOMRange,hdt=Gi.createRectsFromDOMRange,Fzr=Gi.getCSSFromStyleObject,Uzr=Gi.getStyleObjectFromCSS,Bzr=Gi.trimTextContentFromAnchor;var eIe={};zn(eIe,{$descendantsMatching:()=>eXt,$dfs:()=>$Jt,$dfsIterator:()=>Tdt,$filter:()=>YJt,$findMatchingParent:()=>Adt,$firstToLastIterator:()=>tXt,$getAdjacentCaret:()=>FJt,$getAdjacentSiblingOrParentSiblingCaret:()=>Q4,$getDepth:()=>Pdt,$getNearestBlockElementAncestorOrThrow:()=>VJt,$getNearestNodeOfType:()=>jJt,$getNextRightPreorderNode:()=>zJt,$getNextSiblingOrParentSibling:()=>BJt,$insertFirst:()=>ZJt,$insertNodeToNearestRoot:()=>KJt,$insertNodeToNearestRootAtCaret:()=>kdt,$isEditorIsNestedEditor:()=>XJt,$lastToFirstIterator:()=>QTe,$restoreEditorState:()=>HJt,$reverseDfs:()=>UJt,$reverseDfsIterator:()=>Edt,$splitNode:()=>Dct,$unwrapAndFilterDescendants:()=>QJt,$unwrapNode:()=>nXt,$wrapNodeInElement:()=>qJt,CAN_USE_BEFORE_INPUT:()=>IJt,CAN_USE_DOM:()=>Cdt,IS_ANDROID:()=>PJt,IS_ANDROID_CHROME:()=>EJt,IS_APPLE:()=>AJt,IS_APPLE_WEBKIT:()=>kJt,IS_CHROME:()=>MJt,IS_FIREFOX:()=>_dt,IS_IOS:()=>NJt,IS_SAFARI:()=>OJt,addClassNamesToElement:()=>RJt,calculateZoomLevel:()=>JJt,isBlockDomNode:()=>put,isHTMLAnchorElement:()=>mut,isHTMLElement:()=>nJ,isInlineDomNode:()=>j4,isMimeType:()=>Sdt,makeStateWrapper:()=>rXt,markSelection:()=>bdt,mediaFileReader:()=>DJt,mergeRegister:()=>vdt,objectKlassEquals:()=>GJt,positionNodeOnRange:()=>xdt,registerNestedElementResolver:()=>WJt,removeClassNamesFromElement:()=>LJt,selectionAlwaysOnDisplay:()=>TJt});function kJ(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),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.`)}var Nh=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,gJt=Nh&&"documentMode"in document?document.documentMode:null,yJt=Nh&&/Mac|iPod|iPhone|iPad/.test(navigator.platform),wJt=Nh&&/^(?!.*Seamonkey)(?=.*Firefox).*/i.test(navigator.userAgent),vJt=!(!Nh||!("InputEvent"in window)||gJt)&&"getTargetRanges"in new window.InputEvent("input"),xJt=Nh&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),bJt=Nh&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,ydt=Nh&&/Android/.test(navigator.userAgent),XTe=Nh&&/^(?=.*Chrome).*/i.test(navigator.userAgent),CJt=Nh&&ydt&&XTe,_Jt=Nh&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!XTe;function wdt(...t){let e=[];for(let n of t)if(n&&typeof n=="string")for(let[r]of n.matchAll(/\S+/g))e.push(r);return e}function vdt(...t){return()=>{for(let e=t.length-1;e>=0;e--)t[e]();t.length=0}}function Ly(t){return`${t}px`}var SJt={attributes:!0,characterData:!0,childList:!0,subtree:!0};function xdt(t,e,n){let r=null,o=null,i=null,s=[],a=document.createElement("div");function l(){r===null&&kJ(182),o===null&&kJ(183);let{left:d,top:f}=o.getBoundingClientRect(),p=hdt(t,e);var m,h;a.isConnected||(h=a,(m=o).insertBefore(h,m.firstChild));let g=!1;for(let y=0;y<p.length;y++){let w=p[y],v=s[y]||document.createElement("div"),x=v.style;x.position!=="absolute"&&(x.position="absolute",g=!0);let b=Ly(w.left-d);x.left!==b&&(x.left=b,g=!0);let _=Ly(w.top-f);x.top!==_&&(v.style.top=_,g=!0);let T=Ly(w.width);x.width!==T&&(v.style.width=T,g=!0);let S=Ly(w.height);x.height!==S&&(v.style.height=S,g=!0),v.parentNode!==a&&(a.append(v),g=!0),s[y]=v}for(;s.length>p.length;)s.pop();g&&n(s)}function c(){o=null,r=null,i!==null&&i.disconnect(),i=null,a.remove();for(let d of s)d.remove();s=[]}a.style.position="relative";let u=t.registerRootListener(function d(){let f=t.getRootElement();if(f===null)return c();let p=f.parentElement;if(!nJ(p))return c();c(),r=f,o=p,i=new MutationObserver(m=>{let h=t.getRootElement(),g=h&&h.parentElement;if(h!==r||g!==o)return d();for(let y of m)if(!a.contains(y.target))return l()}),i.observe(p,SJt),l()});return()=>{u(),c()}}function gdt(t,e,n){if(t.type!=="text"&&lr(e)){let r=e.getDOMSlot(n);return[r.element,r.getFirstChildOffset()+t.offset]}return[dut(n)||n,t.offset]}function bdt(t,e){let n=null,r=null,o=null,i=null,s=null,a=null,l=()=>{};function c(u){u.read(()=>{let d=gn();if(!jt(d))return n=null,o=null,i=null,a=null,l(),void(l=()=>{});let[f,p]=function(S){let P=S.getStartEndPoints();return S.isBackward()?[P[1],P[0]]:P}(d),m=f.getNode(),h=m.getKey(),g=f.offset,y=p.getNode(),w=y.getKey(),v=p.offset,x=t.getElementByKey(h),b=t.getElementByKey(w),_=n===null||x!==r||g!==o||h!==n.getKey(),T=i===null||b!==s||v!==a||w!==i.getKey();if((_||T)&&x!==null&&b!==null){let S=function(P,A,O,D,$,B,W){let F=(P._window?P._window.document:document).createRange();return F.setStart(...gdt(A,O,D)),F.setEnd(...gdt($,B,W)),F}(t,f,m,x,p,y,b);l(),l=xdt(t,S,P=>{if(e===void 0)for(let A of P){let O=A.style;O.background!=="Highlight"&&(O.background="Highlight"),O.color!=="HighlightText"&&(O.color="HighlightText"),O.marginTop!==Ly(-1.5)&&(O.marginTop=Ly(-1.5)),O.paddingTop!==Ly(4)&&(O.paddingTop=Ly(4)),O.paddingBottom!==Ly(0)&&(O.paddingBottom=Ly(0))}else e(P)})}n=m,r=x,o=g,i=y,s=b,a=v})}return c(t.getEditorState()),vdt(t.registerUpdateListener(({editorState:u})=>c(u)),()=>{l()})}function TJt(t){let e=null,n=()=>{let r=getSelection(),o=r&&r.anchorNode,i=t.getRootElement();o!==null&&i!==null&&i.contains(o)?e!==null&&(e(),e=null):e===null&&(e=bdt(t))};return document.addEventListener("selectionchange",n),()=>{e!==null&&e(),document.removeEventListener("selectionchange",n)}}var IJt=vJt,Cdt=Nh,PJt=ydt,EJt=CJt,AJt=yJt,kJt=_Jt,MJt=XTe,_dt=wJt,NJt=bJt,OJt=xJt;function RJt(t,...e){let n=wdt(...e);n.length>0&&t.classList.add(...n)}function LJt(t,...e){let n=wdt(...e);n.length>0&&t.classList.remove(...n)}function Sdt(t,e){for(let n of e)if(t.type.startsWith(n))return!0;return!1}function DJt(t,e){let n=t[Symbol.iterator]();return new Promise((r,o)=>{let i=[],s=()=>{let{done:a,value:l}=n.next();if(a)return r(i);let c=new FileReader;c.addEventListener("error",o),c.addEventListener("load",()=>{let u=c.result;typeof u=="string"&&i.push({file:l,result:u}),s()}),Sdt(l,e)?c.readAsDataURL(l):s()};s()})}function $Jt(t,e){return Array.from(Tdt(t,e))}function FJt(t){return t?t.getAdjacentCaret():null}function UJt(t,e){return Array.from(Edt(t,e))}function Tdt(t,e){return Idt("next",t,e)}function Idt(t,e,n){let r=mr(),o=e||r,i=lr(o)?oS(o,t):ux(o,t),s=Pdt(o),a=n?D4(vTe(ux(n,t))):function(c,u){let d=Q4(ux(c,u));return d&&d[0]}(o,t),l=s;return TTe({hasNext:c=>c!==null,initial:i,map:c=>({depth:l,node:c.origin}),step:c=>{if(c.isSameNodeCaret(a))return null;F4(c)&&l++;let u=Q4(c);return!u||u[0].isSameNodeCaret(a)?null:(l+=u[1],u[0])}})}function BJt(t){let e=Q4(ux(t,"next"));return e&&[e[0].origin,e[1]]}function Pdt(t){let e=-1;for(let n=t;n!==null;n=n.getParent())e++;return e}function zJt(t){let e=Q4(vTe(ux(t,"previous")),"root");return e&&e[0].origin}function Edt(t,e){return Idt("previous",t,e)}function jJt(t,e){let n=t;for(;n!=null;){if(n instanceof e)return n;n=n.getParent()}return null}function VJt(t){let e=Adt(t,n=>lr(n)&&!n.isInline());return lr(e)||kJ(4,t.__key),e}var Adt=(t,e)=>{let n=t;for(;n!==mr()&&n!=null;){if(e(n))return n;n=n.getParent()}return null};function WJt(t,e,n,r){let o=i=>i instanceof e;return t.registerNodeTransform(e,i=>{let s=(a=>{let l=a.getChildren();for(let d=0;d<l.length;d++){let f=l[d];if(o(f))return null}let c=a,u=a;for(;c!==null;)if(u=c,c=c.getParent(),o(c))return{child:u,parent:c};return null})(i);if(s!==null){let{child:a,parent:l}=s;if(a.is(i)){r(l,i);let c=a.getNextSiblings(),u=c.length;if(l.insertAfter(a),u!==0){let d=n(l);a.insertAfter(d);for(let f=0;f<u;f++)d.append(c[f])}l.canBeEmpty()||l.getChildrenSize()!==0||l.remove()}}})}function HJt(t,e){let n=new Map,r=t._pendingEditorState;for(let[i,s]of e._nodeMap)n.set(i,rS(s));r&&(r._nodeMap=n),t._dirtyType=2;let o=e._selection;uE(o===null?null:o.clone())}function KJt(t){let e=gn()||$4(),n;if(jt(e))n=r1(e.focus,"next");else{if(e!=null){let s=e.getNodes(),a=s[s.length-1];a&&(n=ux(a,"next"))}n=n||oS(mr(),"previous").getFlipped().insert(cx())}let r=kdt(t,n),o=D4(r),i=F4(o)?kct(o):r;return Oct(Cct(i)),t.getLatest()}function kdt(t,e,n){let r=wTe(e,"next");for(let o=r;o;o=Lct(o,n))r=o;return Y7(r)&&kJ(283),r.insert(t.isInline()?cx().append(t):t),wTe(ux(t.getLatest(),"next"),e.direction)}function qJt(t,e){let n=e();return t.replace(n),n.append(t),n}function GJt(t,e){return t!==null&&Object.getPrototypeOf(t).constructor.name===e.name}function YJt(t,e){let n=[];for(let r=0;r<t.length;r++){let o=e(t[r]);o!==null&&n.push(o)}return n}function ZJt(t,e){oS(t,"next").insert(e)}var JTe=!(_dt||!Cdt)&&void 0;function JJt(t){let e=1;if(function(){if(JTe===void 0){let n=document.createElement("div");n.style.cssText="position: absolute; opacity: 0; width: 100px; left: -1000px;",document.body.appendChild(n);let r=n.getBoundingClientRect();n.style.setProperty("zoom","2"),JTe=n.getBoundingClientRect().width===r.width,document.body.removeChild(n)}return JTe}())for(;t;)e*=Number(window.getComputedStyle(t).getPropertyValue("zoom")),t=t.parentElement;return e}function XJt(t){return t._parentEditor!==null}function QJt(t,e){return Mdt(t,e,null)}function Mdt(t,e,n){let r=!1;for(let o of QTe(t))e(o)?n!==null&&n(o):(r=!0,lr(o)&&Mdt(o,e,n||(i=>o.insertAfter(i))),o.remove());return r}function eXt(t,e){let n=[],r=Array.from(t).reverse();for(let o=r.pop();o!==void 0;o=r.pop())if(e(o))n.push(o);else if(lr(o))for(let i of QTe(o))r.push(i);return n}function tXt(t){return Ndt(oS(t,"next"))}function QTe(t){return Ndt(oS(t,"previous"))}function Ndt(t){return TTe({hasNext:Act,initial:t.getAdjacentCaret(),map:e=>e.origin.getLatest(),step:e=>e.getAdjacentCaret()})}function nXt(t){Nct(ux(t,"next")).splice(1,t.getChildren())}function Q4(t,e="root"){let n=0,r=t,o=D4(r);for(;o===null;){if(n--,o=r.getParentCaret(e),!o)return null;r=o,o=D4(r)}return o&&[o,n]}function rXt(t){let e=r=>Sct(r,t),n=(r,o)=>Rct(r,t,o);return{$get:e,$set:n,accessors:[e,n],makeGetterMethod:()=>function(){return e(this)},makeSetterMethod:()=>function(r){return n(this,r)},stateConfig:t}}var bn=eIe,Hzr=bn.$descendantsMatching,Kzr=bn.$dfs,qzr=bn.$dfsIterator,Gzr=bn.$filter,Yzr=bn.$findMatchingParent,Zzr=bn.$firstToLastIterator,Jzr=bn.$getAdjacentCaret,Xzr=bn.$getAdjacentSiblingOrParentSiblingCaret,Qzr=bn.$getDepth,ejr=bn.$getNearestBlockElementAncestorOrThrow,tjr=bn.$getNearestNodeOfType,njr=bn.$getNextRightPreorderNode,rjr=bn.$getNextSiblingOrParentSibling,ojr=bn.$insertFirst,ijr=bn.$insertNodeToNearestRoot,sjr=bn.$insertNodeToNearestRootAtCaret,ajr=bn.$isEditorIsNestedEditor,ljr=bn.$lastToFirstIterator,cjr=bn.$restoreEditorState,ujr=bn.$reverseDfs,djr=bn.$reverseDfsIterator,fjr=bn.$splitNode,pjr=bn.$unwrapAndFilterDescendants,mjr=bn.$unwrapNode,hjr=bn.$wrapNodeInElement,gjr=bn.CAN_USE_BEFORE_INPUT,yjr=bn.CAN_USE_DOM,wjr=bn.IS_ANDROID,vjr=bn.IS_ANDROID_CHROME,xjr=bn.IS_APPLE,bjr=bn.IS_APPLE_WEBKIT,Cjr=bn.IS_CHROME,_jr=bn.IS_FIREFOX,Sjr=bn.IS_IOS,Tjr=bn.IS_SAFARI,Ijr=bn.addClassNamesToElement,Pjr=bn.calculateZoomLevel,tIe=bn.isBlockDomNode,Ejr=bn.isHTMLAnchorElement,Odt=bn.isHTMLElement,Ajr=bn.isInlineDomNode,kjr=bn.isMimeType,Mjr=bn.makeStateWrapper,Njr=bn.markSelection,Ojr=bn.mediaFileReader,mx=bn.mergeRegister,eV=bn.objectKlassEquals,Rjr=bn.positionNodeOnRange,Ljr=bn.registerNestedElementResolver,Djr=bn.removeClassNamesFromElement,$jr=bn.selectionAlwaysOnDisplay;var nIe={};zn(nIe,{registerDragonSupport:()=>oXt});function oXt(t){let e=window.location.origin,n=r=>{if(r.origin!==e)return;let o=t.getRootElement();if(document.activeElement!==o)return;let i=r.data;if(typeof i=="string"){let s;try{s=JSON.parse(i)}catch{return}if(s&&s.protocol==="nuanria_messaging"&&s.type==="request"){let a=s.payload;if(a&&a.functionId==="makeChanges"){let l=a.args;if(l){let[c,u,d,f,p,m]=l;t.update(()=>{let h=gn();if(jt(h)){let g=h.anchor,y=g.getNode(),w=0,v=0;if(Mr(y)&&c>=0&&u>=0&&(w=c,v=c+u,h.setTextNodeRange(y,w,y,v)),w===v&&d===""||(h.insertRawText(d),y=g.getNode()),Mr(y)){w=f,v=f+p;let x=y.getTextContentSize();w=w>x?x:w,v=v>x?x:v,h.setTextNodeRange(y,w,y,v)}r.stopImmediatePropagation()}})}}}}};return window.addEventListener("message",n,!0),()=>{window.removeEventListener("message",n,!0)}}var iXt=nIe,Rdt=iXt.registerDragonSupport;var rIe={};zn(rIe,{$generateHtmlFromNodes:()=>aXt,$generateNodesFromDOM:()=>sXt});function sXt(t,e){let n=e.body?e.body.childNodes:[],r=[],o=[];for(let i=0;i<n.length;i++){let s=n[i];if(!Ddt.has(s.nodeName)){let a=$dt(s,t,o,!1);a!==null&&(r=r.concat(a))}}return function(i){for(let s of i)s.getNextSibling()instanceof bTe&&s.insertAfter(yTe());for(let s of i){let a=s.getChildren();for(let l of a)s.insertBefore(l);s.remove()}}(o),r}function aXt(t,e){if(typeof document>"u"||typeof window>"u"&&window.window===void 0)throw new Error("To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom before calling this function.");let n=document.createElement("div"),r=mr().getChildren();for(let o=0;o<r.length;o++)Ldt(t,r[o],n,e);return n.innerHTML}function Ldt(t,e,n,r=null){let o=r===null||e.isSelected(r),i=lr(e)&&e.excludeFromCopy("html"),s=e;if(r!==null){let p=rS(e);p=Mr(p)&&r!==null?AJ(r,p):p,s=p}let a=lr(s)?s.getChildren():[],l=fut(t,s.getType()),c;c=l&&l.exportDOM!==void 0?l.exportDOM(t,s):s.exportDOM(t);let{element:u,after:d}=c;if(!u)return!1;let f=document.createDocumentFragment();for(let p=0;p<a.length;p++){let m=a[p],h=Ldt(t,m,f,r);!o&&lr(e)&&h&&e.extractWithChild(m,r,"html")&&(o=!0)}if(o&&!i){if((Odt(u)||STe(u))&&u.append(f),n.append(u),d){let p=d.call(s,u);p&&(STe(u)?u.replaceChildren(p):u.replaceWith(p))}}else n.append(f);return o}var Ddt=new Set(["STYLE","SCRIPT"]);function $dt(t,e,n,r,o=new Map,i){let s=[];if(Ddt.has(t.nodeName))return s;let a=null,l=function(m,h){let{nodeName:g}=m,y=h._htmlConversions.get(g.toLowerCase()),w=null;if(y!==void 0)for(let v of y){let x=v(m);x!==null&&(w===null||(w.priority||0)<=(x.priority||0))&&(w=x)}return w!==null?w.conversion:null}(t,e),c=l?l(t):null,u=null;if(c!==null){u=c.after;let m=c.node;if(a=Array.isArray(m)?m[m.length-1]:m,a!==null){for(let[,h]of o)if(a=h(a,i),!a)break;a&&s.push(...Array.isArray(m)?m:[a])}c.forChild!=null&&o.set(t.nodeName,c.forChild)}let d=t.childNodes,f=[],p=(a==null||!cE(a))&&(a!=null&&q7(a)||r);for(let m=0;m<d.length;m++)f.push(...$dt(d[m],e,n,p,new Map(o),a));return u!=null&&(f=u(f)),tIe(t)&&(f=lXt(t,f,p?()=>{let m=new bTe;return n.push(m),m}:cx)),a==null?f.length>0?s=s.concat(f):tIe(t)&&function(m){return m.nextSibling==null||m.previousSibling==null?!1:j4(m.nextSibling)&&j4(m.previousSibling)}(t)&&(s=s.concat(yTe())):lr(a)&&a.append(...f),s}function lXt(t,e,n){let r=t.style.textAlign,o=[],i=[];for(let s=0;s<e.length;s++){let a=e[s];if(q7(a))r&&!a.getFormat()&&a.setFormat(r),o.push(a);else if(i.push(a),s===e.length-1||s<e.length-1&&q7(e[s+1])){let l=n();l.setFormat(r),l.append(...i),o.push(l),i=[]}}return o}var Fdt=rIe,Udt=Fdt.$generateHtmlFromNodes,Bdt=Fdt.$generateNodesFromDOM;var iIe={};zn(iIe,{$generateJSONFromSelectedNodes:()=>Hdt,$generateNodesFromSerializedNodes:()=>Kdt,$getClipboardDataFromSelection:()=>qdt,$getHtmlContent:()=>jdt,$getLexicalContent:()=>Vdt,$insertDataTransferForPlainText:()=>cXt,$insertDataTransferForRichText:()=>uXt,$insertGeneratedNodes:()=>oIe,copyToClipboard:()=>dXt,setLexicalClipboardDataTransfer:()=>Gdt});function MJ(t,...e){let n=new URL("https://lexical.dev/docs/error"),r=new URLSearchParams;r.append("code",t);for(let o of e)r.append("v",o);throw n.search=r.toString(),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 jdt(t,e=gn()){return e==null&&MJ(166),jt(e)&&e.isCollapsed()||e.getNodes().length===0?"":Udt(t,e)}function Vdt(t,e=gn()){return e==null&&MJ(166),jt(e)&&e.isCollapsed()||e.getNodes().length===0?null:JSON.stringify(Hdt(t,e))}function cXt(t,e){let n=t.getData("text/plain")||t.getData("text/uri-list");n!=null&&e.insertRawText(n)}function uXt(t,e,n){let r=t.getData("application/x-lexical-editor");if(r)try{let a=JSON.parse(r);if(a.namespace===n._config.namespace&&Array.isArray(a.nodes))return oIe(n,Kdt(a.nodes),e)}catch{}let o=t.getData("text/html"),i=t.getData("text/plain");if(o&&i!==o)try{let a=new DOMParser().parseFromString(function(l){return window.trustedTypes&&window.trustedTypes.createPolicy?window.trustedTypes.createPolicy("lexical",{createHTML:c=>c}).createHTML(l):l}(o),"text/html");return oIe(n,Bdt(n,a),e)}catch{}let s=i||t.getData("text/uri-list");if(s!=null)if(jt(e)){let a=s.split(/(\r?\n|\t)/);a[a.length-1]===""&&a.pop();for(let l=0;l<a.length;l++){let c=gn();if(jt(c)){let u=a[l];u===`
`||u===`\r
`?c.insertParagraph():u==="	"?c.insertNodes([wct()]):c.insertText(u)}}}else e.insertRawText(s)}function oIe(t,e,n){t.dispatchCommand(sut,{nodes:e,selection:n})||(n.insertNodes(e),function(r){if(jt(r)&&r.isCollapsed()){let o=r.anchor,i=null,s=r1(o,"previous");if(s)if(Y7(s))i=s.origin;else{let a=xct(s,oS(mr(),"next").getFlipped());for(let l of a){if(Mr(l.origin)){i=l.origin;break}if(lr(l.origin)&&!l.origin.isInline())break}}if(i&&Mr(i)){let a=i.getFormat(),l=i.getStyle();r.format===a&&r.style===l||(r.format=a,r.style=l,r.dirty=!0)}}}(n))}function Wdt(t,e,n,r=[]){let o=e===null||n.isSelected(e),i=lr(n)&&n.excludeFromCopy("html"),s=n;if(e!==null){let c=rS(n);c=Mr(c)&&e!==null?AJ(e,c):c,s=c}let a=lr(s)?s.getChildren():[],l=function(c){let u=c.exportJSON(),d=c.constructor;if(u.type!==d.getType()&&MJ(58,d.name),lr(c)){let f=u.children;Array.isArray(f)||MJ(59,d.name)}return u}(s);if(Mr(s)){let c=s.__text;c.length>0?l.text=c:o=!1}for(let c=0;c<a.length;c++){let u=a[c],d=Wdt(t,e,u,l.children);!o&&lr(n)&&d&&n.extractWithChild(u,e,"clone")&&(o=!0)}if(o&&!i)r.push(l);else if(Array.isArray(l.children))for(let c=0;c<l.children.length;c++){let u=l.children[c];r.push(u)}return o}function Hdt(t,e){let n=[],r=mr().getChildren();for(let o=0;o<r.length;o++)Wdt(t,e,r[o],n);return{namespace:t._config.namespace,nodes:n}}function Kdt(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n],o=Mct(r);Mr(o)&&mdt(o),e.push(o)}return e}var f1=null;async function dXt(t,e,n){if(f1!==null)return!1;if(e!==null)return new Promise((c,u)=>{t.update(()=>{c(zdt(t,e,n))})});let r=t.getRootElement(),o=t._window||window,i=window.document,s=_Te(o);if(r===null||s===null)return!1;let a=i.createElement("span");a.style.cssText="position: fixed; top: -1000px;",a.append(i.createTextNode("#")),r.append(a);let l=new Range;return l.setStart(a,0),l.setEnd(a,1),s.removeAllRanges(),s.addRange(l),new Promise((c,u)=>{let d=t.registerCommand(X7,f=>(eV(f,ClipboardEvent)&&(d(),f1!==null&&(window.clearTimeout(f1),f1=null),c(zdt(t,f,n))),!0),J7);f1=window.setTimeout(()=>{d(),f1=null,c(!1)},50),i.execCommand("copy"),a.remove()})}function zdt(t,e,n){if(n===void 0){let o=_Te(t._window);if(!o)return!1;let i=o.anchorNode,s=o.focusNode;if(i!==null&&s!==null&&!hut(t,i,s))return!1;let a=gn();if(a===null)return!1;n=qdt(a)}e.preventDefault();let r=e.clipboardData;return r!==null&&(Gdt(r,n),!0)}var fXt=[["text/html",jdt],["application/x-lexical-editor",Vdt]];function qdt(t=gn()){let e={"text/plain":t?t.getTextContent():""};if(t){let n=K7();for(let[r,o]of fXt){let i=o(n,t);i!==null&&(e[r]=i)}}return e}function Gdt(t,e){for(let n in e){let r=e[n];r!==void 0&&t.setData(n,r)}}var Dy=iIe,Yjr=Dy.$generateJSONFromSelectedNodes,Zjr=Dy.$generateNodesFromSerializedNodes,Jjr=Dy.$getClipboardDataFromSelection,Ydt=Dy.$getHtmlContent,Xjr=Dy.$getLexicalContent,sIe=Dy.$insertDataTransferForPlainText,Qjr=Dy.$insertDataTransferForRichText,e4r=Dy.$insertGeneratedNodes,t4r=Dy.copyToClipboard,n4r=Dy.setLexicalClipboardDataTransfer;var aIe={};zn(aIe,{registerPlainText:()=>wXt});var p1=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,pXt=p1&&"documentMode"in document?document.documentMode:null,mXt=!(!p1||!("InputEvent"in window)||pXt)&&"getTargetRanges"in new window.InputEvent("input"),hXt=p1&&/Version\/[\d.]+.*Safari/.test(navigator.userAgent),Zdt=p1&&/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream,gXt=p1&&/^(?=.*Chrome).*/i.test(navigator.userAgent),yXt=p1&&/AppleWebKit\/[\d.]+/.test(navigator.userAgent)&&!gXt;function Jdt(t,e){e.update(()=>{if(t!==null){let n=eV(t,KeyboardEvent)?null:t.clipboardData,r=gn();if(r!==null&&n!=null){t.preventDefault();let o=Ydt(e);o!==null&&n.setData("text/html",o),n.setData("text/plain",r.getTextContent())}}})}function wXt(t){return mx(t.registerCommand(i1,e=>{let n=gn();return!!jt(n)&&(n.deleteCharacter(e),!0)},zo),t.registerCommand(Wct,e=>{let n=gn();return!!jt(n)&&(n.deleteWord(e),!0)},zo),t.registerCommand(Vct,e=>{let n=gn();return!!jt(n)&&(n.deleteLine(e),!0)},zo),t.registerCommand(zct,e=>{let n=gn();if(!jt(n))return!1;if(typeof e=="string")n.insertText(e);else{let r=e.dataTransfer;if(r!=null)sIe(r,n);else{let o=e.data;o&&n.insertText(o)}}return!0},zo),t.registerCommand(iut,()=>{let e=gn();return!!jt(e)&&(e.removeText(),!0)},zo),t.registerCommand(CTe,e=>{let n=gn();return!!jt(n)&&(n.insertLineBreak(e),!0)},zo),t.registerCommand(Gct,()=>{let e=gn();return!!jt(e)&&(e.insertLineBreak(),!0)},zo),t.registerCommand(Zct,e=>{let n=gn();if(!jt(n))return!1;let r=e,o=r.shiftKey;return!!ZTe(n,!0)&&(r.preventDefault(),YTe(n,o,!0),!0)},zo),t.registerCommand(Jct,e=>{let n=gn();if(!jt(n))return!1;let r=e,o=r.shiftKey;return!!ZTe(n,!1)&&(r.preventDefault(),YTe(n,o,!1),!0)},zo),t.registerCommand(Qct,e=>{let n=gn();return!!jt(n)&&(!Zdt||navigator.language!=="ko-KR")&&(e.preventDefault(),t.dispatchCommand(i1,!0))},zo),t.registerCommand(eut,e=>{let n=gn();return!!jt(n)&&(e.preventDefault(),t.dispatchCommand(i1,!1))},zo),t.registerCommand(a1,e=>{let n=gn();if(!jt(n))return!1;if(e!==null){if((Zdt||hXt||yXt)&&mXt)return!1;e.preventDefault()}return t.dispatchCommand(CTe,!1)},zo),t.registerCommand(aut,()=>(Z7(),!0),zo),t.registerCommand(X7,e=>{let n=gn();return!!jt(n)&&(Jdt(e,t),!0)},zo),t.registerCommand(jct,e=>{let n=gn();return!!jt(n)&&(function(r,o){Jdt(r,o),o.update(()=>{let i=gn();jt(i)&&i.removeText()})}(e,t),!0)},zo),t.registerCommand(tJ,e=>{let n=gn();return!!jt(n)&&(function(r,o){r.preventDefault(),o.update(()=>{let i=gn(),s=eV(r,ClipboardEvent)?r.clipboardData:null;s!=null&&jt(i)&&sIe(s,i)},{tag:rut})}(e,t),!0)},zo),t.registerCommand(Kct,e=>{let n=gn();return!!jt(n)&&(e.preventDefault(),!0)},zo),t.registerCommand(Hct,e=>{let n=gn();return!!jt(n)&&(e.preventDefault(),!0)},zo))}var vXt=aIe,Xdt=vXt.registerPlainText;var cIe={};zn(cIe,{PlainTextPlugin:()=>xXt});var nm=N(U(),1),NJ=N(yo(),1),dS=N(Ve(),1);var lIe=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0?nm.useLayoutEffect:nm.useEffect;function Qdt(t){return t.getEditorState().read(IJ(t.isComposing()))}function xXt({contentEditable:t,placeholder:e=null,ErrorBoundary:n}){let[r]=vr(),o=function(i,s){let[a,l]=(0,nm.useState)(()=>i.getDecorators());return lIe(()=>i.registerDecoratorListener(c=>{(0,NJ.flushSync)(()=>{l(c)})}),[i]),(0,nm.useEffect)(()=>{l(i.getDecorators())},[i]),(0,nm.useMemo)(()=>{let c=[],u=Object.keys(a);for(let d=0;d<u.length;d++){let f=u[d],p=(0,dS.jsx)(s,{onError:h=>i._onError(h),children:(0,dS.jsx)(nm.Suspense,{fallback:null,children:a[f]})}),m=i.getElementByKey(f);m!==null&&c.push((0,NJ.createPortal)(p,m,f))}return c},[s,a,i])}(r,n);return function(i){lIe(()=>mx(Xdt(i),Rdt(i)),[i])}(r),(0,dS.jsxs)(dS.Fragment,{children:[t,(0,dS.jsx)(bXt,{content:e}),o]})}function bXt({content:t}){let[e]=vr(),n=function(o){let[i,s]=(0,nm.useState)(()=>Qdt(o));return lIe(()=>{function a(){let l=Qdt(o);s(l)}return a(),mx(o.registerUpdateListener(()=>{a()}),o.registerEditableListener(()=>{a()}))},[o]),i}(e),r=edt();return n?typeof t=="function"?t(r):t:null}var CXt=cIe,OJ=CXt.PlainTextPlugin;var uIe={};zn(uIe,{ContentEditable:()=>SXt,ContentEditableElement:()=>nft});var Cc=N(U(),1),hx=N(Ve(),1);var tft=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0?Cc.useLayoutEffect:Cc.useEffect;function _Xt({editor:t,ariaActiveDescendant:e,ariaAutoComplete:n,ariaControls:r,ariaDescribedBy:o,ariaErrorMessage:i,ariaExpanded:s,ariaInvalid:a,ariaLabel:l,ariaLabelledBy:c,ariaMultiline:u,ariaOwns:d,ariaRequired:f,autoCapitalize:p,className:m,id:h,role:g="textbox",spellCheck:y=!0,style:w,tabIndex:v,"data-testid":x,...b},_){let[T,S]=(0,Cc.useState)(t.isEditable()),P=(0,Cc.useCallback)(O=>{O&&O.ownerDocument&&O.ownerDocument.defaultView?t.setRootElement(O):t.setRootElement(null)},[t]),A=(0,Cc.useMemo)(()=>function(...O){return D=>{O.forEach($=>{typeof $=="function"?$(D):$!=null&&($.current=D)})}}(_,P),[P,_]);return tft(()=>(S(t.isEditable()),t.registerEditableListener(O=>{S(O)})),[t]),(0,hx.jsx)("div",{"aria-activedescendant":T?e:void 0,"aria-autocomplete":T?n:"none","aria-controls":T?r:void 0,"aria-describedby":o,...i!=null?{"aria-errormessage":i}:{},"aria-expanded":T&&g==="combobox"?!!s:void 0,...a!=null?{"aria-invalid":a}:{},"aria-label":l,"aria-labelledby":c,"aria-multiline":u,"aria-owns":T?d:void 0,"aria-readonly":!T||void 0,"aria-required":f,autoCapitalize:p,className:m,contentEditable:T,"data-testid":x,id:h,ref:A,role:g,spellCheck:y,style:w,tabIndex:v,...b})}var nft=(0,Cc.forwardRef)(_Xt);function eft(t){return t.getEditorState().read(IJ(t.isComposing()))}var SXt=(0,Cc.forwardRef)(TXt);function TXt(t,e){let{placeholder:n,...r}=t,[o]=vr();return(0,hx.jsxs)(hx.Fragment,{children:[(0,hx.jsx)(nft,{editor:o,...r,ref:e}),n!=null&&(0,hx.jsx)(IXt,{editor:o,content:n})]})}function IXt({content:t,editor:e}){let n=function(s){let[a,l]=(0,Cc.useState)(()=>eft(s));return tft(()=>{function c(){let u=eft(s);l(u)}return c(),mx(s.registerUpdateListener(()=>{c()}),s.registerEditableListener(()=>{c()}))},[s]),a}(e),[r,o]=(0,Cc.useState)(e.isEditable());if((0,Cc.useLayoutEffect)(()=>(o(e.isEditable()),e.registerEditableListener(s=>{o(s)})),[e]),!n)return null;let i=null;return typeof t=="function"?i=t(r):t!==null&&(i=t),i===null?null:(0,hx.jsx)("div",{"aria-hidden":!0,children:i})}var rft=uIe,RJ=rft.ContentEditable,v4r=rft.ContentEditableElement;var pIe={};zn(pIe,{createEmptyHistoryState:()=>OXt,registerHistory:()=>NXt});var LJ=0,dIe=1,fIe=2,Oh=0,PXt=1,oft=2,EXt=3,AXt=4;function kXt(t,e,n,r,o){if(t===null||n.size===0&&r.size===0&&!o)return Oh;let i=e._selection,s=t._selection;if(o)return PXt;if(!(jt(i)&&jt(s)&&s.isCollapsed()&&i.isCollapsed()))return Oh;let a=function(y,w,v){let x=y._nodeMap,b=[];for(let _ of w){let T=x.get(_);T!==void 0&&b.push(T)}for(let[_,T]of v){if(!T)continue;let S=x.get(_);S===void 0||o1(S)||b.push(S)}return b}(e,n,r);if(a.length===0)return Oh;if(a.length>1){let y=e._nodeMap,w=y.get(i.anchor.key),v=y.get(s.anchor.key);return w&&v&&!t._nodeMap.has(w.__key)&&Mr(w)&&w.__text.length===1&&i.anchor.offset===1?oft:Oh}let l=a[0],c=t._nodeMap.get(l.__key);if(!Mr(c)||!Mr(l)||c.__mode!==l.__mode)return Oh;let u=c.__text,d=l.__text;if(u===d)return Oh;let f=i.anchor,p=s.anchor;if(f.key!==p.key||f.type!=="text")return Oh;let m=f.offset,h=p.offset,g=d.length-u.length;return g===1&&h===m-1?oft:g===-1&&h===m+1?EXt:g===-1&&h===m?AXt:Oh}function MXt(t,e){let n=Date.now(),r=Oh;return(o,i,s,a,l,c)=>{let u=Date.now();if(c.has(eJ))return r=Oh,n=u,fIe;let d=kXt(o,i,a,l,t.isComposing()),f=(()=>{let p=s===null||s.editor===t,m=c.has(qct);if(!m&&p&&c.has(s1))return LJ;if(o===null)return dIe;let h=i._selection;return a.size>0||l.size>0?m===!1&&d!==Oh&&d===r&&u<n+e&&p||a.size===1&&function(g,y,w){let v=y._nodeMap.get(g),x=w._nodeMap.get(g),b=y._selection,_=w._selection;return!(jt(b)&&jt(_)&&b.anchor.type==="element"&&b.focus.type==="element"&&_.anchor.type==="text"&&_.focus.type==="text"||!Mr(v)||!Mr(x)||v.__parent!==x.__parent)&&JSON.stringify(y.read(()=>v.exportJSON()))===JSON.stringify(w.read(()=>x.exportJSON()))}(Array.from(a)[0],o,i)?LJ:dIe:h!==null?LJ:fIe})();return n=u,r=d,f}}function ift(t){t.undoStack=[],t.redoStack=[],t.current=null}function NXt(t,e,n){let r=MXt(t,n);return mx(t.registerCommand(lut,()=>(function(i,s){let a=s.redoStack,l=s.undoStack;if(l.length!==0){let c=s.current,u=l.pop();c!==null&&(a.push(c),i.dispatchCommand(U4,!0)),l.length===0&&i.dispatchCommand(B4,!1),s.current=u||null,u&&u.editor.setEditorState(u.editorState,{tag:eJ})}}(t,e),!0),zo),t.registerCommand(out,()=>(function(i,s){let a=s.redoStack,l=s.undoStack;if(a.length!==0){let c=s.current;c!==null&&(l.push(c),i.dispatchCommand(B4,!0));let u=a.pop();a.length===0&&i.dispatchCommand(U4,!1),s.current=u||null,u&&u.editor.setEditorState(u.editorState,{tag:eJ})}}(t,e),!0),zo),t.registerCommand(Fct,()=>(ift(e),!1),zo),t.registerCommand(Uct,()=>(ift(e),t.dispatchCommand(U4,!1),t.dispatchCommand(B4,!1),!0),zo),t.registerUpdateListener(({editorState:i,prevEditorState:s,dirtyLeaves:a,dirtyElements:l,tags:c})=>{let u=e.current,d=e.redoStack,f=e.undoStack,p=u===null?null:u.editorState;if(u!==null&&i===p)return;let m=r(s,i,u,a,l,c);if(m===dIe)d.length!==0&&(e.redoStack=[],t.dispatchCommand(U4,!1)),u!==null&&(f.push({...u}),t.dispatchCommand(B4,!0));else if(m===fIe)return;e.current={editor:t,editorState:i}}))}function OXt(){return{current:null,redoStack:[],undoStack:[]}}var sft=pIe,DJ=sft.createEmptyHistoryState,aft=sft.registerHistory;var mIe={};zn(mIe,{HistoryPlugin:()=>RXt,createEmptyHistoryState:()=>DJ});var $J=N(U(),1);function RXt({delay:t,externalHistoryState:e}){let[n]=vr();return function(r,o,i=1e3){let s=(0,$J.useMemo)(()=>o||DJ(),[o]);(0,$J.useEffect)(()=>aft(r,s,i),[i,r,s])}(n,e,t),null}var lft=mIe,FJ=lft.HistoryPlugin,P4r=lft.createEmptyHistoryState;var hIe={};zn(hIe,{OnChangePlugin:()=>DXt});var UJ=N(U(),1),LXt=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0?UJ.useLayoutEffect:UJ.useEffect;function DXt({ignoreHistoryMergeTagChange:t=!0,ignoreSelectionChange:e=!1,onChange:n}){let[r]=vr();return LXt(()=>{if(n)return r.registerUpdateListener(({editorState:o,dirtyElements:i,dirtyLeaves:s,prevEditorState:a,tags:l})=>{e&&i.size===0&&s.size===0||t&&l.has(s1)||a.isEmpty()||n(o,r,l)})},[r,t,e,n]),null}var $Xt=hIe,BJ=$Xt.OnChangePlugin;var wIe={};zn(wIe,{LexicalErrorBoundary:()=>UXt});var m1=N(U(),1),gIe=N(Ve(),1);function yIe(t,e){return yIe=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,r){return n.__proto__=r,n},yIe(t,e)}var cft={error:null},FXt=function(t){var e,n;function r(){for(var i,s=arguments.length,a=new Array(s),l=0;l<s;l++)a[l]=arguments[l];return(i=t.call.apply(t,[this].concat(a))||this).state=cft,i.resetErrorBoundary=function(){for(var c,u=arguments.length,d=new Array(u),f=0;f<u;f++)d[f]=arguments[f];i.props.onReset==null||(c=i.props).onReset.apply(c,d),i.reset()},i}n=t,(e=r).prototype=Object.create(n.prototype),e.prototype.constructor=e,yIe(e,n),r.getDerivedStateFromError=function(i){return{error:i}};var o=r.prototype;return o.reset=function(){this.setState(cft)},o.componentDidCatch=function(i,s){var a,l;(a=(l=this.props).onError)==null||a.call(l,i,s)},o.componentDidUpdate=function(i,s){var a,l,c,u,d=this.state.error,f=this.props.resetKeys;d!==null&&s.error!==null&&((c=i.resetKeys)===void 0&&(c=[]),(u=f)===void 0&&(u=[]),c.length!==u.length||c.some(function(p,m){return!Object.is(p,u[m])}))&&((a=(l=this.props).onResetKeysChange)==null||a.call(l,i.resetKeys,f),this.reset())},o.render=function(){var i=this.state.error,s=this.props,a=s.fallbackRender,l=s.FallbackComponent,c=s.fallback;if(i!==null){var u={error:i,resetErrorBoundary:this.resetErrorBoundary};if(m1.isValidElement(c))return c;if(typeof a=="function")return a(u);if(l)return m1.createElement(l,u);throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop")}return this.props.children},r}(m1.Component);function UXt({children:t,onError:e}){return(0,gIe.jsx)(FXt,{fallback:(0,gIe.jsx)("div",{style:{border:"1px solid #f00",color:"#f00",padding:"8px"},children:"An error was thrown."}),onError:e,children:t})}var BXt=wIe,zJ=BXt.LexicalErrorBoundary;var Lh=N(U());var xIe=N(W4());var Rh=N(U()),dft=N(yo());function fft(t,e){let n=e.getSelection();if(n===null||!n.isCollapsed)return null;let r=n.anchorNode,o=t,i=n.anchorOffset;if(r==null||i==null)return null;let s=e.document.createRange();try{s.setStart(r,o),s.setEnd(r,i)}catch{return null}return s}var uft=400,zXt=.9;function fS({options:t,selectedIndex:e,onSelect:n,onHighlight:r,range:o,query:i,showPreview:s=!1,mode:a="search",onKeyDown:l}){let[c,u]=(0,Rh.useState)(null),d=o?.startContainer.win??window,f=(0,Rh.useCallback)(h=>{let g=Math.floor(h.innerWidth*zXt);if(t.length===0)return Math.min(uft,g);let y=Math.max(...t.map(b=>b.title.length)),w=Math.max(...t.map(b=>b.subtitle?.length||0)),v=Math.max(y*8+32,w*6+32),x=Math.min(Math.max(v,300),uft);return Math.min(x,g)},[t]),p=(0,Rh.useCallback)(()=>{if(!o)return;let h=o.startContainer.win,g=o.getBoundingClientRect(),y=f(h),w=g.top-4,v=8,x=h.innerWidth-y-8,b=Math.min(Math.max(g.left,v),x);u({top:w,left:b,width:y})},[o,f]);if((0,Rh.useEffect)(()=>{p()},[p]),(0,Rh.useEffect)(()=>{if(!o)return;let h=o.startContainer.win,g=()=>p();return h.addEventListener("resize",g),h.document.addEventListener("scroll",g,{passive:!0}),()=>{h.removeEventListener("resize",g),h.document.removeEventListener("scroll",g)}},[p,o]),!c||t.length===0)return null;let m=Rh.default.createElement("div",{className:"tw-absolute tw-z-[9999] tw-flex tw-flex-col tw-items-end",style:{bottom:`calc(100vh - ${c.top}px)`,left:c.left,width:c.width}},Rh.default.createElement(uJ,{options:t,selectedIndex:e,onSelect:n,onHighlight:r,query:i,mode:a,showPreview:s,onKeyDown:l,className:"tw-shadow-lg",width:c.width}));return(0,dft.createPortal)(m,d.document.body)}var $y=require("obsidian");ye();function jXt(t){let{type:e,title:n,data:r}=t;switch(e){case"active-note":return G4();case"notes":if(r instanceof $y.TFile&&n)return q4(n,r.path);break;case"tools":if(typeof r=="string")return hE(r);break;case"folders":if(r instanceof $y.TFolder)return Z4(r.path);break;case"webTabs":if(r&&typeof r=="object"&&"url"in r)return CJ(r.url,r.title,r.faviconUrl);break;case"activeWebTab":return bJ()}throw new Error(`Invalid pill data: ${JSON.stringify(t)}`)}function vIe(t,e,n){return{beforeText:t.slice(0,e),afterText:t.slice(n)}}function VXt(t,e,n=!0){if(e.length===1&&e[0].getType()==="text")t.replace(e[0]),n&&pft(e[0]);else{for(let r=0;r<e.length;r++)r===0?t.replace(e[r]):e[r-1].insertAfter(e[r]);if(n&&e.length>0){let r=e[e.length-1];pft(r)}}}function WXt(t,e,n,r,o){let i=o?r?" "+r:" ":r;e?(t.setTextContent(e),t.insertAfter(n),i&&n.insertAfter(vf(i))):(t.replace(n),i&&n.insertAfter(vf(i))),n.selectNext()}function pft(t){if(t.getType()==="text"){let e=t,n=e.getTextContent().length;e.select(n,n)}else{let e=t.getParent();if(e){let n=H7(),r=t.getIndexWithinParent();n.anchor.set(e.getKey(),r+1,"element"),n.focus.set(e.getKey(),r+1,"element"),uE(n)}}}var jJ=cut("INSERT_TEXT_WITH_PILLS_COMMAND");function HXt(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}function KXt(t){let e=t.startsWith("@")?t:`@${t}`;return oR.includes(e)?e:null}function qXt(t){if(!app?.vault)return null;try{let e=app.vault.getAllLoadedFiles().filter(r=>r instanceof $y.TFolder);for(let r of e)if(r.name===t)return r;for(let r of e)if(r.path===t)return r;let n=t.toLowerCase();for(let r of e)if(r.name.toLowerCase()===n||r.path.toLowerCase()===n)return r;return null}catch(e){return k("Error resolving folder reference:",e),null}}function GXt(t){if(!app?.vault||!app?.metadataCache)return null;try{let e=app.metadataCache.getFirstLinkpathDest(t,"");if(e&&e instanceof $y.TFile)return e;if(!t.endsWith(".md")){let i=app.metadataCache.getFirstLinkpathDest(t+".md","");if(i&&i instanceof $y.TFile)return i}if(!t.endsWith(".pdf")){let i=app.metadataCache.getFirstLinkpathDest(t+".pdf","");if(i&&i instanceof $y.TFile)return i}let n=app.vault.getMarkdownFiles();for(let i of n)if(i.basename===t||i.name===t)return i;let o=app.vault.getFiles().filter(i=>i instanceof $y.TFile&&i.extension==="pdf");for(let i of o)if(i.basename===t||i.name===t)return i;return null}catch(e){return k("Error resolving note reference:",e),null}}function VJ(t,e={}){let{includeNotes:n=!0,includeURLs:r=!1,includeTools:o=!1,includeCustomTemplates:i=!1}=e,s=[],a=[],l=[],c=1;if(n&&(a.push("(\\[\\[([^\\]]+)\\]\\])"),l.push({type:"notes",groupCount:2,startIndex:c}),c+=2),r&&(a.push(`(https?:\\/\\/[^\\s"'<>]+)`),l.push({type:"urls",groupCount:1,startIndex:c}),c+=1),o&&(a.push("(@[a-zA-Z][a-zA-Z0-9_]*)"),l.push({type:"tools",groupCount:1,startIndex:c}),c+=1),i&&(a.push("(\\{([^}]+)\\})"),l.push({type:"customTemplates",groupCount:2,startIndex:c}),c+=2),a.length===0)return[{type:"text",content:t}];let u=new RegExp(a.join("|"),"g"),d=0,f;for(;(f=u.exec(t))!==null;){if(f.index>d){let m=t.slice(d,f.index);m&&s.push({type:"text",content:m})}let p=null;for(let m of l)if(f[m.startIndex]){p=m;break}if(!p)s.push({type:"text",content:f[0]});else if(p.type==="notes"){let m=f[p.startIndex+1].trim(),h=GXt(m);if(h&&h instanceof $y.TFile){let y=app?.workspace.getActiveFile()?.path===h.path;s.push({type:"note-pill",content:h.basename,file:h,isActive:y})}else s.push({type:"text",content:f[0]})}else if(p.type==="urls"){let m=f[p.startIndex].replace(/,+$/,"");HXt(m)?s.push({type:"url-pill",content:m,url:m}):s.push({type:"text",content:f[0]})}else if(p.type==="tools"){let m=f[p.startIndex],h=KXt(m);h?s.push({type:"tool-pill",content:h,toolName:h}):s.push({type:"text",content:f[0]})}else if(p.type==="customTemplates"){let m=f[p.startIndex+1].trim();if(m==="activeNote")s.push({type:"active-note-pill",content:"activeNote"});else{let h=qXt(m);h?s.push({type:"folder-pill",content:h.path,folder:h}):s.push({type:"text",content:f[0]})}}d=u.lastIndex}if(d<t.length){let p=t.slice(d);p&&s.push({type:"text",content:p})}return s}function WJ(t){let e=[];for(let n of t)n.type==="text"&&n.content?e.push(vf(n.content)):n.type==="active-note-pill"?e.push(G4()):n.type==="note-pill"&&n.file?e.push(q4(n.content,n.file.path)):n.type==="url-pill"&&n.url?e.push(vJ(n.url)):n.type==="tool-pill"&&n.toolName?e.push(hE(n.toolName)):n.type==="folder-pill"&&n.folder&&e.push(Z4(n.folder.path));return e}function mft(t,e={}){let{enableURLPills:n=!1,insertAtSelection:r=!0}=e;if(!t)return;let o=gn();if(!jt(o)){k("No range selection available for text insertion");return}let i=VJ(t,{includeNotes:!0,includeURLs:n}),s=WJ(i);s.length>0&&(r||o.removeText(),o.insertNodes(s))}function hft(t,e,n,r={}){let{enableURLPills:o=!1,enableToolPills:i=!1,enableCustomTemplatePills:s=!1}=r,a=gn();if(!jt(a))return;let c=a.anchor.getNode();if(c.getType()!=="text")return;let u=c,d=u.getTextContent(),f=VJ(n,{includeNotes:!0,includeURLs:o,includeTools:i,includeCustomTemplates:s});if(f.length===1&&f[0].type==="text"){let{beforeText:p,afterText:m}=vIe(d,t,e),h=p+f[0].content+m;u.setTextContent(h);let g=p.length+f[0].content.length;u.select(g,g)}else{let{beforeText:p,afterText:m}=vIe(d,t,e),h=[];p&&h.push(vf(p)),h.push(...WJ(f)),m&&h.push(vf(m)),VXt(u,h)}}function h1(t,e,n=!0){let r=gn();if(!jt(r))return;let o=r.anchor,i=o.getNode();if(!(i instanceof My))return;let s=i.getTextContent(),a=o.offset,l=-1;if(t==="[["?l=s.lastIndexOf("[[",a):l=s.lastIndexOf(t,a),l===-1)return;let{beforeText:c,afterText:u}=vIe(s,l,a),d=jXt(e);WXt(i,c,d,u,n)}var Cf=N(U());function pS({triggerConfig:t,options:e,onSelect:n,onStateChange:r,onHighlight:o}){let[i]=vr(),[s,a]=(0,Cf.useState)({isOpen:!1,query:"",selectedIndex:0,range:null});(0,Cf.useEffect)(()=>{r?.(s)},[s,r]);let l=(0,Cf.useCallback)(()=>{a({isOpen:!1,query:"",selectedIndex:0,range:null})},[]),c=(0,Cf.useCallback)(f=>{a(p=>({...p,selectedIndex:f})),o&&e[f]&&o(f,e[f])},[o,e]),u=(0,Cf.useCallback)(f=>{if(!f||!s.isOpen)return!1;switch(f.key){case"ArrowDown":{if(e.length===0)return!1;f.preventDefault();let p=s.selectedIndex+1;for(;p<e.length&&e[p]?.disabled;)p++;return p>=e.length&&(p=s.selectedIndex),c(p),!0}case"ArrowUp":{if(e.length===0)return!1;f.preventDefault();let p=s.selectedIndex-1;for(;p>=0&&e[p]?.disabled;)p--;return p<0&&(p=s.selectedIndex),c(p),!0}case"Enter":case"Tab":return e.length===0?(l(),!1):(e[s.selectedIndex]?.disabled||(f.preventDefault(),e[s.selectedIndex]&&n(e[s.selectedIndex])),!0);case"Escape":return f.preventDefault(),l(),!0;default:return!1}},[s.isOpen,s.selectedIndex,e,n,l,c]);(0,Cf.useEffect)(()=>{let f=i.registerCommand(Yct,w=>u(w),dx),p=i.registerCommand(Xct,w=>u(w),dx),m=i.registerCommand(a1,w=>u(w),dx),h=i.registerCommand(nut,w=>u(w),dx),g=i.registerCommand(tut,w=>u(w),dx),y=i.registerCommand($ct,()=>(s.isOpen&&l(),!1),dx);return()=>{f(),p(),m(),h(),g(),y()}},[i,u,s.isOpen,l]);let d=(0,Cf.useCallback)((f,p)=>{let{char:m,multiChar:h=!1,allowWhitespace:g=!1}=t;if(h){let y=m.length,w=-1;for(let v=p-1;v>=y-1;v--)if(f.slice(v-y+1,v+1)===m){if(v-y+1===0||/\s/.test(f[v-y])){w=v-y+1;break}}else if(!g&&/\s/.test(f[v]))break;if(w!==-1){let v=f.slice(w+y,p);return v.startsWith(" ")?null:{triggerIndex:w,query:v}}}else{let y=-1;for(let w=p-1;w>=0;w--){let v=f[w];if(v===m){if(w===0||/\s/.test(f[w-1])){y=w;break}}else if(!g&&/\s/.test(v))break}if(y!==-1){let w=f.slice(y+1,p);return w.startsWith(" ")?null:{triggerIndex:y,query:w}}}return null},[t]);return(0,Cf.useEffect)(()=>i.registerUpdateListener(({editorState:f})=>{f.read(()=>{let p=gn();if(!jt(p)||!p.isCollapsed()){s.isOpen&&l();return}let m=p.anchor,h=m.getNode();if(!(h instanceof My)){s.isOpen&&l();return}let g=h.getTextContent(),y=m.offset,w=d(g,y);if(w){let{triggerIndex:v,query:x}=w,b=i._window??window,_=fft(v,b);_&&a(T=>({...T,isOpen:!0,query:x,selectedIndex:0,range:_}))}else s.isOpen&&l()})}),[i,s.isOpen,l,d]),(0,Cf.useEffect)(()=>{a(f=>({...f,selectedIndex:0}))},[e.length]),(0,Cf.useEffect)(()=>{a(f=>f.selectedIndex>=e.length&&e.length>0?{...f,selectedIndex:Math.max(0,e.length-1)}:f)},[e.length]),{state:s,setState:a,closeMenu:l,detectTrigger:d,handleHighlight:c}}function gft(){let[t]=vr(),e=G9(),[n,r]=(0,Lh.useState)(""),o=(0,Lh.useMemo)(()=>J9(e.filter(u=>u.showInSlashMenu)).map((u,d)=>({key:`${u.title}-${d}`,title:u.title,content:u.content,command:u})),[e]),i=(0,Lh.useMemo)(()=>{if(!n)return o;let c=n,u=xIe.default.go(c,o,{key:"title",threshold:-1e4});return u.length>0?u.map(f=>f.obj):xIe.default.go(c,o,{key:"content",threshold:-1e4}).map(f=>f.obj)},[o,n]),s=(0,Lh.useCallback)(c=>{Xs.getInstance().recordUsage(c.command),t.update(()=>{let u=gn();if(!jt(u))return;let d=u.anchor,f=d.getNode();if(f instanceof My){let m=f.getTextContent().lastIndexOf("/",d.offset);if(m!==-1){let h=c.content||c.title;hft(m,d.offset,h,{enableURLPills:!0,enableToolPills:!0,enableCustomTemplatePills:!0})}}})},[t]),{state:a,handleHighlight:l}=pS({triggerConfig:{char:"/",allowWhitespace:!0},options:i,onSelect:s,onStateChange:c=>{r(c.query)}});return Lh.default.createElement(Lh.default.Fragment,null,a.isOpen&&Lh.default.createElement(fS,{options:i,selectedIndex:a.selectedIndex,onSelect:s,onHighlight:l,range:a.range,query:a.query,showPreview:!0}))}var _f=N(U());var yE=N(U());vt();var yft=N(W4());Se();var YXt={limit:30,threshold:-1e4};function wft(t,e=!1,n={},r=null){let o=mJ(e),i=(0,yE.useMemo)(()=>o.map((a,l)=>({key:`${a.basename}-${l}`,title:a.basename,subtitle:a.path,content:"",icon:yE.default.createElement(Ur,{className:"tw-size-4"}),file:a})),[o]);return(0,yE.useMemo)(()=>{let a={...YXt,...n},l=q().customPromptsFolder;if(!t.trim()){let y=i.filter(x=>!x.file.path.startsWith(l+"/")),w=i.filter(x=>x.file.path.startsWith(l+"/"));if(r){let x={key:`active-note-${r.path}`,title:"Active Note",subtitle:r.path,content:"",category:"activeNote",icon:yE.default.createElement(iw,{className:"tw-size-4"}),file:r},b=[...y,...w].slice(0,a.limit-1);return[x,...b]}return[...y,...w].slice(0,a.limit)}let c=t.trim(),u=c.toLowerCase(),p="active note".includes(u)&&r?{key:`active-note-${r.path}`,title:"Active Note",subtitle:r.path,content:"",category:"activeNote",icon:yE.default.createElement(iw,{className:"tw-size-4"}),file:r}:null,m=p?a.limit-1:a.limit,g=yft.default.go(c,i,{keys:["subtitle"],limit:m,threshold:a.threshold}).map(y=>y.obj);return p?[p,...g]:g},[i,t,n,r])}async function ZXt(t,e=500){try{if(t.extension==="pdf"||t.extension==="canvas")return"";let r=(await app.vault.cachedRead(t)).replace(/^---\s*\n[\s\S]*?\n---\s*\n?/,"").trim();return r.length>e?r.slice(0,e)+"...":r}catch(n){return console.warn("Failed to read note content:",n),"Failed to load content"}}var HJ=class{constructor(){this.cache=new Map}async getOrLoadContent(e,n=500){let r=this.cache.get(e.path);if(r!==void 0)return r;let o=await ZXt(e,n);return this.cache.set(e.path,o),o}clear(){this.cache.clear()}remove(e){this.cache.delete(e)}has(e){return this.cache.has(e)}};function vft({isCopilotPlus:t=!1,currentActiveFile:e=null}){let[n]=vr(),[r,o]=(0,_f.useState)(""),[i]=(0,_f.useState)(()=>new HJ),[s,a]=(0,_f.useState)(()=>new Map),l=(0,_f.useCallback)(async m=>{try{let h=await i.getOrLoadContent(m,500);return a(g=>{let y=new Map(g);return y.set(m.path,h),y}),h}catch{let h="Failed to load content";return a(g=>{let y=new Map(g);return y.set(m.path,h),y}),h}},[i]),u=wft(r,t,{},e).map(m=>({...m,content:s.get(m.file.path)||""})),d=(0,_f.useCallback)(m=>{if(m.category==="activeNote")n.update(()=>{h1("[[",{type:"active-note"})});else{let h={type:"notes",title:m.title,data:m.file};n.update(()=>{h1("[[",h)})}},[n]),{state:f,handleHighlight:p}=pS({triggerConfig:{char:"[[",multiChar:!0,allowWhitespace:!0},options:u,onSelect:d,onStateChange:m=>{o(m.query)},onHighlight:(m,h)=>{h&&!s.has(h.file.path)&&l(h.file)}});return(0,_f.useEffect)(()=>{u.length>0&&!s.has(u[0].file.path)&&l(u[0].file)},[u,s,l]),_f.default.createElement(_f.default.Fragment,null,f.isOpen&&_f.default.createElement(fS,{options:u,selectedIndex:f.selectedIndex,onSelect:d,onHighlight:p,range:f.range,query:f.query,showPreview:!0}))}var mS=N(U());var KJ=N(U()),bft=N(W4());Id();Se();function xft(t=!1){let e=Wl(ETe,{store:Kn}),n=Wl(ATe,{store:Kn});return t?e:n}var JXt={limit:10,threshold:-1e4,frontmatterOnly:!1};function Cft(t,e={}){let n=(0,KJ.useMemo)(()=>({...JXt,...e}),[e]),r=xft(n.frontmatterOnly),o=(0,KJ.useMemo)(()=>r.map((s,a)=>{let l=s.startsWith("#")?s.slice(1):s;return{key:`tag-${l}-${a}`,title:s,subtitle:void 0,content:"",tag:l}}),[r]);return(0,KJ.useMemo)(()=>{if(!t.trim())return o.slice(0,n.limit);let s=t.trim();return bft.default.go(s,o,{key:"title",limit:n.limit,threshold:n.threshold}).map(l=>l.obj)},[o,t,n])}function _ft({onTagSelected:t}){let[e]=vr(),[n,r]=(0,mS.useState)(""),o=Cft(n,{limit:10}),i=(0,mS.useCallback)(l=>{e.update(()=>{let c=gn();if(!jt(c))return;let u=c.anchor,d=u.getNode();if(!(d instanceof My))return;let f=d.getTextContent(),p=u.offset,m=f.lastIndexOf("#",p);if(m===-1)return;let h=f.slice(0,m),g=f.slice(p),y=`#${l.tag} `;d.setTextContent(h+y+g);let w=h.length+y.length;d.select(w,w)}),t?.()},[e,t]),{state:s,handleHighlight:a}=pS({triggerConfig:{char:"#",multiChar:!1,allowWhitespace:!1},options:o,onSelect:i,onStateChange:l=>{r(l.query)}});return mS.default.createElement(mS.default.Fragment,null,s.isOpen&&mS.default.createElement(fS,{options:o,selectedIndex:s.selectedIndex,onSelect:i,onHighlight:a,range:s.range,query:s.query,showPreview:!1}))}var xa=N(U());var bIe=require("obsidian");function qJ({isCopilotPlus:t=!1,currentActiveFile:e=null}){let[n]=vr(),[r,o]=(0,xa.useState)({mode:"category"}),[i,s]=(0,xa.useState)(""),a=dJ(t),l=(0,xa.useCallback)(async x=>{if(!x){s("");return}try{if(x.extension==="pdf"||x.extension==="canvas"){s("");return}let _=(await app.vault.cachedRead(x)).replace(/^---\s*\n[\s\S]*?\n---\s*\n?/,"").trim(),T=_.length>300?_.slice(0,300)+"...":_;s(T)}catch{s("Failed to load content")}},[]),[c,u]=(0,xa.useState)(""),d=yJ(c,r.mode,r.selectedCategory,t,a,e),f=(0,xa.useCallback)(x=>"data"in x,[]),p=(0,xa.useCallback)(x=>"icon"in x&&!("data"in x),[]),m=(0,xa.useCallback)(x=>{if(r.mode==="category"&&p(x)&&!c){o(b=>({...b,mode:"search",selectedCategory:x.category}));return}if(f(x))if(x.category==="activeNote")n.update(()=>{h1("@",{type:"active-note"})});else{let b={type:x.category,title:x.title,data:x.data};n.update(()=>{h1("@",b)})}},[r.mode,c,p,f,n]),h=(0,xa.useCallback)(x=>{u(x.query),x.isOpen||o({mode:"category",selectedCategory:void 0})},[]),{state:g,handleHighlight:y}=pS({triggerConfig:{char:"@",allowWhitespace:!0},options:d,onSelect:m,onStateChange:h}),w=(0,xa.useMemo)(()=>{let x=d[g.selectedIndex];return x&&f(x)&&x.category==="notes"&&x.data instanceof bIe.TFile?x.data:null},[g.selectedIndex,d,f]);(0,xa.useEffect)(()=>{l(w)},[w,l]);let v=(0,xa.useMemo)(()=>d.map((x,b)=>b===g.selectedIndex&&f(x)&&x.category==="notes"&&x.data instanceof bIe.TFile?{...x,content:i}:x),[d,g.selectedIndex,i,f]);return xa.default.createElement(xa.default.Fragment,null,g.isOpen&&xa.default.createElement(fS,{options:v,selectedIndex:g.selectedIndex,onSelect:m,onHighlight:y,range:g.range,query:g.query,showPreview:d[g.selectedIndex]&&f(d[g.selectedIndex])&&d[g.selectedIndex].category==="notes",mode:r.mode}))}var Sft=N(U());function CIe(t){if(!(t instanceof Q7))return!1;let e=t;return typeof e.isPill=="function"&&e.isPill()===!0}function GJ(){let[t]=vr();return Sft.default.useEffect(()=>{let e=t.registerCommand(i1,n=>{let r=!1;return t.update(()=>{let o=gn();if(!jt(o)||!o.isCollapsed()){r=!1;return}let i=o.anchor,s=i.getNode();if(CIe(s)){(n&&i.offset===1||!n&&i.offset===0)&&(s.remove(),r=!0);return}if(lr(s)&&n&&i.offset>0){let l=s.getChildren()[i.offset-1];if(CIe(l)){l.remove(),r=!0;return}}if(n&&i.offset===0){let a=s.getPreviousSibling();if(a&&CIe(a)){a.remove(),r=!0;return}}r=!1}),r},J7);return()=>{e()}},[t]),null}var Tft=N(U());It();function YJ({onSubmit:t,sendShortcut:e}){let[n]=vr();return(0,Tft.useEffect)(()=>n.registerCommand(a1,r=>r?r.isComposing||r.key==="Process"?(r.preventDefault(),!0):XXt(r,e)?(r.preventDefault(),t(),!0):!1:!1,Bct),[n,t,e]),null}function XXt(t,e){switch(e){case"enter":return!t.shiftKey&&!t.metaKey&&!t.ctrlKey&&!t.altKey;case"shift+enter":return t.shiftKey&&!t.metaKey&&!t.ctrlKey&&!t.altKey;default:return!1}}var Ift=N(U());function ZJ({value:t}){let[e]=vr();return Ift.default.useEffect(()=>{e.update(()=>{let n=mr();if(n.getTextContent()!==t){n.clear();let o=cx();t&&o.append(vf(t)),n.append(o)}})},[e,t]),null}var Pft=N(U());function JJ({onFocus:t,onEditorReady:e}){let[n]=vr();return Pft.default.useEffect(()=>{t(()=>{n.focus()}),e&&e(n)},[n,t,e]),null}var Eft=N(U());var XJ=N(U());function Dh({config:t,onChange:e,onRemoved:n}){let[r]=vr(),o=XJ.default.useRef([]),{isPillNode:i,extractData:s,getKey:a=u=>String(u),getChangeKey:l}=t,c=XJ.default.useMemo(()=>l??a,[l,a]);return XJ.default.useEffect(()=>{if(!(!e&&!n))return r.registerUpdateListener(({editorState:u})=>{u.read(()=>{let d=[],f=mr();function p(P){if(i(P)){let O=s(P);d.push(O)}let A=P;if(typeof A.getChildren=="function"){let O=A.getChildren();for(let D of O)p(D)}}p(f);let m=new Set,g=d.filter(P=>{let A=a(P);return m.has(A)?!1:(m.add(A),!0)}).sort((P,A)=>a(P).localeCompare(a(A))),y=o.current,w=g.map(a),v=y.map(a),x=g.map(c),b=y.map(c),_=w.length!==v.length||w.some((P,A)=>P!==v[A]),T=x.length!==b.length||x.some((P,A)=>P!==b[A]);if(_||T){if(n){let P=new Set(w),A=y.filter(O=>!P.has(a(O)));A.length>0&&n(A)}o.current=g,e&&e(g)}})})},[r,e,n,i,s,a,c]),null}var QXt={isPillNode:OTe,extractData:t=>{let e=t;return{path:e.getNotePath(),basename:e.getNoteTitle()}},getKey:t=>t.path};function QJ({onNotesChange:t,onNotesRemoved:e}){return Eft.default.createElement(Dh,{config:QXt,onChange:t,onRemoved:e})}var Aft=N(U());var eQt={isPillNode:But,extractData:t=>t.getURL()};function kft({onURLsChange:t,onURLsRemoved:e}){return Aft.default.createElement(Dh,{config:eQt,onChange:t,onRemoved:e})}var Mft=N(U());var tQt={isPillNode:Vut,extractData:t=>t.getToolName()};function Nft({onToolsChange:t,onToolsRemoved:e}){return Mft.default.createElement(Dh,{config:tQt,onChange:t,onRemoved:e})}var Oft=N(U());var nQt={isPillNode:zut,extractData:t=>t.getFolderPath()};function eX({onFoldersChange:t,onFoldersRemoved:e}){return Oft.default.createElement(Dh,{config:nQt,onChange:t,onRemoved:e})}var Rft=N(U());function tX({onActiveNoteAdded:t,onActiveNoteRemoved:e}){let[n]=vr();return(0,Rft.useEffect)(()=>{let r=!1,o=n.registerUpdateListener(({editorState:i})=>{i.read(()=>{let s=mr(),a=!1;function l(c){if(RTe(c)){a=!0;return}if("getChildren"in c&&typeof c.getChildren=="function"){let u=c.getChildren();for(let d of u){if(a)return;l(d)}}}l(s),a&&!r?(r=!0,t?.()):!a&&r&&(r=!1,e?.())})});return()=>{o()}},[n,t,e]),null}var hS=N(U());var rQt={isPillNode:qut,extractData:t=>({url:t.getURL(),title:t.getTitle(),faviconUrl:t.getFaviconUrl()}),getKey:t=>t.url,getChangeKey:t=>[t.url,t.title??"",t.faviconUrl??""].join(`
`)};function Lft({onWebTabsChange:t,onWebTabsRemoved:e,onActiveWebTabAdded:n,onActiveWebTabRemoved:r}){return hS.default.createElement(hS.default.Fragment,null,hS.default.createElement(Dh,{config:rQt,onChange:t,onRemoved:e}),(n||r)&&hS.default.createElement(oQt,{onActiveWebTabAdded:n,onActiveWebTabRemoved:r}))}function oQt({onActiveWebTabAdded:t,onActiveWebTabRemoved:e}){let n={isPillNode:LTe,extractData:()=>!0,getKey:()=>"active-web-tab"},r=hS.default.useCallback(i=>{i.length>0&&t&&t()},[t]),o=hS.default.useCallback(i=>{i.length>0&&e&&e()},[e]);return hS.default.createElement(Dh,{config:n,onChange:r,onRemoved:o})}var Dft=N(U());function $ft({enableURLPills:t=!1,onImagePaste:e}){let[n]=vr();return Dft.default.useEffect(()=>n.registerCommand(tJ,r=>{let o=r.clipboardData;if(!o)return!1;if(e){let p=o.items;if(p){let m=Array.from(p).filter(h=>h.type.indexOf("image")!==-1);if(m.length>0){r.preventDefault();let g=m.map(y=>y.getAsFile()).filter(y=>y!==null);return g.length>0&&e(g),!0}}}let i=o.getData("text/plain"),s=i.includes("[["),a=t&&i.includes("http"),l=i.includes("@"),c=i.includes("#"),u=i.includes("{")&&i.includes("}");if(!i||!s&&!a&&!l&&!c&&!u)return!1;let d=VJ(i,{includeNotes:!0,includeURLs:t,includeTools:!0,includeCustomTemplates:!0});return d.some(p=>p.type==="note-pill"||p.type==="active-note-pill"||t&&p.type==="url-pill"||p.type==="tool-pill"||p.type==="folder-pill")?(r.preventDefault(),n.update(()=>{let p=gn();if(!jt(p))return;let m=WJ(d);m.length>0&&p.insertNodes(m)}),!0):!1},dx),[n,t,e]),null}var Fft=N(U());function Uft(){let[t]=vr();return Fft.default.useEffect(()=>t.registerCommand(jJ,e=>{let{text:n,options:r={}}=e;return t.update(()=>{mft(n,r)}),!0},zo),[t]),null}var _c=N(U());var Bft=(0,_c.createContext)(void 0);function gS(){let t=(0,_c.useContext)(Bft);if(t===void 0)throw new Error("useChatInput must be used within a ChatInputProvider");return t}function zft({children:t}){let[e,n]=(0,_c.useState)(null),[r,o]=(0,_c.useState)(null),i=(0,_c.useCallback)(u=>{n(u)},[]),s=(0,_c.useCallback)(u=>{o(()=>u)},[]),a=(0,_c.useCallback)((u,d=!1)=>{e&&e.dispatchCommand(jJ,{text:u,options:{enableURLPills:d,insertAtSelection:!0}})},[e]),l=(0,_c.useCallback)(()=>{r&&r()},[r]),c=(0,_c.useMemo)(()=>({insertTextWithPills:a,focusInput:l,registerEditor:i,registerFocusHandler:s}),[a,l,i,s]);return _c.default.createElement(Bft.Provider,{value:c},t)}Kt();ye();Qi();Se();var iQt=({value:t,onChange:e,onSubmit:n,placeholder:r="Type a message...",disabled:o=!1,className:i="",onNotesChange:s,onNotesRemoved:a,onURLsChange:l,onURLsRemoved:c,onToolsChange:u,onToolsRemoved:d,onFoldersChange:f,onFoldersRemoved:p,onActiveNoteAdded:m,onActiveNoteRemoved:h,onWebTabsChange:g,onWebTabsRemoved:y,onActiveWebTabAdded:w,onActiveWebTabRemoved:v,onEditorReady:x,onImagePaste:b,onTagSelected:_,isCopilotPlus:T=!1,currentActiveFile:S=null,currentChain:P})=>{let[A,O]=Nr.default.useState(null),[D,$]=Nr.default.useState(null),B=gS(),W=Ht(),F=Nr.default.useCallback(te=>{O(()=>te)},[]);(0,Nr.useEffect)(()=>{D&&B.registerEditor(D)},[D,B]),(0,Nr.useEffect)(()=>{A&&B.registerFocusHandler(A)},[A,B]);let Z=Nr.default.useMemo(()=>({namespace:"ChatEditor",theme:{root:"tw-outline-none",paragraph:"tw-m-0"},nodes:[aS,cS,mE,fx,px,uS,...l?[pE]:[]],onError:te=>{z("Lexical error:",te)},editable:!o}),[l,o]),V=(0,Nr.useCallback)(te=>{te.read(()=>{let me=mr().getTextContent();e(me)})},[e]),H=(0,Nr.useCallback)(te=>{$(te),x?.(te)},[x]);return Nr.default.createElement(TJ,{initialConfig:Z},Nr.default.createElement(wJ,{currentActiveFile:S},Nr.default.createElement("div",{className:oe("tw-relative",i)},Nr.default.createElement(OJ,{contentEditable:Nr.default.createElement(RJ,{className:"tw-max-h-40 tw-min-h-[60px] tw-w-full tw-resize-none tw-overflow-y-auto tw-rounded-md tw-border-none tw-bg-transparent tw-px-2 tw-text-sm tw-text-normal tw-outline-none focus-visible:tw-ring-0","aria-label":"Chat input"}),placeholder:Nr.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-left-2 tw-top-0 tw-select-none tw-text-sm tw-text-muted/60"},r),ErrorBoundary:zJ}),Nr.default.createElement(BJ,{onChange:V}),Nr.default.createElement(FJ,null),Nr.default.createElement(YJ,{onSubmit:n,sendShortcut:W.defaultSendShortcut}),Nr.default.createElement(ZJ,{value:t}),Nr.default.createElement(JJ,{onFocus:F,onEditorReady:H}),Nr.default.createElement(QJ,{onNotesChange:s,onNotesRemoved:a}),l&&Nr.default.createElement(kft,{onURLsChange:l,onURLsRemoved:c}),Nr.default.createElement(Nft,{onToolsChange:u,onToolsRemoved:d}),Nr.default.createElement(eX,{onFoldersChange:f,onFoldersRemoved:p}),Nr.default.createElement(tX,{onActiveNoteAdded:m,onActiveNoteRemoved:h}),Nr.default.createElement(Lft,{onWebTabsChange:g,onWebTabsRemoved:y,onActiveWebTabAdded:w,onActiveWebTabRemoved:v}),Nr.default.createElement(GJ,null),Nr.default.createElement($ft,{enableURLPills:!!l,onImagePaste:b}),Nr.default.createElement(gft,null),Nr.default.createElement(vft,{isCopilotPlus:T,currentActiveFile:S}),P&&P!=="llm_chain"&&Nr.default.createElement(_ft,{onTagSelected:_}),Nr.default.createElement(qJ,{isCopilotPlus:T,currentActiveFile:S}),Nr.default.createElement(Uft,null))))},jft=iQt;var Vft=({inputMessage:t,setInputMessage:e,handleSendMessage:n,isGenerating:r,onStopGenerating:o,app:i,contextNotes:s,setContextNotes:a,includeActiveNote:l,setIncludeActiveNote:c,includeActiveWebTab:u,setIncludeActiveWebTab:d,activeWebTab:f,selectedImages:p,onAddImage:m,setSelectedImages:h,disableModelSwitch:g,selectedTextContexts:y,onRemoveSelectedText:w,showProgressCard:v,showIndexingCard:x,editMode:b=!1,onEditSave:_,onEditCancel:T,initialContext:S})=>{let[P,A]=(0,ct.useState)(S?.urls||[]),[O,D]=(0,ct.useState)(S?.folders||[]),[$,B]=(0,ct.useState)([]),W=(0,ct.useRef)(null),F=(0,ct.useRef)(null),[Z,V]=qx(),[H]=kd(),[te]=KW(),fe=Ht(),[me,j]=(0,ct.useState)(()=>{let gt=i.workspace.getActiveFile();return tg(gt)?gt:null}),[G,J]=(0,ct.useState)([]),[M,E]=(0,ct.useState)([]),[R,L]=(0,ct.useState)([]),[K,Y]=(0,ct.useState)([]),[re,ae]=(0,ct.useState)([]),ve=Mc(H),Te=(0,ct.useMemo)(()=>$P([...$,...re]),[$,re]),Ee=()=>{let gt=F.current;return gt?gt.read(()=>DTe().map(xt=>({url:xt.getURL(),title:xt.getTitle(),faviconUrl:xt.getFaviconUrl()}))):re},[nt,rt]=(0,ct.useState)(!1),[Jt,ke]=(0,ct.useState)(!1),[Ln,He]=(0,ct.useState)(!1),[Ie,dt]=(0,ct.useState)(fe.enableAutonomousAgent),[Me,Ue]=(0,ct.useState)(0),it=["Loading the project context...","Processing context files...","If you have many files in context, this can take a while..."],St=(0,ct.useRef)({chain:H,enabled:fe.enableAutonomousAgent});(St.current.chain!==H||St.current.enabled!==fe.enableAutonomousAgent)&&(St.current={chain:H,enabled:fe.enableAutonomousAgent},dt(H==="project"?!1:fe.enableAutonomousAgent));let $r=(0,ct.useSyncExternalStore)(OA,br),oo=H==="project"?$r:null;(0,ct.useEffect)(()=>{if(!te)return;let gt=window.setInterval(()=>{Ue(Je=>(Je+1)%it.length)},3e3);return()=>window.clearInterval(gt)},[te,it.length]);let Bn=()=>oo&&H==="project"&&oo.projectModelKey?oo.projectModelKey:Z,Tr=()=>{if(b&&_){_(t,{notes:s,urls:P,folders:O});return}let gt=Ee(),Je=$P([...$,...gt]);if(!ve){n({webTabs:Je});return}let xt=[];if(!Ie){let ge=t.toLowerCase();nt&&!ge.includes("@vault")&&xt.push("@vault"),Jt&&!ge.includes("@websearch")&&!ge.includes("@web")&&xt.push("@websearch"),Ln&&!ge.includes("@composer")&&xt.push("@composer")}n({toolCalls:xt,contextNotes:s,urls:P,contextFolders:O,webTabs:Je})},Px=gt=>{let Je=new Set(gt.map(xt=>xt.path));a(xt=>xt.filter(ge=>!Je.has(ge.path)))},Zi=gt=>{let Je=new Set(gt);A(xt=>xt.filter(ge=>!Je.has(ge)))},Hh=gt=>{!ve||Ie||gt.forEach(Je=>{switch(Je){case"@vault":rt(!1);break;case"@websearch":case"@web":ke(!1);break;case"@composer":He(!1);break}})},_d=(0,ct.useRef)({tools:K,isCopilotPlus:ve,autonomousAgentToggle:Ie});(_d.current.tools!==K||_d.current.isCopilotPlus!==ve||_d.current.autonomousAgentToggle!==Ie)&&(_d.current={tools:K,isCopilotPlus:ve,autonomousAgentToggle:Ie},ve&&!Ie&&(rt(K.includes("@vault")),ke(K.includes("@websearch")||K.includes("@web")),He(K.includes("@composer"))));let Q1=gt=>{F.current&&F.current.update(()=>{Lut(gt)}),J(Je=>Je.filter(xt=>xt.path!==gt))},zl=gt=>{F.current&&F.current.update(()=>{Uut(gt)}),E(Je=>Je.filter(xt=>xt!==gt))},zy=gt=>{F.current&&F.current.update(()=>{jut(gt)}),L(Je=>Je.filter(xt=>xt!==gt))},eD=(gt,Je)=>{switch(gt){case"activeNote":c(!0);break;case"notes":if(Je instanceof tV.TFile){let xt=i.workspace.getActiveFile();xt&&Je.path===xt.path?(c(!0),a(ge=>ge.filter(ht=>ht.path!==Je.path))):a(ge=>ge.find(ir=>ir.path===Je.path)?ge:[...ge,Je])}break;case"tools":typeof Je=="string"&&F.current&&F.current.update(()=>{let xt=gn();if(jt(xt)){let ge=hE(Je);xt.insertNodes([ge])}});break;case"folders":if(Je&&typeof Je.path=="string"){let xt=Je.path;D(ge=>ge.find(ir=>ir===xt)?ge:[...ge,xt])}break;case"webTabs":if(Je&&typeof Je=="object"&&"url"in Je&&typeof Je.url=="string"){let xt=e_e(Je);if(!xt)break;let ge=wc(f?.url);if(ge&&xt.url===ge){d(!0),B(ht=>ht.filter(ir=>wc(ir.url)!==ge));break}B(ht=>$P([...ht,xt]))}break;case"activeWebTab":d(!0);{let xt=wc(f?.url);xt&&B(ge=>ge.filter(ht=>wc(ht.url)!==xt))}break}},tD=(gt,Je)=>{switch(gt){case"activeNote":c(!1),F.current&&F.current.update(()=>{Fut()});break;case"notes":typeof Je=="string"&&(me?.path===Je&&l?c(!1):a(xt=>xt.filter(ge=>ge.path!==Je)),Q1(Je));break;case"urls":typeof Je=="string"&&(A(xt=>xt.filter(ge=>ge!==Je)),zl(Je));break;case"folders":typeof Je=="string"&&(D(xt=>xt.filter(ge=>ge!==Je)),zy(Je));break;case"selectedText":typeof Je=="string"&&w?.(Je);break;case"activeWebTab":d(!1),F.current&&F.current.update(()=>{Hut()});break;case"webTabs":if(typeof Je=="string"){let xt=wc(Je);if(!xt)break;B(ge=>ge.filter(ht=>wc(ht.url)!==xt)),ae(ge=>ge.filter(ht=>wc(ht.url)!==xt)),F.current&&F.current.update(()=>{Gut(xt)})}break}},hs=gt=>{let Je=new Set(gt);D(xt=>xt.filter(ge=>!Je.has(ge)))};(0,ct.useEffect)(()=>{a(gt=>{let Je=new Set(gt.map(ht=>ht.path)),xt=G.filter(ht=>!Je.has(ht.path)),ge=[];return xt.forEach(ht=>{let ir=i.vault.getAbstractFileByPath(ht.path);ir instanceof tV.TFile&&ge.push(ir)}),[...gt,...ge]})},[G,i.vault,a]),(0,ct.useEffect)(()=>{Mc(H)?A(gt=>{let Je=new Set(gt),xt=M.filter(ge=>!Je.has(ge));return xt.length>0?Array.from(new Set([...gt,...xt])):gt}):A([])},[M,H]),(0,ct.useEffect)(()=>{D(gt=>{let Je=new Set(gt),xt=R.filter(ge=>!Je.has(ge));return[...gt,...xt]})},[R]),(0,ct.useEffect)(()=>{let gt,Je=()=>{window.clearTimeout(gt),gt=window.setTimeout(()=>{let ge=i.workspace.getActiveFile();j(tg(ge)?ge:null)},100)},xt=i.workspace.on("active-leaf-change",Je);return()=>{window.clearTimeout(gt),i.workspace.offref(xt)}},[i.workspace]);let Ta=(0,ct.useCallback)(gt=>{F.current=gt},[]);(0,ct.useEffect)(()=>{if(!b||!T)return;let gt=xt=>{xt.key==="Escape"&&(xt.preventDefault(),T())},Je=W.current?.doc;if(Je)return Je.addEventListener("keydown",gt),()=>Je.removeEventListener("keydown",gt)},[b,T]);let sl=(0,ct.useCallback)(()=>{F.current&&ve&&F.current.update(()=>{J4("@vault")})},[ve]),If=(0,ct.useCallback)(()=>{F.current&&ve&&F.current.update(()=>{J4("@websearch"),J4("@web")})},[ve]),jl=(0,ct.useCallback)(()=>{F.current&&ve&&F.current.update(()=>{J4("@composer")})},[ve]),Ji=(0,ct.useCallback)(()=>{c(!0)},[c]),xu=(0,ct.useCallback)(()=>{c(!1)},[c]),Kh=(0,ct.useCallback)(()=>{d(!0)},[d]),Xi=(0,ct.useCallback)(()=>{d(!1)},[d]),Pf=(0,ct.useCallback)(()=>{ve&&!Ie&&!nt&&(rt(!0),new tV.Notice("Vault search enabled for tag query"))},[ve,Ie,nt]);return ct.default.createElement("div",{className:"tw-flex tw-w-full tw-flex-col tw-gap-0.5 tw-rounded-md tw-border tw-border-solid tw-border-border tw-px-1 tw-pb-1 tw-pt-2 tw-@container/chat-input",ref:W},!b&&ct.default.createElement(Nut,{contextNotes:s,includeActiveNote:l,activeNote:me,includeActiveWebTab:u,activeWebTab:f,contextUrls:P,contextFolders:O,contextWebTabs:Te,selectedTextContexts:y,showProgressCard:v,showIndexingCard:x,lexicalEditorRef:F,onAddToContext:eD,onRemoveFromContext:tD}),p.length>0&&ct.default.createElement("div",{className:"selected-images"},p.map((gt,Je)=>ct.default.createElement("div",{key:o7(gt),className:"image-preview-container"},ct.default.createElement("img",{src:URL.createObjectURL(gt),alt:gt.name,className:"selected-image-preview"}),ct.default.createElement("button",{type:"button",className:"remove-image-button",onClick:()=>h(xt=>xt.filter((ge,ht)=>ht!==Je)),title:"Remove image"},ct.default.createElement(Sn,{className:"tw-size-4"}))))),ct.default.createElement("div",{className:"tw-relative"},te&&ct.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-modal tw-flex tw-items-center tw-justify-center tw-bg-primary tw-opacity-80 tw-backdrop-blur-sm"},ct.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},ct.default.createElement(Pr,{className:"tw-size-4 tw-animate-spin"}),ct.default.createElement("span",{className:"tw-text-sm"},it[Me]))),ct.default.createElement(jft,{value:t,onChange:gt=>e(gt),onSubmit:Tr,onNotesChange:J,onNotesRemoved:Px,onActiveNoteAdded:Ji,onActiveNoteRemoved:xu,onURLsChange:ve?E:void 0,onURLsRemoved:ve?Zi:void 0,onToolsChange:ve?Y:void 0,onToolsRemoved:ve?Hh:void 0,onFoldersChange:L,onFoldersRemoved:hs,onWebTabsChange:ae,onActiveWebTabAdded:Kh,onActiveWebTabRemoved:Xi,onEditorReady:Ta,onImagePaste:m,onTagSelected:Pf,placeholder:"Your AI assistant for Obsidian \u2022 @ to add context \u2022 / for custom prompts",disabled:te,isCopilotPlus:ve,currentActiveFile:me,currentChain:H})),ct.default.createElement("div",{className:"tw-flex tw-h-6 tw-justify-between tw-gap-1 tw-px-1"},r?ct.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-px-1 tw-text-sm tw-text-muted"},ct.default.createElement(Pr,{className:"tw-size-3 tw-animate-spin"}),ct.default.createElement("span",null,"Generating...")):ct.default.createElement("div",{className:"tw-min-w-0 tw-flex-1"},ct.default.createElement(eL,{variant:"ghost2",size:"fit",disabled:g,value:Bn(),onChange:gt=>{H!=="project"&&V(gt)},className:"tw-max-w-full tw-truncate"})),ct.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},r?ct.default.createElement(X,{variant:"ghost2",size:"fit",className:"tw-text-muted",onClick:()=>o()},ct.default.createElement(Xx,{className:"tw-size-4"}),"Stop"):ct.default.createElement(ct.default.Fragment,null,ct.default.createElement(Wst,{vaultToggle:nt,setVaultToggle:rt,webToggle:Jt,setWebToggle:ke,composerToggle:Ln,setComposerToggle:He,autonomousAgentToggle:Ie,setAutonomousAgentToggle:dt,currentChain:H,onVaultToggleOff:sl,onWebToggleOff:If,onComposerToggleOff:jl}),ct.default.createElement(uu,{delayDuration:0},ct.default.createElement(cn,null,ct.default.createElement(un,{asChild:!0},ct.default.createElement(X,{variant:"ghost2",size:"fit",className:"tw-text-muted hover:tw-text-accent",onClick:gt=>{let Je=gt.currentTarget.doc.createElement("input");Je.type="file",Je.accept="image/*",Je.multiple=!0,Je.addEventListener("change",()=>m(Array.from(Je.files||[])),{once:!0}),Je.click()}},ct.default.createElement(b$,{className:"tw-size-4"}))),ct.default.createElement(on,{className:"tw-px-1 tw-py-0.5"},"Add image(s)"))),b&&T&&ct.default.createElement(X,{variant:"ghost2",size:"fit",className:"tw-text-muted",onClick:T},ct.default.createElement("span",null,"cancel")),ct.default.createElement(X,{variant:"ghost2",size:"fit",className:"tw-text-muted",onClick:()=>Tr()},ct.default.createElement(ag,{className:"!tw-size-3"}),ct.default.createElement("span",null,b?"save":"chat"))))))};Vft.displayName="ChatInput";var nX=Vft;rn();It();Kt();vt();var Wft=require("obsidian"),Rn=N(U()),Hft=({message:t,onCopy:e,isCopied:n,onInsertIntoEditor:r,onRegenerate:o,onEdit:i,onDelete:s,onShowSources:a,hasSources:l})=>Rn.default.createElement("div",{className:oe("tw-flex tw-gap-1",{"group-hover:opacity-100 opacity-0":!Wft.Platform.isMobile})},t.sender===uo?Rn.default.createElement(Rn.default.Fragment,null,Rn.default.createElement(cn,null,Rn.default.createElement(un,{asChild:!0},Rn.default.createElement(X,{variant:"ghost2",size:"fit",onClick:e,title:"Copy"},n?Rn.default.createElement(Ro,{className:"tw-size-4"}):Rn.default.createElement(Eu,{className:"tw-size-4"}))),Rn.default.createElement(on,null,"Copy")),Rn.default.createElement(cn,null,Rn.default.createElement(un,{asChild:!0},Rn.default.createElement(X,{onClick:i,variant:"ghost2",size:"fit",title:"Edit"},Rn.default.createElement(Au,{className:"tw-size-4"}))),Rn.default.createElement(on,null,"Edit")),Rn.default.createElement(cn,null,Rn.default.createElement(un,{asChild:!0},Rn.default.createElement(X,{onClick:s,variant:"ghost2",size:"fit",title:"Delete"},Rn.default.createElement(ka,{className:"tw-size-4"}))),Rn.default.createElement(on,null,"Delete"))):Rn.default.createElement(Rn.default.Fragment,null,l&&Rn.default.createElement(cn,null,Rn.default.createElement(un,{asChild:!0},Rn.default.createElement(X,{onClick:a,variant:"ghost2",size:"fit",title:"Show Sources"},Rn.default.createElement(YS,{className:"tw-size-4"}))),Rn.default.createElement(on,null,"Show Sources")),Rn.default.createElement(cn,null,Rn.default.createElement(un,{asChild:!0},Rn.default.createElement(X,{onClick:r,variant:"ghost2",size:"fit",title:"Insert / Replace at cursor"},Rn.default.createElement(N$,{className:"tw-size-4"}))),Rn.default.createElement(on,null,"Insert / Replace at cursor")),Rn.default.createElement(cn,null,Rn.default.createElement(un,{asChild:!0},Rn.default.createElement(X,{variant:"ghost2",size:"fit",onClick:e,title:"Copy"},n?Rn.default.createElement(Ro,{className:"tw-size-4"}):Rn.default.createElement(Eu,{className:"tw-size-4"}))),Rn.default.createElement(on,null,"Copy")),Rn.default.createElement(cn,null,Rn.default.createElement(un,{asChild:!0},Rn.default.createElement(X,{onClick:o,variant:"ghost2",size:"fit",title:"Regenerate"},Rn.default.createElement(k$,{className:"tw-size-4"}))),Rn.default.createElement(on,null,"Regenerate")),Rn.default.createElement(cn,null,Rn.default.createElement(un,{asChild:!0},Rn.default.createElement(X,{onClick:s,variant:"ghost2",size:"fit",title:"Delete"},Rn.default.createElement(ka,{className:"tw-size-4"}))),Rn.default.createElement(on,null,"Delete"))));ye();var g1=require("obsidian"),rX=class extends g1.Modal{constructor(e,n){super(e),this.sources=n}onOpen(){let{contentEl:e}=this;e.empty(),new g1.Setting(e).setName("Sources").setHeading(),this.createSourceList(e,this.sources)}createSourceList(e,n){let r=e.createEl("ul");r.addClass("tw-list-none","tw-p-0"),n.forEach(o=>{let i=r.createEl("li");i.addClass("tw-mb-4");let s=i.createDiv();s.addClass("tw-cursor-pointer");let a=s.createSpan();a.addClass("tw-mr-2","tw-inline-block","tw-w-4","tw-transition-transform"),a.textContent=o.explanation?"\u25B6":"";let l=o.path&&o.path!==o.title?`${o.title} (${o.path})`:o.title,c=s.createEl("a",{href:`obsidian://open?vault=${encodeURIComponent(this.app.vault.getName())}&file=${encodeURIComponent(o.path||o.title)}`,text:l});c.title=`${l} - drag to insert wikilink`,c.draggable=!0,c.addEventListener("dragstart",d=>{let f=o.path||o.title,p=this.app.vault.getAbstractFileByPath(f);if(p instanceof g1.TFile){let m=this.app.dragManager;if(!m)return;let h=this.app.metadataCache.fileToLinktext(p,""),g=m.dragLink(d,h);m.onDragStart(d,g)}}),c.addEventListener("click",d=>{d.preventDefault(),d.stopPropagation(),this.app.workspace.openLinkText(o.path||o.title,"").catch(z)}),typeof o.score=="number"&&s.appendChild(this.contentEl.doc.createTextNode(` - Relevance score: ${o.score.toFixed(4)}`));let u=null;o.explanation&&(u=this.addExplanation(i,o.explanation),u.addClass("tw-hidden"),s.addEventListener("click",d=>{if(d.target!==c&&u){let f=!u.hasClass("tw-hidden");u.toggleClass("tw-hidden",f),a.toggleClass("tw-rotate-90",!f)}}))})}addExplanation(e,n){let r=e.createDiv({cls:"search-explanation"});r.addClass("tw-ml-[2.5em]","tw-mt-2","tw-pl-2","tw-text-[0.9em]","tw-text-muted","tw-border-l","tw-border-l-border");let o=n,i=[];if(o.lexicalMatches&&o.lexicalMatches.length>0){let s=o.lexicalMatches,a=new Set(s.map(c=>c.field)),l=new Set(s.map(c=>c.query));i.push(`Lexical: matched "${Array.from(l).join('", "')}" in ${Array.from(a).join(", ")}`)}if(o.semanticScore!==void 0&&o.semanticScore>0&&i.push(`Semantic: ${(o.semanticScore*100).toFixed(1)}% similarity`),o.folderBoost){let s=o.folderBoost;i.push(`Folder boost: ${s.boostFactor.toFixed(2)}x (${s.documentCount} docs in ${s.folder||"root"})`)}if(o.graphConnections){let s=o.graphConnections,a=[];s.backlinks>0&&a.push(`${s.backlinks} backlinks`),s.coCitations>0&&a.push(`${s.coCitations} co-citations`),s.sharedTags>0&&a.push(`${s.sharedTags} shared tags`),a.length>0&&i.push(`Graph connections: ${s.score.toFixed(1)} score (${a.join(", ")})`)}if(o.graphBoost&&!o.graphConnections){let s=o.graphBoost;i.push(`Graph boost: ${s.boostFactor.toFixed(2)}x (${s.connections} connections)`)}return o.baseScore!==o.finalScore&&i.push(`Score: ${o.baseScore.toFixed(4)} \u2192 ${o.finalScore.toFixed(4)}`),i.length>0&&i.forEach(s=>{let a=r.createEl("div");a.addClass("tw-mb-1"),a.textContent=`\u2022 ${s}`}),r}onClose(){let{contentEl:e}=this;e.empty()}};var Sc=N(U()),Kft=require("obsidian");var qft=({initialValue:t,initialContext:e,onSave:n,onCancel:r,app:o})=>{let[i,s]=(0,Sc.useState)(t),[a,l]=(0,Sc.useState)(e?.notes?.filter(S=>S instanceof Kft.TFile)||[]),[c,u]=(0,Sc.useState)(!1),[d,f]=(0,Sc.useState)(!1),[p,m]=(0,Sc.useState)([]),{activeWebTabForMentions:h}=iS(),g=(0,Sc.useCallback)((S,P)=>{let A={notes:P.notes,urls:P.urls,tags:P.tags,folders:P.folders,selectedTextContexts:e?.selectedTextContexts||[]};n(S,A)},[n,e?.selectedTextContexts]),y=(0,Sc.useCallback)(()=>{r()},[r]),w=(0,Sc.useCallback)(()=>{},[]),v=(0,Sc.useCallback)(()=>{},[]),x=(0,Sc.useCallback)(S=>{m(P=>i7(P,S))},[]),b=(0,Sc.useCallback)(S=>{},[]),_=(0,Sc.useCallback)(()=>{},[]),T={notes:a,urls:e?.urls||[],tags:e?.tags||[],folders:e?.folders||[]};return Sc.default.createElement(nX,{inputMessage:i,setInputMessage:s,handleSendMessage:w,isGenerating:!1,onStopGenerating:v,app:o,contextNotes:a,setContextNotes:l,includeActiveNote:c,setIncludeActiveNote:u,includeActiveWebTab:d,setIncludeActiveWebTab:f,activeWebTab:h,selectedImages:p,onAddImage:x,setSelectedImages:m,disableModelSwitch:!1,selectedTextContexts:e?.selectedTextContexts,onRemoveSelectedText:b,showProgressCard:_,editMode:!0,onEditSave:g,onEditCancel:y,initialContext:T})};Ir();rn();Se();rn();var mu=N(U());Kt();vt();Su();ye();qe();function Fy({value:t,onChange:e,placeholder:n,disabled:r,className:o,autoDecrypt:i=!0}){let[s,a]=(0,mu.useState)(!1),[l,c]=(0,mu.useState)(!1),u=(0,mu.useRef)(null),d=(0,mu.useRef)(!0);return(0,mu.useEffect)(()=>{let f=!1;return(async()=>{let m=u.current;if(!m)return;if(d.current&&i&&t&&kx(t)){try{let g=await pn(t);if(f)return;g?(m.value=g,c(!1)):(m.value="",c(!0))}catch(g){if(f)return;z("Failed to decrypt value:"+Xt(g)),m.value="",c(!0)}d.current=!1}else m.value=t||"",c(!1),t!==void 0&&(d.current=!1)})(),()=>{f=!0}},[t,i]),mu.default.createElement("div",{className:oe("tw-relative",o)},mu.default.createElement(Xn,{ref:u,type:s?"text":"password",onChange:f=>e?.(f.target.value),placeholder:n,disabled:r,className:oe("tw-w-full !tw-pr-7")}),mu.default.createElement("div",{onClick:()=>!r&&a(!s),className:oe("tw-absolute tw-inset-y-0 tw-right-2 tw-flex tw-items-center tw-justify-center","tw-cursor-pointer",r&&"tw-cursor-not-allowed tw-opacity-50"),role:"button","aria-label":s?"Hide password":"Show password"},s?mu.default.createElement(h$,{className:oe("tw-size-3.5","tw-text-muted/60 hover:tw-text-accent","tw-transition-colors tw-duration-200")}):mu.default.createElement(ow,{className:oe("tw-size-3.5","tw-text-muted/60 hover:tw-text-accent","tw-transition-colors tw-duration-200")})),l&&mu.default.createElement("p",{className:"tw-mt-1 tw-text-xs tw-text-error"},"Unable to decrypt this key on the current device. Please re-enter the key."))}It();Se();qe();VS();var oX=require("obsidian"),Mt=N(U());ws();var sQt=({model:t,onUpdate:e,isEmbeddingModel:n,onCancel:r})=>{let[o,i]=(0,Mt.useState)(t),s=t,a=(0,Mt.useMemo)(()=>t.provider?ew(t.provider):{},[t.provider]),l=q(),c=o.provider==="amazon-bedrock",u=(0,Mt.useMemo)(()=>Li((y,w)=>{e(n,y,w)},500),[n,e]),d=(0,Mt.useCallback)((y,w)=>{i(v=>{let x={...v,[y]:w};return u(s,x),x})},[s,u]),f=(0,Mt.useCallback)(y=>{i(w=>{let v={...w};return delete v[y],u(s,v),v})},[u,s]);if(!o)return null;let p=()=>{if(!o||!o.provider||o.provider!=="azure-openai")return a.host||"https://api.example.com/v1";let y=o.azureOpenAIApiInstanceName||"[instance]",w=o.isEmbeddingModel?o.azureOpenAIApiEmbeddingDeploymentName||"[deployment]":o.azureOpenAIApiDeploymentName||"[deployment]",v=o.azureOpenAIApiVersion||"[api-version]",x=o.isEmbeddingModel?"embeddings":"chat/completions";return`https://${y}.openai.azure.com/openai/deployments/${w}/${x}?api-version=${v}`},m=Object.entries(Ex).map(([y,w])=>({id:y,label:y.charAt(0).toUpperCase()+y.slice(1),description:w})),h=Ad(o.provider,o),g=!n&&o.provider!=="copilot-plus-jina";return Mt.default.createElement("div",{className:"tw-space-y-3 tw-p-4"},Mt.default.createElement("div",{className:"tw-space-y-3"},Mt.default.createElement(Zn,{label:"Model Name",required:!0},Mt.default.createElement(Xn,{type:"text",disabled:o.core,value:o.name,onChange:y=>d("name",y.target.value),placeholder:"Enter model name"})),Mt.default.createElement(Zn,{label:Mt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Mt.default.createElement("span",{className:"tw-leading-none"},"Display Name"),Mt.default.createElement(Nn,{content:Mt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-0.5 tw-text-sm tw-text-muted"},Mt.default.createElement("div",{className:"tw-text-[12px] tw-font-bold"},"Suggested format:"),Mt.default.createElement("div",{className:"tw-text-accent"},"[Source]-[Payment]:[Pretty Model Name]"),Mt.default.createElement("div",{className:"tw-text-[12px]"},"Example:",Mt.default.createElement("li",null,"Direct-Paid:Ds-r1"),Mt.default.createElement("li",null,"OpenRouter-Paid:Ds-r1"),Mt.default.createElement("li",null,"Perplexity-Paid:lg"))),contentClassName:"tw-max-w-96"}))},Mt.default.createElement(Xn,{type:"text",placeholder:"Custom display name (optional)",value:o.displayName||"",onChange:y=>d("displayName",y.target.value)})),Mt.default.createElement(Zn,{label:"Provider"},Mt.default.createElement(Xn,{type:"text",value:cl(o.provider),disabled:!0})),Mt.default.createElement(Zn,{label:"Base URL",description:"Leave it blank, unless you are using a proxy."},Mt.default.createElement(Xn,{type:"text",placeholder:p(),value:o.baseUrl||"",onChange:y=>d("baseUrl",y.target.value)})),c&&Mt.default.createElement(Zn,{label:"Region (optional)",description:"Defaults to us-east-1 when left blank. With inference profiles (global., us., eu., apac.), region is auto-managed."},Mt.default.createElement(Xn,{type:"text",placeholder:"Enter AWS region (e.g. us-east-1)",value:o.bedrockRegion||"",onChange:y=>d("bedrockRegion",y.target.value)})),Mt.default.createElement(Zn,{label:"API Key"},Mt.default.createElement(Fy,{placeholder:`Enter ${a.label||"Provider"} API Key`,value:h,onChange:y=>d("apiKey",y)}),a.keyManagementURL&&Mt.default.createElement("p",{className:"tw-text-xs tw-text-muted"},Mt.default.createElement("a",{href:a.keyManagementURL,target:"_blank",rel:"noopener noreferrer"},"Get ",a.label," API Key"))),o.provider==="openrouterai"&&Mt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Mt.default.createElement(To,{id:"enable-prompt-caching",checked:o.enablePromptCaching!==!1,onCheckedChange:y=>d("enablePromptCaching",y)}),Mt.default.createElement(hi,{htmlFor:"enable-prompt-caching",className:"tw-cursor-pointer tw-text-sm"},"Prompt Caching"),Mt.default.createElement(Nn,{content:Mt.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Disable if your OpenRouter endpoint uses Zero Data Retention (ZDR), which does not support prompt caching.")})),g&&Mt.default.createElement(Mt.default.Fragment,null,Mt.default.createElement(Zn,{label:Mt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Mt.default.createElement("span",{className:"tw-leading-none"},"Model Capabilities"),Mt.default.createElement(Nn,{content:Mt.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Only used to display model capabilities, does not affect model functionality"),contentClassName:"tw-max-w-96"}))},Mt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-4"},m.map(({id:y,label:w,description:v})=>Mt.default.createElement("div",{key:y,className:"tw-flex tw-items-center tw-gap-2"},Mt.default.createElement(To,{id:y,checked:o.capabilities?.includes(y),onCheckedChange:x=>{let b=o.capabilities||[],_=x?[...b,y]:b.filter(T=>T!==y);d("capabilities",_)}}),Mt.default.createElement(Nn,{content:v},Mt.default.createElement(hi,{htmlFor:y,className:"tw-text-sm"},w)))))),(o.provider==="3rd party (openai-format)"||o.provider==="lm-studio")&&Mt.default.createElement(Zn,{label:"Stream Options"},Mt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Mt.default.createElement(To,{id:"stream-usage",checked:o.streamUsage||!1,onCheckedChange:y=>d("streamUsage",y)}),Mt.default.createElement(Nn,{content:Mt.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enable if your provider supports stream_options for token usage tracking. Disable for providers that do not support it (e.g., Databricks, MLFlow).")},Mt.default.createElement(hi,{htmlFor:"stream-usage",className:"tw-cursor-pointer tw-text-sm"},"Stream Usage")))),o.provider==="lm-studio"&&Mt.default.createElement(Zn,{label:"Responses API"},Mt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Mt.default.createElement(To,{id:"use-responses-api",checked:o.useResponsesApi!==!1,onCheckedChange:y=>d("useResponsesApi",y)}),Mt.default.createElement(Nn,{content:Mt.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Use /v1/responses instead of /v1/chat/completions. Patches compatibility issues with LM Studio (text.format, tool definitions). Requires LM Studio 0.3.6+.")},Mt.default.createElement(hi,{htmlFor:"use-responses-api",className:"tw-cursor-pointer tw-text-sm"},"Use Responses API (faster inference)")))),Mt.default.createElement(r7,{model:o,settings:l,onChange:d,onReset:f,showTokenLimit:!0}))),Mt.default.createElement("div",{className:"tw-mt-6 tw-flex tw-justify-end tw-gap-2 tw-border-t tw-border-border tw-pt-4"},Mt.default.createElement(X,{variant:"secondary",onClick:r},"Close")))},y1=class extends oX.Modal{constructor(n,r,o,i){super(n);this.model=r;this.isEmbeddingModel=o;this.onUpdate=i;this.setTitle(`Model Settings - ${this.model.name}`)}onOpen(){let{contentEl:n,modalEl:r}=this;oX.Platform.isMobile&&r.addClass("tw-h-4/5"),this.root=sr(n,this.app);let o=(s,a,l)=>{this.onUpdate(s,a,l)},i=()=>{this.close()};this.root.render(Mt.default.createElement(sQt,{model:this.model,isEmbeddingModel:this.isEmbeddingModel,onUpdate:o,onCancel:i}))}onClose(){this.root.unmount()}};vt();var Gft=require("obsidian"),gx=N(U()),Yft=({message:t,app:e})=>{let n=()=>{let r=q(),o=Iu(),i=r.activeModels.find(l=>ln(l)===o);if(!i){new Gft.Notice("Could not find the current model settings");return}let s=(l,c,u)=>{let d=r.activeModels.map(f=>f===c?u:f);pe("activeModels",d)};new y1(e,i,!1,s).open()};return gx.default.createElement("div",{className:"tw-mt-3 tw-rounded-md tw-border tw-border-border tw-bg-callout-warning/20 tw-p-4"},gx.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-3"},gx.default.createElement(dl,{className:"tw-size-5 tw-shrink-0 tw-text-warning"}),gx.default.createElement("div",{className:"tw-flex-1"},gx.default.createElement("div",{className:"tw-mb-2 tw-font-semibold tw-text-warning"},"Response Truncated"),gx.default.createElement("div",{className:"tw-mb-3 tw-text-normal"},"The AI response was cut off because it reached the token limit. You can increase the 'Token Limit' in model settings for longer responses."),t.responseMetadata?.tokenUsage&&gx.default.createElement("div",{className:"tw-mb-3 tw-text-sm tw-text-muted"},"Output tokens used: ",t.responseMetadata.tokenUsage.outputTokens||"N/A"),gx.default.createElement(X,{variant:"secondary",size:"sm",onClick:n,className:"tw-text-warning hover:tw-bg-callout-warning/10"},"Open Model Settings"))))};var RIe=N(U());var iX=N(U()),Zft=({errorContent:t})=>iX.default.createElement("div",{className:"tw-my-2 tw-mb-6 tw-max-h-[180px] tw-overflow-y-scroll tw-rounded-xl tw-bg-modifier-error-rgb/5 tw-p-3"},iX.default.createElement("div",{className:"tw-mb-2 tw-text-sm tw-font-semibold tw-text-error"},"\u26A0\uFE0F Error occurred"),iX.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-xs tw-text-error"},t.trim()));var Dl=N(U(),1);function Jft(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var yx=N(U(),1),Xft=N(Ve(),1);function Qft(t,e=[]){let n=[];function r(i,s){let a=yx.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=yx.useMemo(()=>m,Object.values(m));return(0,Xft.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=yx.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>yx.createContext(s));return function(a){let l=a?.[t]||i;return yx.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,aQt(o,...e)]}function aQt(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return yx.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var yS=N(U(),1);var w1=N(U(),1);function _Ie(t){let e=w1.useRef(t);return w1.useEffect(()=>{e.current=t}),w1.useMemo(()=>(...n)=>e.current?.(...n),[])}function ept({prop:t,defaultProp:e,onChange:n=()=>{}}){let[r,o]=lQt({defaultProp:e,onChange:n}),i=t!==void 0,s=i?t:r,a=_Ie(n),l=yS.useCallback(c=>{if(i){let d=typeof c=="function"?c(t):c;d!==t&&a(d)}else o(c)},[i,t,o,a]);return[s,l]}function lQt({defaultProp:t,onChange:e}){let n=yS.useState(t),[r]=n,o=yS.useRef(r),i=_Ie(e);return yS.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}var tpt=N(U(),1),wE=globalThis?.document?tpt.useLayoutEffect:()=>{};var rpt=N(U(),1);function npt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function SIe(...t){return e=>{let n=!1,r=t.map(o=>{let i=npt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():npt(t[o],null)}}}}function opt(...t){return rpt.useCallback(SIe(...t),t)}var ipt=N(U(),1),pQt=N(yo(),1);var Ll=N(U(),1);var v1=N(Ve(),1),IIe=Ll.forwardRef((t,e)=>{let{children:n,...r}=t,o=Ll.Children.toArray(n),i=o.find(uQt);if(i){let s=i.props.children,a=o.map(l=>l===i?Ll.Children.count(s)>1?Ll.Children.only(null):Ll.isValidElement(s)?s.props.children:null:l);return(0,v1.jsx)(TIe,{...r,ref:e,children:Ll.isValidElement(s)?Ll.cloneElement(s,void 0,a):null})}return(0,v1.jsx)(TIe,{...r,ref:e,children:n})});IIe.displayName="Slot";var TIe=Ll.forwardRef((t,e)=>{let{children:n,...r}=t;if(Ll.isValidElement(n)){let o=fQt(n);return Ll.cloneElement(n,{...dQt(r,n.props),ref:e?SIe(e,o):o})}return Ll.Children.count(n)>1?Ll.Children.only(null):null});TIe.displayName="SlotClone";var cQt=({children:t})=>(0,v1.jsx)(v1.Fragment,{children:t});function uQt(t){return Ll.isValidElement(t)&&t.type===cQt}function dQt(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{i(...a),o(...a)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function fQt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var spt=N(Ve(),1),mQt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],sX=mQt.reduce((t,e)=>{let n=ipt.forwardRef((r,o)=>{let{asChild:i,...s}=r,a=i?IIe:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,spt.jsx)(a,{...s,ref:o})});return n.displayName=`Primitive.${e}`,{...t,[e]:n}},{});var gd=N(U(),1);var lpt=N(U(),1);function apt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function hQt(...t){return e=>{let n=!1,r=t.map(o=>{let i=apt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():apt(t[o],null)}}}}function cpt(...t){return lpt.useCallback(hQt(...t),t)}var upt=N(U(),1);function gQt(t,e){return upt.useReducer((n,r)=>e[n][r]??n,t)}var PIe=t=>{let{present:e,children:n}=t,r=yQt(e),o=typeof n=="function"?n({present:r.isPresent}):gd.Children.only(n),i=cpt(r.ref,wQt(o));return typeof n=="function"||r.isPresent?gd.cloneElement(o,{ref:i}):null};PIe.displayName="Presence";function yQt(t){let[e,n]=gd.useState(),r=gd.useRef({}),o=gd.useRef(t),i=gd.useRef("none"),s=t?"mounted":"unmounted",[a,l]=gQt(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return gd.useEffect(()=>{let c=aX(r.current);i.current=a==="mounted"?c:"none"},[a]),wE(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=aX(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),wE(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=aX(r.current).includes(p.animationName);if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=aX(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:gd.useCallback(c=>{c&&(r.current=getComputedStyle(c)),n(c)},[])}}function aX(t){return t?.animationName||"none"}function wQt(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var lX=N(U(),1);var vQt=lX.useId||(()=>{}),xQt=0;function dpt(t){let[e,n]=lX.useState(vQt());return wE(()=>{t||n(r=>r??String(xQt++))},[t]),t||(e?`radix-${e}`:"")}var vE=N(Ve(),1),EIe="Collapsible",[bQt,A3r]=Qft(EIe),[CQt,AIe]=bQt(EIe),fpt=Dl.forwardRef((t,e)=>{let{__scopeCollapsible:n,open:r,defaultOpen:o,disabled:i,onOpenChange:s,...a}=t,[l=!1,c]=ept({prop:r,defaultProp:o,onChange:s});return(0,vE.jsx)(CQt,{scope:n,disabled:i,contentId:dpt(),open:l,onOpenToggle:Dl.useCallback(()=>c(u=>!u),[c]),children:(0,vE.jsx)(sX.div,{"data-state":OIe(l),"data-disabled":i?"":void 0,...a,ref:e})})});fpt.displayName=EIe;var ppt="CollapsibleTrigger",kIe=Dl.forwardRef((t,e)=>{let{__scopeCollapsible:n,...r}=t,o=AIe(ppt,n);return(0,vE.jsx)(sX.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":OIe(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...r,ref:e,onClick:Jft(t.onClick,o.onOpenToggle)})});kIe.displayName=ppt;var MIe="CollapsibleContent",NIe=Dl.forwardRef((t,e)=>{let{forceMount:n,...r}=t,o=AIe(MIe,t.__scopeCollapsible);return(0,vE.jsx)(PIe,{present:n||o.open,children:({present:i})=>(0,vE.jsx)(_Qt,{...r,ref:e,present:i})})});NIe.displayName=MIe;var _Qt=Dl.forwardRef((t,e)=>{let{__scopeCollapsible:n,present:r,children:o,...i}=t,s=AIe(MIe,n),[a,l]=Dl.useState(r),c=Dl.useRef(null),u=opt(e,c),d=Dl.useRef(0),f=d.current,p=Dl.useRef(0),m=p.current,h=s.open||a,g=Dl.useRef(h),y=Dl.useRef(void 0);return Dl.useEffect(()=>{let w=requestAnimationFrame(()=>g.current=!1);return()=>cancelAnimationFrame(w)},[]),wE(()=>{let w=c.current;if(w){y.current=y.current||{transitionDuration:w.style.transitionDuration,animationName:w.style.animationName},w.style.transitionDuration="0s",w.style.animationName="none";let v=w.getBoundingClientRect();d.current=v.height,p.current=v.width,g.current||(w.style.transitionDuration=y.current.transitionDuration,w.style.animationName=y.current.animationName),l(r)}},[s.open,r]),(0,vE.jsx)(sX.div,{"data-state":OIe(s.open),"data-disabled":s.disabled?"":void 0,id:s.contentId,hidden:!h,...i,ref:u,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":m?`${m}px`:void 0,...t.style},children:h&&o})});function OIe(t){return t?"open":"closed"}var mpt=fpt;var cs=mpt,hu=kIe,us=NIe;Kt();vt();var jo=N(U()),TQt="shimmer 2s ease-in-out infinite",nV=5e3,IQt=(t,e)=>{if(!e)return null;if(e.length>nV)return`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`;try{let n=_v.format(t,e);return n.length>nV?n.slice(0,nV)+`

\u2026 (truncated ${(n.length-nV).toLocaleString()} characters for display)`:n}catch{return e.length>nV?`Tool '${t}' returned ${e.length.toLocaleString()} characters. The full output is preserved in chat history but omitted here to keep the UI responsive.`:e}},hpt=({toolName:t,displayName:e,emoji:n,isExecuting:r,result:o,confirmationMessage:i,onAccept:s,onReject:a})=>{let[l,c]=(0,jo.useState)(!1),u=(0,jo.useMemo)(()=>IQt(t,o),[t,o]),d=r&&!o,f=!d&&u!==null;return jo.default.createElement(cs,{open:f?l:!1,onOpenChange:c,disabled:!f,"aria-disabled":!f,className:"tw-my-3 tw-w-full sm:tw-max-w-sm"},jo.default.createElement("div",{className:oe("tw-rounded-md tw-border tw-border-border tw-bg-secondary/50",d&&"tw-relative tw-overflow-hidden")},d&&jo.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-[1] tw-overflow-hidden"},jo.default.createElement("div",{className:"tw-absolute tw-inset-0 -tw-translate-x-full",style:{background:"linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%)",animation:TQt}})),jo.default.createElement(hu,{className:oe("tw-flex tw-w-full tw-items-center tw-justify-between tw-px-3 tw-py-2.5 tw-text-sm sm:tw-px-4 sm:tw-py-3",f&&"hover:tw-bg-secondary/70",!f&&"tw-cursor-default")},jo.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},jo.default.createElement("span",{className:"tw-text-base"},n),jo.default.createElement("span",{className:"tw-font-medium"},t==="readNote"?`${d?"Reading":"Read"} ${e}`:`${d?"Calling":"Called"} ${e}`,d&&t!=="readNote"&&"..."),d&&i&&jo.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"\u2022 ",i,"...")),jo.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!d&&s&&a&&jo.default.createElement(jo.default.Fragment,null,jo.default.createElement("button",{type:"button",onClick:p=>{p.stopPropagation(),s()},className:"hover:tw-bg-green-rgb/20 tw-rounded tw-p-1",title:"Accept"},jo.default.createElement(Ro,{className:"tw-size-4 tw-text-success"})),jo.default.createElement("button",{type:"button",onClick:p=>{p.stopPropagation(),a()},className:"hover:tw-bg-red-rgb/20 tw-rounded tw-p-1",title:"Reject"},jo.default.createElement(Sn,{className:"tw-size-4 tw-text-error"}))),f&&jo.default.createElement(Di,{className:oe("tw-size-4 tw-text-muted tw-transition-transform",l&&"tw-rotate-90")}))),jo.default.createElement(us,null,jo.default.createElement("div",{className:"tw-border-t tw-border-border tw-px-3 tw-py-2.5 sm:tw-px-4 sm:tw-py-3"},jo.default.createElement("div",{className:"tw-text-sm tw-text-muted"},jo.default.createElement("pre",{className:"tw-overflow-x-auto tw-whitespace-pre-wrap tw-font-mono tw-text-xs"},u??"No result available"))))))};ye();ws();var gpt=60*60*1e3,x1=()=>(window.__copilotToolCallRoots||(window.__copilotToolCallRoots=new Map),window.__copilotToolCallRoots),b1=()=>(window.__copilotErrorBlocks||(window.__copilotErrorBlocks=new Map),window.__copilotErrorBlocks),LIe=(t,e,n)=>{if(e.size>0)return;n.get(t)===e&&n.delete(t)},DIe=(t,e,n,r,o,i)=>{try{r.root.unmount()}catch(s){ee(`Error unmounting tool call root during ${o}`,n,s)}r.isUnmounting=!1,e.get(n)===r&&e.delete(n),LIe(t,e,i)},ypt=(t,e,n,r,o,i)=>{e.delete(n),r.isUnmounting=!0,window.setTimeout(()=>{try{r.root.unmount()}catch(s){ee(`Error unmounting tool call root during ${o}`,n,s)}r.isUnmounting=!1,LIe(t,e,i)},0)},wS=(t,e,n,r,o,i)=>{r.isUnmounting||(r.isUnmounting=!0,window.setTimeout(()=>{let s=i.get(t),a=s?.get(n);if(!s||a!==r){r.isUnmounting=!1,LIe(t,e,i);return}DIe(t,s,n,a,o,i)},0))},wpt=(t,e,n,r,o,i)=>{let s=n.get(r);return s?.isUnmounting&&(DIe(e,n,r,s,`${i} (finalizing stale root)`,x1()),s=void 0),s&&s.container&&s.container!==o&&(ypt(e,n,r,s,`${i} (container changed)`,x1()),s=void 0),s||(s={root:sr(o,t),isUnmounting:!1,container:o},n.set(r,s)),s},vpt=(t,e,n,r,o,i)=>{let s=n.get(r);return s?.isUnmounting&&(DIe(e,n,r,s,`${i} (finalizing stale error root)`,b1()),s=void 0),s&&s.container&&s.container!==o&&(ypt(e,n,r,s,`${i} (container changed)`,b1()),s=void 0),s||(s={root:sr(o,t),isUnmounting:!1,container:o},n.set(r,s)),s},xpt=(t,e)=>{t.root.render(RIe.default.createElement(hpt,{toolName:e.toolName,displayName:e.displayName,emoji:e.emoji,isExecuting:e.isExecuting,result:e.result||null,confirmationMessage:e.confirmationMessage}))},bpt=(t,e)=>{t.root.render(RIe.default.createElement(Zft,{errorContent:e.errorContent}))},Cpt=(t,e,n,r)=>{let o=e.get(n);o&&wS(t,e,n,o,r,x1())},_pt=(t,e,n,r)=>{let o=e.get(n);o&&wS(t,e,n,o,r,b1())},Spt=t=>{let e=x1(),n=e.get(t);return n||(n=new Map,e.set(t,n)),n},Tpt=t=>{let e=b1(),n=e.get(t);return n||(n=new Map,e.set(t,n)),n},Ipt=(t=Date.now())=>{let e=x1();e.forEach((n,r)=>{n.forEach((o,i)=>{if(o.container){if(o.container.isConnected)return;wS(r,n,i,o,"stale cleanup (detached container)",e);return}let s=Number.parseInt(r,10);Number.isNaN(s)||t-s<gpt||wS(r,n,i,o,"stale cleanup (legacy record)",e)})})},Ppt=(t=Date.now())=>{let e=b1();e.forEach((n,r)=>{n.forEach((o,i)=>{if(o.container){if(o.container.isConnected)return;wS(r,n,i,o,"stale error cleanup (detached container)",e);return}let s=Number.parseInt(r,10);Number.isNaN(s)||t-s<gpt||wS(r,n,i,o,"stale error cleanup (legacy record)",e)})})},Ept=(t,e,n)=>{let r=x1();e.forEach((o,i)=>{wS(t,e,i,o,n,r)})},Apt=(t,e,n)=>{let r=b1();e.forEach((o,i)=>{wS(t,e,i,o,n,r)})};Kt();vt();var $l=N(U()),PQt=t=>{if(t<60)return`${t}s`;let e=Math.floor(t/60),n=t%60;return`${e}m ${n}s`},EQt=()=>{let t=[{row:0,col:0,animIndex:2},{row:0,col:1,animIndex:1},{row:0,col:2,animIndex:0},{row:1,col:1,animIndex:3},{row:2,col:0,animIndex:4},{row:2,col:1,animIndex:5},{row:2,col:2,animIndex:6}],e=2.5,n=3,r=e*3+n*2;return $l.default.createElement("svg",{width:r,height:r,viewBox:`0 0 ${r} ${r}`,className:"copilot-spinner"},t.map(o=>{let i=o.col*(e+n)+e/2,s=o.row*(e+n)+e/2;return $l.default.createElement("circle",{key:`${o.row}-${o.col}`,cx:i,cy:s,r:e/2,className:`copilot-spinner-dot copilot-spinner-dot-${o.animIndex}`})}))},kpt=({status:t,elapsedSeconds:e,steps:n,isStreaming:r})=>{let[o,i]=(0,$l.useState)(t==="reasoning"),[s,a]=(0,$l.useState)(t);if(t!==s&&(a(t),t==="reasoning"?i(!0):(t==="collapsed"||t==="complete")&&i(!1)),t==="idle")return null;let l=t==="reasoning",c=!l&&n.length>0;return $l.default.createElement(cs,{open:c?o:l,onOpenChange:c?i:void 0,disabled:!c,className:"agent-reasoning-block"},$l.default.createElement(hu,{asChild:!0,disabled:!c},$l.default.createElement("div",{className:oe("agent-reasoning-header",c&&"tw-cursor-pointer",!c&&"tw-cursor-default")},$l.default.createElement("span",{className:"agent-reasoning-icon"},l?$l.default.createElement(EQt,null):$l.default.createElement(Di,{className:oe("tw-size-3 tw-text-muted tw-transition-transform",o&&"tw-rotate-90")})),$l.default.createElement("span",{className:"agent-reasoning-title"},l?"Reasoning":"Thought for"),$l.default.createElement("span",{className:"agent-reasoning-timer"},PQt(e)))),$l.default.createElement(us,null,n.length>0&&$l.default.createElement("ul",{className:"agent-reasoning-steps"},n.map((u,d)=>$l.default.createElement("li",{key:d,className:"agent-reasoning-step"},u)))))};It();Kt();yye();ye();qe();var xE=require("obsidian"),mt=N(U());Se();var cX="copilot-collapsible",AQt=()=>(window.__copilotCollapsibleStates||(window.__copilotCollapsibleStates=new Map),window.__copilotCollapsibleStates),Mpt=t=>{let e=AQt(),n=e.get(t);return n||(n=new Map,e.set(t,n)),n},$Ie=(t,e)=>{let n=t.replace(/[^a-zA-Z0-9_-]/g,"_");return`${cX}-${n}-${e}`},Npt=(t,e,n={})=>{let r=n.overwriteExisting??!0;t.querySelectorAll(`details[id^="${cX}-"]`).forEach(i=>{let s=i.id;s&&(!r&&e.has(s)||e.set(s,i.open))})},uX=(t,e)=>{let n=typeof t.composedPath=="function"?t.composedPath():[];for(let i of n)if(i instanceof HTMLElement&&i.tagName==="DETAILS"){let s=i;if(s.id.startsWith(`${cX}-`)&&e.contains(s))return s}let r=t.target;if(!(r instanceof Element))return null;let o=r.closest(`details[id^="${cX}-"]`);return o?.instanceOf(HTMLElement)&&o.tagName==="DETAILS"&&e.contains(o)?o:null},FIe=(t,e)=>{let n=e.querySelector("summary");if(!n)return!1;let r=t.target;return r instanceof Node?n.contains(r):(typeof t.composedPath=="function"?t.composedPath():[]).includes(n)};var kQt=/^\d+-\d+$/,MQt=t=>{let e=t.querySelector(".footnotes");e?(e.querySelectorAll("hr, hr.footnotes-sep").forEach(n=>n.remove()),e.querySelectorAll("a.footnote-backref, a.footnote-link.footnote-backref").forEach(n=>n.remove())):t.querySelectorAll("a.footnote-backref, a.footnote-link.footnote-backref").forEach(n=>n.remove()),t.querySelectorAll('a.footnote-ref, sup a[href^="#fn"], sup a[href^="#fn-"], a[href^="#fn"], a[href^="#fn-"]').forEach(n=>{let r=n.textContent?.trim()??"";if(!r||!kQt.test(r))return;let[o]=r.split("-");o&&o!==r&&(n.textContent=o)})},rV=/\[(\d+(?:\s*,\s*\d+)*)\]/g,NQt=t=>{let e=t.querySelectorAll(".copilot-sources__item");if(e.length===0)return;let n=new Map;if(e.forEach(l=>{let c=l.querySelector(".copilot-sources__index"),u=l.querySelector(".copilot-sources__text");if(!c||!u)return;let d=c.textContent?.match(/\[(\d+)\]/);if(!d)return;let f=parseInt(d[1],10),p=u.querySelector("a");p&&n.set(f,p)}),n.size===0)return;let r=t.doc,o=t.querySelector(".copilot-sources"),i=[],s=r.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(l){return o?.contains(l)||l.parentElement?.closest("code, pre")?NodeFilter.FILTER_REJECT:(rV.lastIndex=0,rV.test(l.textContent||"")?(rV.lastIndex=0,NodeFilter.FILTER_ACCEPT):NodeFilter.FILTER_REJECT)}}),a;for(;a=s.nextNode();)i.push(a);i.forEach(l=>{let c=l.textContent||"";rV.lastIndex=0;let u=r.createDocumentFragment(),d=0,f;for(;(f=rV.exec(c))!==null;){f.index>d&&u.appendChild(r.createTextNode(c.slice(d,f.index)));let m=f[1].split(/\s*,\s*/).map(g=>parseInt(g.trim(),10));if(m.every(g=>n.has(g))){let g=r.createElement("span");g.className="copilot-citation-group",g.appendChild(r.createTextNode("[")),m.forEach((y,w)=>{w>0&&g.appendChild(r.createTextNode(", "));let v=n.get(y),x=r.createElement("a");for(let b of Array.from(v.attributes))x.setAttribute(b.name,b.value);x.className=`copilot-citation-link${v.className?` ${v.className}`:""}`,x.textContent=String(y),x.setAttribute("aria-label",`Source ${y}`),g.appendChild(x)}),g.appendChild(r.createTextNode("]")),u.appendChild(g)}else u.appendChild(r.createTextNode(f[0]));d=f.index+f[0].length}d<c.length&&u.appendChild(r.createTextNode(c.slice(d)));let p=l.parentElement?.classList.contains("copilot-citation-ref")?l.parentElement:l;p.parentNode?.replaceChild(u,p)})};function OQt({context:t}){return!t||!t.notes?.length&&!t.urls?.length&&!t.webTabs?.length&&!t.tags?.length&&!t.folders?.length&&!t.selectedTextContexts?.length?null:mt.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-gap-2"},t.notes.map((e,n)=>mt.default.createElement(cn,{key:`note-${n}-${e.path}`},mt.default.createElement(un,{asChild:!0},mt.default.createElement("div",null,mt.default.createElement(sJ,{note:e}))),mt.default.createElement(on,{className:"tw-max-w-sm tw-break-words"},e.path))),t.urls.map((e,n)=>mt.default.createElement(cn,{key:`url-${n}-${e}`},mt.default.createElement(un,{asChild:!0},mt.default.createElement("div",null,mt.default.createElement(aJ,{url:e}))),mt.default.createElement(on,{className:"tw-max-w-sm tw-break-words"},e))),t.webTabs?.map((e,n)=>mt.default.createElement(cn,{key:`webTab-${n}-${e.url}`},mt.default.createElement(un,{asChild:!0},mt.default.createElement("div",null,mt.default.createElement(lJ,{webTab:e}))),mt.default.createElement(on,{className:"tw-max-w-sm tw-break-words"},e.title?mt.default.createElement("div",{className:"tw-text-left"},mt.default.createElement("div",{className:"tw-font-medium"},e.title),mt.default.createElement("div",null,e.url)):e.url))),t.tags?.map((e,n)=>mt.default.createElement(cn,{key:`tag-${n}-${e}`},mt.default.createElement(un,{asChild:!0},mt.default.createElement("div",null,mt.default.createElement(wut,{tag:e}))),mt.default.createElement(on,{className:"tw-max-w-sm tw-break-words"},e))),t.folders?.map((e,n)=>mt.default.createElement(cn,{key:`folder-${n}-${e}`},mt.default.createElement(un,{asChild:!0},mt.default.createElement("div",null,mt.default.createElement(cJ,{folder:e}))),mt.default.createElement(on,{className:"tw-max-w-sm tw-break-words"},e))),t.selectedTextContexts?.map((e,n)=>mt.default.createElement(cn,{key:`selectedText-${n}-${e.id}`},mt.default.createElement(un,{asChild:!0},mt.default.createElement("div",null,mt.default.createElement(vut,{selectedText:e}))),mt.default.createElement(on,{className:"tw-max-w-sm tw-break-words"},e.sourceType==="web"?e.url:e.notePath))))}var RQt=({message:t,app:e,isStreaming:n,onRegenerate:r,onEdit:o,onDelete:i})=>{let[s,a]=(0,mt.useState)(!1),[l,c]=(0,mt.useState)(!1),u=(0,mt.useMemo)(()=>tj(t.message),[t.message]),d=(0,mt.useMemo)(()=>!u?.hasReasoning||u.status==="idle"?null:{status:u.status,elapsedSeconds:u.elapsedSeconds,steps:u.steps},[u]),f=(0,mt.useRef)(null),p=(0,mt.useRef)(null),m=(0,mt.useRef)(!1),h=(0,mt.useRef)(t.id||(t.timestamp?.epoch?String(t.timestamp.epoch):`temp-${Date.now()}-${Math.random()}`)),g=(0,mt.useRef)(Spt(h.current)),y=(0,mt.useRef)(Tpt(h.current)),v=(0,mt.useRef)(Mpt(h.current)).current,x=Ht(),b=()=>{if(!navigator.clipboard||!navigator.clipboard.writeText)return;let $=ng(t.message);navigator.clipboard.writeText($).then(()=>{a(!0),window.setTimeout(()=>{a(!1)},2e3)}).catch(B=>z("Clipboard writeText failed",B))},_=(0,mt.useCallback)($=>{let B=e.workspace.getActiveFile(),W=B?B.path:"",F=(R,L,K,Y)=>{let re="margin: 0.5rem 0 1.5rem; padding: 0.75rem; border: 1px solid var(--background-modifier-border); border-radius: 4px; background-color: var(--background-secondary)",ae="cursor: pointer; color: var(--text-muted); font-size: 0.8em; margin-bottom: 0.5rem; user-select: none",ve="margin-top: 0.75rem; padding: 0.75rem; border-radius: 4px; background-color: var(--background-primary)",Te=`<${L}>`,Ee=0,nt=ke=>ke.trim()+`
`,rt=(ke,Ln,He)=>`<details id="${He}"${Ln} style="${re}"><summary style="${ae}">${K}</summary><div class="tw-text-muted" style="${ve}">${nt(ke)}</div></details>

`;if(n&&R.includes(Te)){let ke=new RegExp(`<${L}>([\\s\\S]*?)<\\/${L}>`,"g");R=R.replace(ke,(He,Ie)=>{let dt=`${L}-${Ee}`;Ee+=1;let Me=$Ie(h.current,dt),Ue=v.get(Me)?" open":"";return rt(Ie,Ue,Me)});let Ln=new RegExp(`<${L}>([\\s\\S]*)$`);return R=R.replace(Ln,(He,Ie)=>`<div style="${re}"><div style="${ae}">${Y}</div><div class="tw-text-muted" style="${ve}">${nt(Ie)}</div></div>`),R}let Jt=new RegExp(`<${L}>([\\s\\S]*?)<\\/${L}>`,"g");return R.replace(Jt,(ke,Ln)=>{let He=`${L}-${Ee}`;Ee+=1;let Ie=$Ie(h.current,He),dt=v.get(Ie)?" open":"";return rt(Ln,dt,Ie)})},Z=R=>F(R,"think","Thought for a while","Thinking..."),V=R=>{let L=ae=>ae.replace(/<(\/?)writeToFile>/g,"<$1writeFile>"),K=ae=>{let ve=/```(?:xml)?\s*([\s\S]*?<writeFile>[\s\S]*?<\/writeFile>[\s\S]*?)\s*```/g;return ae.replace(ve,(Te,Ee)=>Ee.trim())},Y=ae=>{if(!n)return ae;let ve=/```xml\s*([\s\S]*?<writeFile>[\s\S]*?)$/g;return ae.replace(ve,(Te,Ee)=>Ee.trim())},re=L(R);return re=K(re),re=Y(re),F(re,"writeFile","Generated new content","Generating changes...")},H=(R,L,K)=>R.split(/(```[\s\S]*?```|`[^`]*`)/g).map((re,ae)=>ae%2===0?re.replace(L,(ve,Te)=>{let Ee=e.metadataCache.getFirstLinkpathDest(Te,W);return Ee?K(Ee):ve}):re).join(""),te=oL($),fe=H(te,/!\[\[(.*?)]]/g,R=>`![](${e.vault.getResourcePath(R)})`),me=Z(fe),j=V(me),J=j9e(j,x.enableInlineCitations).replace(/\[\^(\d+)\](?!:)/g,'<span class="copilot-citation-ref">[$1]</span>'),M=H(J,/(?<!!)\[\[([^\]]+)]]/g,R=>`<a href="obsidian://open?file=${encodeURIComponent(R.path)}">${R.basename}</a>`);return(R=>{if(!n)return R;let L=/!\[([^\]]*)\]\(([^)]+)\)/g;return R.replace(L,(K,Y,re)=>{let ae=Ute(re);if(!ae)return K;let ve=Y||"YouTube Video",Te=`https://i.ytimg.com/vi/${ae}/hqdefault.jpg`;return`[![${ve}](${Te})](${re})`})})(M)},[e,n,x.enableInlineCitations,v]);(0,mt.useEffect)(()=>{let $=f.current;if(!$||t.sender===uo||!n)return;let B=Z=>{if(Z instanceof PointerEvent&&(Z.button!==0||!Z.isPrimary))return;let V=uX(Z,$);if(!V||!FIe(Z,V))return;let H=!V.open;V.open=H,v.set(V.id,H)},W=Z=>{let V=uX(Z,$);!V||!FIe(Z,V)||Z.preventDefault()},F=Z=>{let V=uX(Z,$);V&&v.set(V.id,V.open)};return $.addEventListener("pointerdown",B,!0),$.addEventListener("click",W,!0),$.addEventListener("toggle",F,!0),()=>{$.removeEventListener("pointerdown",B,!0),$.removeEventListener("click",W,!0),$.removeEventListener("toggle",F,!0)}},[n,t.sender,v]),(0,mt.useEffect)(()=>{if(m.current=!1,f.current&&t.sender!==uo){p.current||(p.current=new xE.Component,p.current.load()),Npt(f.current,v,{overwriteExisting:!n});let $=t.message,B=u?.contentAfter??$,W=_(B),F=gye(W,h.current);if(!m.current){let Z=f.current.doc,V=new Set,H=new Set;f.current.querySelectorAll('[id^="tool-call-"]').forEach(M=>{let E=M.id.replace("tool-call-","");V.add(E)}),f.current.querySelectorAll('[id^="error-block-"]').forEach(M=>{let E=M.id.replace("error-block-","");H.add(E)}),f.current.querySelectorAll(".message-segment").forEach(M=>M.remove());let j=0;F.segments.forEach(M=>{if(M.type==="text"&&M.content.trim()){let E=f.current.children[j],R=Z.createElement("div");R.className="message-segment",E?f.current.insertBefore(R,E):f.current.appendChild(R),xE.MarkdownRenderer.renderMarkdown(M.content,R,"",p.current).then(()=>MQt(R)).catch(L=>z("renderMarkdown failed",L)),j++}else if(M.type==="toolCall"&&M.toolCall){let E=M.toolCall.id,R=Z.getElementById(`tool-call-${E}`);if(!R){let K=f.current.children[j],Y=Z.createElement("div");Y.className="tool-call-container",Y.id=`tool-call-${E}`,K?f.current.insertBefore(Y,K):f.current.appendChild(Y),R=Y}let L=wpt(e,h.current,g.current,E,R,"render refresh");!m.current&&!L.isUnmounting&&xpt(L,M.toolCall),j++}else if(M.type==="error"&&M.error){let E=M.error.id,R=Z.getElementById(`error-block-${E}`);if(!R){let K=f.current.children[j],Y=Z.createElement("div");Y.className="error-block-container",Y.id=`error-block-${E}`,K?f.current.insertBefore(Y,K):f.current.appendChild(Y),R=Y}let L=vpt(e,h.current,y.current,E,R,"error render");!m.current&&!L.isUnmounting&&bpt(L,M.error),j++}});let G=new Set(F.segments.filter(M=>M.type==="toolCall"&&M.toolCall).map(M=>M.toolCall.id));V.forEach(M=>{if(!G.has(M)){let E=Z.getElementById(`tool-call-${M}`);E&&(Cpt(h.current,g.current,M,"tool call removal"),E.remove())}});let J=new Set(F.segments.filter(M=>M.type==="error"&&M.error).map(M=>M.error.id));H.forEach(M=>{if(!J.has(M)){let E=Z.getElementById(`error-block-${M}`);E&&(_pt(h.current,y.current,M,"error block removal"),E.remove())}}),f.current&&!n&&NQt(f.current)}}return()=>{m.current=!0}},[t,e,p,n,_,v,u]),(0,mt.useEffect)(()=>{let $=p,B=h.current,W=g.current,F=y.current;return(()=>{Ipt(),Ppt()})(),()=>{m.current=!0,window.setTimeout(()=>{$.current&&($.current.unload(),$.current=null),B.startsWith("temp-")&&(Ept(B,W,"component cleanup"),Apt(B,F,"component cleanup"))},0)}},[]);let T=()=>{c(!0)},S=()=>{c(!1)},P=$=>{c(!1),o&&o($)},A=()=>{t.sources&&t.sources.length>0&&new rX(e,t.sources).open()},O=()=>{let $=e.workspace.getMostRecentLeaf();if((!$||!($.view instanceof xE.MarkdownView))&&($=e.workspace.getLeaf(!1),!$||!($.view instanceof xE.MarkdownView)))return;let W=$.view.editor.getSelection().length>0;EA(t.message,W)},D=()=>t.content?mt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},t.content.map(($,B)=>$.type==="text"?mt.default.createElement("div",{key:B},t.sender===uo?mt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):mt.default.createElement("div",{ref:f,className:t.isErrorMessage?"tw-text-error":""})):$.type==="image_url"?mt.default.createElement("div",{key:B,className:"message-image-content"},mt.default.createElement("img",{src:$.image_url.url,alt:"User uploaded image",className:"chat-message-image"})):null)):t.sender===uo?mt.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)] tw-font-normal"},t.message):mt.default.createElement("div",{ref:f,className:t.isErrorMessage?"tw-text-error":""});return l&&t.sender===uo?mt.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col"},mt.default.createElement(qft,{initialValue:t.message,initialContext:t.context,onSave:P,onCancel:S,app:e})):mt.default.createElement("div",{className:"tw-my-1 tw-flex tw-w-full tw-flex-col"},mt.default.createElement("div",{className:oe("tw-group tw-mx-2 tw-rounded-md tw-p-2",t.sender===uo&&"tw-border tw-border-solid tw-border-border"),style:t.sender===uo?{backgroundColor:"var(--background-modifier-hover)"}:void 0},mt.default.createElement("div",{className:"tw-flex tw-max-w-full tw-flex-col tw-gap-2 tw-overflow-hidden"},!l&&mt.default.createElement(OQt,{context:t.context}),d&&t.sender!==uo&&mt.default.createElement(kpt,{status:d.status,elapsedSeconds:d.elapsedSeconds,steps:d.steps,isStreaming:n}),mt.default.createElement("div",{className:"message-content tw-break-words !tw-leading-[1.6]"},D()),t.responseMetadata?.wasTruncated&&t.sender!==uo&&mt.default.createElement(Yft,{message:t,app:e}),!n&&mt.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},mt.default.createElement("div",{className:"tw-text-xs tw-text-faint"},t.timestamp?.display),mt.default.createElement(Hft,{message:t,onCopy:b,isCopied:s,onInsertIntoEditor:O,onRegenerate:r,onEdit:T,onDelete:i,onShowSources:A,hasSources:!!(t.sources&&t.sources.length>0)})))))},UIe=RQt;rn();bi();It();bi();var C1=N(U());function BIe(){let t=tr(),[e,n]=(0,C1.useState)(null),r=(0,C1.useContext)(qA);return(0,C1.useEffect)(()=>{let o=()=>{let i=t.workspace.getActiveFile();n(i)};return r?.addEventListener(kf.ACTIVE_LEAF_CHANGE,o),()=>{r?.removeEventListener(kf.ACTIVE_LEAF_CHANGE,o)}},[t,r]),e}var Opt=N(U());bi();function zIe(){let t=tr();return(0,Opt.useCallback)((n,r)=>{let o=t.dragManager;if(!o)return;n.dataTransfer.setData("copilot/internal-drag","true");let i=t.metadataCache.fileToLinktext(r,""),s=o.dragLink(n.nativeEvent,i);o.onDragStart(n.nativeEvent,s)},[t])}Kt();ye();var _1=class extends Cr{constructor(e,n,r){let o=r?`Semantic search requires building an embedding index for your vault.

Use 'Refresh Vault Index' or 'Force Reindex Vault' commands to build the index after enabling. Pick your embedding model below.`:`Disabling semantic search will fall back to index-free lexical search (less resource-intensive, could be less accurate).

Your existing index will be preserved but not used.`,i=r?"Enable Semantic Search":"Disable Semantic Search",s=r?"Enable":"Disable";super(e,n,o,i,s,"Cancel")}};yp();ye();RN();yp();rD();var Rpt=require("obsidian");function Lpt(t,e=20){let n=app.metadataCache.getFileCache(t),r=[];if(n?.links)for(let o of n.links){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(r.push(i),r.length>=e))break}if(n?.embeds&&r.length<e)for(let o of n.embeds){let i=app.metadataCache.getFirstLinkpathDest(o.link,t.path);if(i&&(r.push(i),r.length>=e))break}return[...new Set(r)]}function Dpt(t,e=20){let n=[],r=app.metadataCache.getBacklinksForFile(t);if(r?.data)for(let[o]of r.data){let i=app.vault.getAbstractFileByPath(o);if(i instanceof Rpt.TFile&&(n.push(i),n.length>=e))break}return n}aG();ei();Se();var jIe=require("obsidian"),fX=20,$pt=.7,dX=.3;function LQt(){return Fa(q())}function DQt(t,e){let n=new Map;for(let r of t){let o=r.document.path,i=n.get(o);i?r.score>i&&n.set(o,r.score):n.set(o,r.score)}return n.delete(e),n}function Upt(t){if(t.size<=fX)return t;let e=Array.from(t.entries()).sort((n,r)=>r[1]-n[1]).slice(0,fX);return new Map(e)}function $Qt(t){return Array.isArray(t.embedding)&&t.embedding.length>0}function FQt(t){return t.some(e=>e.content.trim().length>0)}async function UQt({db:t,filePath:e,currentNoteEmbeddings:n}){let r=n.map(a=>IC.getDocsByEmbedding(t,a,{limit:fX,similarity:0})),i=(await Promise.all(r)).flat(),s=DQt(i,e);return Upt(s)}async function Fpt(t){let e=q(),n=new wp,r=Jg(app),o=Uq(app,t);try{let i=await n.resolveBaseUrl(Jm(e)),s=await n.searchRelated(i,o,{folderName:r,limit:fX}),a=new Map,l=s.results||[];for(let c of l){let u=i0(app,c.path);if(u===t||typeof c.score!="number"||Number.isNaN(c.score))continue;let d=a.get(u);(d===void 0||c.score>d)&&a.set(u,c.score)}if(e.debug){let c=l[0]?.path,u=c?i0(app,c):void 0;k(`RelevantNotes(Miyo): file_path=${o} folder_name=${r} received ${l.length} chunks, collected ${a.size} note scores (sample response.path=${c??"n/a"} \u2192 stripped=${u??"n/a"})`)}return Upt(a)}catch(i){return z(`RelevantNotes(Miyo): searchRelated failed for file_path=${o} folder_name=${r}: ${i.message}`),new Map}}async function BQt(t){if(LQt())return Fpt(t);let e=await Cp.getInstance().getDocumentsByPath(t);if(e.length===0)return new Map;let n=e.filter(r=>$Qt(r)).map(r=>r.embedding);if(n.length>0)try{let r=await Cp.getInstance().getDb();return UQt({db:r,filePath:t,currentNoteEmbeddings:n})}catch(r){return ee("RelevantNotes(Orama): failed to compute similarity scores",r),new Map}return FQt(e)?Fpt(t):new Map}function zQt(t){let e=new Map,r=Lpt(t).map(s=>s.path);for(let s of r)e.set(s,{links:!0,backlinks:!1});let i=Dpt(t).map(s=>s.path);for(let s of i)e.has(s)?e.set(s,{links:!0,backlinks:!0}):e.set(s,{links:!1,backlinks:!0});return e}function jQt(t,e){let n=new Map,r=$pt+dX;for(let[o,i]of t)n.set(o,i*$pt/r);for(let[o,i]of e){let s=0;i.links&&i.backlinks?s=dX:(i.links||i.backlinks)&&(s=dX*.8),n.set(o,(n.get(o)??0)+s)}return n}async function Bpt({filePath:t}){let e=app.vault.getAbstractFileByPath(t);if(!(e instanceof jIe.TFile))return[];let n=await BQt(t),r=zQt(e),o=jQt(n,r);return Array.from(o.entries()).sort((s,a)=>{let l=s[0],c=a[0],u=pX(n.get(l)??0),d=pX(n.get(c)??0);return u!==d?d-u:a[1]-s[1]}).map(([s,a])=>{let l=app.vault.getAbstractFileByPath(s);return!(l instanceof jIe.TFile)||l.extension!=="md"?null:{note:{path:s,title:l.basename},metadata:{score:a,similarityScore:n.get(s),hasOutgoingLinks:r.get(s)?.links??!1,hasBacklinks:r.get(s)?.backlinks??!1}}}).filter(s=>s!==null)}function pX(t){return t>.7?3:t>.55?2:1}Gge();vt();var bE=require("obsidian"),Ye=N(U());function VQt(t){let[e,n]=(0,Ye.useState)([]),[r,o]=(0,Ye.useState)(0),i=BIe();return(0,Ye.useEffect)(()=>qge(()=>o(s=>s+1)),[]),(0,Ye.useEffect)(()=>{async function s(){if(i?.path)try{let a=await Bpt({filePath:i.path});n(a)}catch(a){ee("Failed to fetch relevant notes",a),n([])}}s()},[i?.path,t,r]),e}function WQt(t,e){let[n,r]=(0,Ye.useState)(!0),[o,i]=(0,Ye.useState)(0);return(0,Ye.useEffect)(()=>qge(()=>i(s=>s+1)),[]),(0,Ye.useEffect)(()=>{if(!t)return;async function s(){try{let a=(await Promise.resolve().then(()=>(ei(),ji))).default,{getSettings:l}=await Promise.resolve().then(()=>(Se(),qy)),c=l();if(Fa(c)){let f=await a.getInstance().isIndexEmpty();r(!f);return}let d=await a.getInstance().hasIndex(t);r(d)}catch{r(!1)}}s()},[t,e,o]),n}function HQt({score:t}){let e=pX(t),n="\u{1F534}";return e===2&&(n="\u{1F7E0}"),e===3&&(n="\u{1F7E2}"),Ye.default.createElement("span",{className:"tw-text-sm"},n)}function KQt({note:t,onAddToChat:e,onNavigateToNote:n}){let r=tr(),[o,i]=(0,Ye.useState)(!1),[s,a]=(0,Ye.useState)(null),l=zIe(),c=(0,Ye.useCallback)(async()=>{if(s)return;let u=r.vault.getAbstractFileByPath(t.note.path);if(u instanceof bE.TFile){let d=await r.vault.cachedRead(u),f=d;if(d.startsWith("---")){let p=d.indexOf("---",3);p!==-1&&(f=d.slice(p+3).trim())}a(f.slice(0,1e3)+(f.length>1e3?"...":""))}},[r,s,t.note.path]);return(0,Ye.useEffect)(()=>{o&&c()},[o,c]),Ye.default.createElement(cs,{open:o,onOpenChange:i,className:"tw-rounded-md tw-border tw-border-solid tw-border-border"},Ye.default.createElement("div",{className:oe("tw-flex tw-items-center tw-justify-between tw-gap-2 tw-p-2")},Ye.default.createElement(X,{variant:"ghost2",size:"icon",className:"tw-shrink-0",asChild:!0},Ye.default.createElement(hu,null,Ye.default.createElement(Di,{className:oe("tw-size-4 tw-transition-transform tw-duration-200",{"rotate-90":o})}))),Ye.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-2"},Ye.default.createElement(HQt,{score:t.metadata.similarityScore??0})),Ye.default.createElement("div",{className:"tw-flex-1 tw-overflow-hidden"},Ye.default.createElement("a",{draggable:!0,onDragStart:u=>{let d=r.vault.getAbstractFileByPath(t.note.path);d instanceof bE.TFile&&l(u,d)},onClick:u=>{u.preventDefault();let d=u.metaKey||u.ctrlKey;n(d)},onAuxClick:u=>{u.button===1&&(u.preventDefault(),n(!0))},className:"tw-block tw-w-full tw-truncate tw-text-sm tw-font-bold tw-text-normal",title:`${t.note.title} - drag to insert wikilink`},t.note.title)),Ye.default.createElement(cn,null,Ye.default.createElement(un,{asChild:!0},Ye.default.createElement(X,{variant:"ghost2",size:"icon",onClick:e,className:"tw-shrink-0"},Ye.default.createElement(Md,{className:"tw-size-4"}))),Ye.default.createElement(on,null,"Add to Chat"))),Ye.default.createElement(us,null,Ye.default.createElement("div",{className:"tw-border-[0px] tw-border-t tw-border-solid tw-border-border tw-px-4 tw-py-2"},Ye.default.createElement("div",{className:"tw-whitespace-pre-wrap tw-text-wrap tw-break-all tw-text-xs tw-text-muted tw-opacity-75"},t.note.path),s&&Ye.default.createElement("div",{className:"tw-overflow-hidden tw-whitespace-pre-wrap tw-border-t tw-border-border tw-pb-4 tw-pt-2 tw-text-xs tw-text-normal"},s)),Ye.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-4 tw-border-[0px] tw-border-t tw-border-solid tw-border-border tw-px-4 tw-py-2 tw-text-xs tw-text-muted"},t.metadata.similarityScore!=null&&Ye.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ye.default.createElement("span",null,"Similarity: ",(t.metadata.similarityScore*100).toFixed(1),"%")),t.metadata.hasOutgoingLinks&&Ye.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ye.default.createElement(w$,{className:"tw-size-4"}),Ye.default.createElement("span",null,"Outgoing links")),t.metadata.hasBacklinks&&Ye.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ye.default.createElement(y$,{className:"tw-size-4"}),Ye.default.createElement("span",null,"Backlinks")))))}function qQt({note:t,onAddToChat:e,onNavigateToNote:n,children:r}){return Ye.default.createElement(R_,{key:t.note.path},Ye.default.createElement(L_,{asChild:!0},r),Ye.default.createElement(Kv,{className:"tw-flex tw-w-fit tw-min-w-72 tw-max-w-96 tw-flex-col tw-gap-2 tw-overflow-hidden"},Ye.default.createElement("span",{className:"tw-text-sm tw-text-normal"},t.note.title),Ye.default.createElement("span",{className:"tw-text-xs tw-text-muted"},t.note.path),Ye.default.createElement("div",{className:"tw-flex tw-gap-2"},Ye.default.createElement("button",{type:"button",onClick:e,className:"tw-inline-flex tw-items-center tw-gap-2 tw-border tw-border-solid tw-border-border !tw-bg-transparent !tw-shadow-none hover:!tw-bg-interactive-hover"},"Add to Chat ",Ye.default.createElement(Md,{className:"tw-size-4"})),Ye.default.createElement("button",{type:"button",onClick:o=>{let i=o.metaKey||o.ctrlKey;n(i)},className:"tw-inline-flex tw-items-center tw-gap-2 tw-border tw-border-solid tw-border-border !tw-bg-transparent !tw-shadow-none hover:!tw-bg-interactive-hover"},"Navigate to Note ",Ye.default.createElement(l$,{className:"tw-size-4"})))))}var mX=(0,Ye.memo)(({className:t,defaultOpen:e=!1})=>{let n=tr(),[r,o]=(0,Ye.useState)(0),[i,s]=(0,Ye.useState)(e),a=VQt(r),l=BIe(),c=gS(),u=WQt(l?.path??"",r),d=zIe(),f=(g,y=!1)=>{let w=n.vault.getAbstractFileByPath(g);w instanceof bE.TFile&&n.workspace.getLeaf(y).openFile(w).catch(x=>z("openFile failed",x))},p=g=>{c.insertTextWithPills(`[[${g}]]`,!0)},m=async()=>{l&&(await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().reindexFile(l),new bE.Notice(`Refreshed index for ${l.basename}`),o(r+1))},h=async()=>{let{getSettings:g,updateSetting:y}=await Promise.resolve().then(()=>(Se(),qy));g().enableSemanticSearchV3?(await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0}),o(r+1)):new _1(n,async()=>{y("enableSemanticSearchV3",!0),await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0}),o(r+1)},!0).open()};return Ye.default.createElement("div",{className:oe("tw-w-full tw-border tw-border-solid tw-border-transparent tw-border-b-border tw-pb-2",t)},Ye.default.createElement(cs,{open:i,onOpenChange:s},Ye.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-pb-2 tw-pl-1"},Ye.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-gap-2"},Ye.default.createElement("span",{className:"tw-font-semibold tw-text-normal"},"Relevant Notes"),Ye.default.createElement(Nn,{content:"Relevance is a combination of semantic similarity and links. Requires semantic search setting on.",contentClassName:"tw-w-64",buttonClassName:"tw-size-4 tw-text-muted"})),Ye.default.createElement("div",{className:"tw-flex tw-items-center"},u?Ye.default.createElement(cn,null,Ye.default.createElement(un,{asChild:!0},Ye.default.createElement(X,{variant:"ghost2",size:"icon",onClick:()=>void m()},Ye.default.createElement(P$,{className:"tw-size-4"}))),Ye.default.createElement(on,{side:"bottom"},"Reindex Current Note")):Ye.default.createElement(X,{variant:"secondary",size:"sm",onClick:()=>void h()},"Build Index"),a.length>0&&Ye.default.createElement(hu,{asChild:!0},Ye.default.createElement(X,{variant:"ghost2",size:"icon"},i?Ye.default.createElement($s,{className:"tw-size-5"}):Ye.default.createElement(hr,{className:"tw-size-5"}))))),a.length===0&&u&&Ye.default.createElement("div",{className:"tw-flex tw-max-h-12 tw-flex-wrap tw-items-center tw-gap-x-2 tw-gap-y-1 tw-overflow-y-hidden tw-px-1"},Ye.default.createElement("span",{className:"tw-text-xs tw-text-muted"},"No relevant notes found")),!i&&a.length>0&&Ye.default.createElement("div",{className:"tw-flex tw-max-h-6 tw-flex-wrap tw-gap-x-2 tw-gap-y-1 tw-overflow-y-hidden tw-px-1"},a.map(g=>Ye.default.createElement(qQt,{key:g.note.path,note:g,onAddToChat:()=>p(g.note.title),onNavigateToNote:y=>f(g.note.path,y)},Ye.default.createElement(ro,{variant:"outline",key:g.note.path,draggable:!0,onDragStart:y=>{let w=n.vault.getAbstractFileByPath(g.note.path);w instanceof bE.TFile&&d(y,w)},className:"tw-max-w-40 tw-text-xs tw-text-muted hover:tw-cursor-pointer hover:tw-bg-interactive-hover",title:`${g.note.title} - drag to insert wikilink`},Ye.default.createElement("span",{className:"tw-truncate"},g.note.title))))),Ye.default.createElement(us,null,Ye.default.createElement("div",{className:"tw-flex tw-max-h-screen tw-flex-col tw-gap-2 tw-overflow-y-auto tw-px-1 tw-py-2"},a.map(g=>Ye.default.createElement(KQt,{note:g,key:g.note.path,onAddToChat:()=>p(g.note.title),onNavigateToNote:y=>f(g.note.path,y)}))))))});mX.displayName="RelevantNotes";Ir();Qi();rn();var yd=N(U());Kt();var wx=yd.forwardRef(({className:t,...e},n)=>yd.createElement("div",{ref:n,className:oe("tw-rounded-xl tw-border tw-border-border tw-bg-primary tw-text-normal tw-shadow",t),...e}));wx.displayName="Card";var vx=yd.forwardRef(({className:t,...e},n)=>yd.createElement("div",{ref:n,className:oe("tw-flex tw-flex-col tw-space-y-1.5 tw-p-6",t),...e}));vx.displayName="CardHeader";var CE=yd.forwardRef(({className:t,...e},n)=>yd.createElement("div",{ref:n,className:oe("tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));CE.displayName="CardTitle";var GQt=yd.forwardRef(({className:t,...e},n)=>yd.createElement("div",{ref:n,className:oe("tw-text-sm tw-text-muted",t),...e}));GQt.displayName="CardDescription";var xx=yd.forwardRef(({className:t,...e},n)=>yd.createElement("div",{ref:n,className:oe("tw-p-6 tw-pt-0",t),...e}));xx.displayName="CardContent";var YQt=yd.forwardRef(({className:t,...e},n)=>yd.createElement("div",{ref:n,className:oe("tw-flex tw-items-center tw-p-6 tw-pt-0",t),...e}));YQt.displayName="CardFooter";It();Se();vt();var Vo=N(U());var VIe={activeNote:{title:"Active Note Insights",prompts:["Provide three follow-up questions worded as if I'm asking you based on {activeNote}?","What key questions does {activeNote} answer?","Give me a quick recap of {activeNote} in two sentences."]},quoteNote:{title:"Note Link Chat",prompts:["Based on [[<note>]], what improvements should we focus on next?","Summarize the key points from [[<note>]].","Summarize the recent updates from [[<note>]].","Roast my writing in [[<note>]] and give concrete actionable feedback"]},fun:{title:"Test LLM",prompts:["9.11 and 9.8, which is bigger?","What's the longest river in the world?","If a lead ball and a feather are dropped simultaneously from the same height, which will reach the ground first?"]},qaVault:{title:"Vault Q&A",prompts:["What insights can I gather about <topic> from my notes?","Explain <concept> based on my stored notes.","Highlight important details on <topic> from my notes.","Based on my notes on <topic>, what is the question that I should be asking, but am not?"]},copilotPlus:{title:"Copilot Plus",prompts:["Give me a recap of last week @vault","What are the key takeaways from my notes on <topic> @vault","Summarize <url> in under 10 bullet points","Summarize <youtube_video_url>","@websearch what are most recent updates in the AI industry","What are the key insights from this paper <arxiv_url>","What new methods are proposed in this paper [[<note_with_embedded_pdf>]]"]}},zpt={llm_chain:["activeNote","quoteNote","fun"],vault_qa:["qaVault","qaVault","quoteNote"],copilot_plus:["copilotPlus","copilotPlus","copilotPlus"],project:["copilotPlus","copilotPlus","copilotPlus"]};function ZQt(t="llm_chain"){let e=zpt[t]||zpt.llm_chain,n={};return e.map(r=>(n[r]||(n[r]=[...VIe[r].prompts].sort(()=>Math.random()-.5)),{title:VIe[r].title,text:n[r].pop()||VIe[r].prompts[0]}))}var jpt=({onClick:t})=>{let[e]=kd(),n=(0,Vo.useMemo)(()=>ZQt(e),[e]),o=Ht().indexVaultToVectorStore;return Vo.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Vo.default.createElement(wx,{className:"tw-w-full tw-bg-transparent"},Vo.default.createElement(vx,{className:"tw-px-2"},Vo.default.createElement(CE,null,"Suggested Prompts")),Vo.default.createElement(xx,{className:"tw-p-2 tw-pt-0"},Vo.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},n.map(i=>Vo.default.createElement("div",{key:i.text,className:"tw-flex tw-justify-between tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-2 tw-text-sm"},Vo.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},Vo.default.createElement("div",{className:"tw-text-muted"},i.title),Vo.default.createElement("div",null,i.text)),Vo.default.createElement("div",{className:"tw-flex tw-h-full tw-items-start"},Vo.default.createElement(cn,null,Vo.default.createElement(un,{asChild:!0},Vo.default.createElement(X,{variant:"ghost2",size:"fit",className:"tw-text-muted",onClick:()=>t(i.text)},Vo.default.createElement(Md,{className:"tw-size-4"}))),Vo.default.createElement(on,null,"Add to Chat")))))))),e==="vault_qa"&&Vo.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-2 tw-text-sm"},"Please note that this is a retrieval-based QA. Questions should contain keywords and concepts that exist literally in your vault"),e==="vault_qa"&&o==="NEVER"&&Vo.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-2 tw-text-sm"},Vo.default.createElement("div",null,Vo.default.createElement(dl,{className:"tw-size-4"})," Your auto-index strategy is set to"," ",Vo.default.createElement("b",null,"NEVER"),". Before proceeding, click the"," ",Vo.default.createElement("span",{className:"tw-text-accent"},"Refresh Index")," button below or run the"," ",Vo.default.createElement("span",{className:"tw-text-accent"},"Copilot command: Index (refresh) vault for QA")," ","to update the index.")))};It();It();var gu=N(U()),Vpt=({chatHistory:t})=>{let[e,n]=(0,gu.useState)(0),r=(0,gu.useRef)(null),o=(0,gu.useRef)(null),i=(0,gu.useCallback)((c,u)=>`message-${c.id||c.timestamp?.epoch||u}`,[]),s=(0,gu.useCallback)(()=>{if(!r.current)return 0;let c=r.current,u=c.clientHeight,d=t.map((m,h)=>({msg:m,idx:h})).filter(({msg:m})=>m.isVisible&&m.sender===uo).pop()?.idx,f=0;if(d!==void 0){let m=i(t[d],d),h=c.querySelector(`[data-message-key="${m}"]`);if(h)f=h.getBoundingClientRect().height;else{let g=t[d].message.length,y=Math.ceil(g/80);f=Math.max(60,y*24)}}return Math.max(100,u-f)},[t,i]),a=(0,gu.useCallback)(c=>{if(c!==r.current&&(o.current&&(o.current.disconnect(),o.current=null),r.current=c,c)){let u=s();n(u);let d=new ResizeObserver(()=>{if(r.current){let f=s();n(f)}});d.observe(c),o.current=d}},[s]);(0,gu.useEffect)(()=>{if(r.current&&t.length>0){let c=s();n(c)}},[t,s]),(0,gu.useEffect)(()=>()=>{o.current&&o.current.disconnect()},[]);let l=(0,gu.useCallback)((c="smooth")=>{r.current&&r.current.scrollTo({top:r.current.scrollHeight,behavior:c})},[]);return(0,gu.useEffect)(()=>{l("instant")},[l]),(0,gu.useEffect)(()=>{if(t.length>0){let c=t[t.length-1];c&&c.sender===uo&&l()}},[t.length,t,l]),{containerMinHeight:e,scrollContainerCallbackRef:a,getMessageKey:i}};Se();var Fl=N(U()),Wpt=(0,Fl.memo)(({chatHistory:t,currentAiMessage:e,streamingMessageId:n,loading:r,loadingMessage:o,app:i,onRegenerate:s,onEdit:a,onDelete:l,onReplaceChat:c,showHelperComponents:u=!0})=>{let[d,f]=(0,Fl.useState)(""),p=Ht(),{containerMinHeight:m,scrollContainerCallbackRef:h,getMessageKey:g}=Vpt({chatHistory:t});if((0,Fl.useEffect)(()=>{let w;return r?w=window.setInterval(()=>{f(v=>v.length<6?v+".":"")},200):f(""),()=>window.clearInterval(w)},[r]),!t.filter(w=>w.isVisible).length&&!e)return Fl.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-gap-2 tw-overflow-y-auto"},u&&p.showRelevantNotes&&Fl.default.createElement(mX,{defaultOpen:!0,key:"relevant-notes-before-chat"}),u&&p.showSuggestedPrompts&&Fl.default.createElement(jpt,{onClick:c}));let y=()=>o?`${o} ${d}`:d;return Fl.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-1 tw-flex-col tw-overflow-hidden"},u&&p.showRelevantNotes&&Fl.default.createElement(mX,{className:"tw-mb-4",defaultOpen:!1,key:"relevant-notes-in-chat"}),Fl.default.createElement("div",{ref:h,"data-testid":"chat-messages",className:"tw-relative tw-flex tw-w-full tw-flex-1 tw-select-text tw-flex-col tw-items-start tw-justify-start tw-overflow-y-auto tw-scroll-smooth tw-break-words tw-text-[calc(var(--font-text-size)_-_2px)]"},t.map((w,v)=>{let x=t.filter(T=>T.isVisible),_=v===x.length-1&&w.sender!==uo;return w.isVisible&&Fl.default.createElement("div",{key:g(w,v),"data-message-key":g(w,v),className:"tw-w-full",style:{minHeight:_?`${m}px`:"auto"}},Fl.default.createElement(UIe,{message:w,app:i,isStreaming:!1,onRegenerate:()=>s(v),onEdit:T=>a(v,T),onDelete:()=>l(v)}))}),(e||r)&&Fl.default.createElement("div",{className:"tw-w-full",style:{minHeight:`${m}px`}},Fl.default.createElement(UIe,{key:n??"ai_message_streaming",message:{id:n??void 0,sender:"AI",message:e||y(),isVisible:!0,timestamp:null},app:i,isStreaming:!0,onDelete:()=>{}}))))});Wpt.displayName="ChatMessages";var Hpt=Wpt;rn();ye();qe();var hX=N(U());function gX(t){let[e,n]=(0,hX.useState)(null);(0,hX.useEffect)(()=>{(async()=>{let i=await UAe();i.version&&n(i.version)})().catch(i=>z("checkVersion failed",i))},[]);let r=e!==null&&zW(e,t);return{latestVersion:e,hasUpdate:r}}Kt();Se();qe();vt();var rm=N(U());function Kpt({currentVersion:t}){let{latestVersion:e,hasUpdate:n}=gX(t),r=Ht().lastDismissedVersion,[o,i]=(0,rm.useState)(!0),s=n&&e&&zW(e,t)&&r!==e,a=()=>{e&&(i(!1),window.setTimeout(()=>{pe("lastDismissedVersion",e)},300))};return s?rm.default.createElement("div",{className:oe("tw-min-h-14 tw-overflow-hidden",o?"tw-duration-300 tw-animate-in tw-slide-in-from-top":"tw-duration-300 tw-animate-out tw-slide-out-to-top")},rm.default.createElement("div",{className:"tw-mb-1 tw-flex tw-items-center tw-justify-between tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-2 tw-pl-3 tw-text-xs"},rm.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},rm.default.createElement("span",{className:"tw-font-medium"},"Update available:"),rm.default.createElement("a",{href:"https://github.com/logancyang/obsidian-copilot/releases/latest",target:"_blank",rel:"noopener noreferrer",className:"tw-text-normal"},"v",e)),rm.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},rm.default.createElement(X,{size:"fit",variant:"ghost2",className:"tw-text-accent hover:tw-text-accent-hover",onClick:()=>{window.open("obsidian://show-plugin?id=copilot","_blank"),a()}},"Update"),rm.default.createElement(X,{variant:"ghost2",size:"icon",onClick:a},rm.default.createElement(Sn,{className:"tw-size-4"}))))):null}Ir();bi();Ir();var qpt=require("obsidian");fc();var S1=class extends qpt.FuzzySuggestModal{constructor(n,r){super(n);this.onChooseFolder=r}getItems(){let n=new Set,r=Wge(this.app);return this.app.vault.getAllLoadedFiles().forEach(o=>{o.parent?.path&&o.parent.path!=="/"&&!r.some(s=>o.parent.path===s||o.parent.path.startsWith(s+"/"))&&n.add(o.parent.path)}),Array.from(n)}getItemText(n){return n}onChooseItem(n,r){this.onChooseFolder(n)}};var wd=require("obsidian"),oV=class extends wd.Modal{constructor(n,r,o){super(n);this.title=r;this.content=o;this.component=new wd.Component}onOpen(){let{contentEl:n,modalEl:r}=this;r.addClass("!tw-w-[90vw]","!tw-max-w-[800px]"),n.empty(),n.addClass("tw-flex","tw-flex-col","tw-p-0"),this.component.load();let o=n.createDiv({cls:"tw-flex tw-items-center tw-justify-between tw-px-5 tw-py-3 tw-border-b tw-border-border"}),i=o.createDiv({cls:"tw-flex tw-items-center tw-gap-2 tw-min-w-0"}),s=i.createDiv({cls:"tw-text-muted tw-shrink-0"});(0,wd.setIcon)(s,"file-text"),i.createEl("span",{text:this.title,cls:"tw-font-semibold tw-text-normal tw-truncate"});let a=o.createEl("button",{cls:"tw-flex tw-items-center tw-gap-1 tw-px-2 tw-py-1 tw-rounded-md tw-bg-secondary tw-border-none tw-cursor-pointer tw-text-muted hover:tw-text-normal tw-shrink-0",attr:{"aria-label":"Copy content",title:"Copy content"}}),l=a.createSpan({cls:"tw-flex tw-items-center"});(0,wd.setIcon)(l,"copy"),a.addEventListener("click",()=>{navigator.clipboard.writeText(this.content).then(()=>{(0,wd.setIcon)(l,"check"),a.addClass("tw-text-accent"),new wd.Notice("Copied to clipboard"),window.setTimeout(()=>{(0,wd.setIcon)(l,"copy"),a.removeClass("tw-text-accent")},2e3)},()=>new wd.Notice("Failed to copy"))});let u=n.createDiv({cls:"tw-overflow-auto tw-p-5",attr:{style:"max-height: 50vh"}}).createDiv({cls:"markdown-rendered tw-p-4 tw-bg-primary-alt tw-rounded-lg tw-border tw-border-border"});wd.MarkdownRenderer.renderMarkdown(this.content,u,"",this.component)}onClose(){this.component.unload(),this.contentEl.empty()}};ye();var bx=require("obsidian");async function Gpt(t,e,n,r){let o=dye(e,n);if(!o){new bx.Notice("No cached content available for this file.");return}if(!await t.vault.adapter.exists(o.cachePath)){new bx.Notice("Cache expired. Please re-process the file.");return}try{let s=await t.vault.adapter.read(o.cachePath);new oV(t,r,s).open()}catch(s){z(`Failed to read cached content for ${n}:`,s),new bx.Notice("Failed to read cached content.")}}async function yX(t,e,n){if(!e){new bx.Notice("No cached content available.");return}let r=null;switch(n.cacheKind){case"web":r=e.webContexts?.[n.id]??null;break;case"youtube":r=e.youtubeContexts?.[n.id]??null;break;case"file":{let o=dye(e,n.id);if(!o){new bx.Notice("No cached content available for this file.");return}if(!await t.vault.adapter.exists(o.cachePath)){new bx.Notice("Cache expired. Please re-process the file.");return}try{r=await t.vault.adapter.read(o.cachePath)}catch(s){z(`Failed to read cached file: ${o.cachePath}`,s),new bx.Notice("Failed to read cached content.");return}break}}if(!r||!r.trim()){new bx.Notice("No content available for this item.");return}new oV(t,n.name,r).open()}var WIe=require("obsidian");var wX=require("obsidian");qe();Qi();var T1=class extends wX.FuzzySuggestModal{constructor(e,n="copilot_plus"){super(e),this.activeNote=e.workspace.getActiveFile(),this.chainType=n}getOrderedNotes(e=[]){let n=this.app.workspace.getLastOpenFiles().map(s=>this.app.vault.getAbstractFileByPath(s)).filter(s=>s instanceof wX.TFile&&PA(s,this.chainType)&&!e.includes(s.path)&&s.path!==this.activeNote?.path),o=this.app.vault.getFiles().filter(s=>PA(s,this.chainType)).filter(s=>!n.some(a=>a.path===s.path)&&!e.includes(s.path)&&s.path!==this.activeNote?.path);return[...this.activeNote&&PA(this.activeNote,this.chainType)?[this.activeNote]:[],...n,...o]}formatNoteTitle(e,n,r){let o=e;return n&&(o+=" (current)"),r==="pdf"?o+=" (PDF)":r==="canvas"&&(o+=" (Canvas)"),o}};var iV=class extends T1{constructor({app:e,onFileSelect:n,excludeFilePaths:r,titleOnly:o=!1}){super(e),this.onFileSelect=n,this.availableNotes=this.getOrderedProjectFiles(r),this.titleOnly=o,this.setTitle("Select File")}getOrderedProjectFiles(e=[]){let n=["mp3","mp4","m4a","wav","webm"],r=this.app.workspace.getLastOpenFiles().map(s=>this.app.vault.getAbstractFileByPath(s)).filter(s=>s instanceof WIe.TFile&&!e.includes(s.path)&&s.path!==this.activeNote?.path&&!n.includes(s.extension.toLowerCase())),i=this.app.vault.getFiles().filter(s=>!n.includes(s.extension.toLowerCase())).filter(s=>!r.some(a=>a.path===s.path)&&!e.includes(s.path)&&s.path!==this.activeNote?.path);return[...this.activeNote?[this.activeNote]:[],...r,...i]}getItems(){if(this.titleOnly){let e=new Map;return this.availableNotes.forEach(n=>{e.set(n.basename,n)}),Array.from(e.values())}return this.availableNotes}getItemText(e){let n=e.path===this.activeNote?.path;return this.formatNoteTitle(e.basename,n,e.extension)}onChooseItem(e,n){this.onFileSelect(e)}renderSuggestion(e,n){let r=n.createDiv({cls:"pointer-events-none"});if(e.item instanceof WIe.TFile){let o=r.createDiv(),i=e.item;o.setText(this.formatNoteTitle(i.basename,i===this.activeNote,i.extension)),this.titleOnly||r.createDiv({cls:"mt-1 text-muted text-xs"}).setText(i.path)}}formatNoteTitle(e,n,r){let o=e;return n&&(o+=" (current)"),r&&(o+=` (${r.toUpperCase()})`),o}};qe();var Ypt=require("obsidian"),I1=class extends Ypt.FuzzySuggestModal{constructor(n,r){super(n);this.onChooseTag=r}getItems(){let n=this.app.vault.getMarkdownFiles(),r=new Set;for(let o of n)eg(o).forEach(s=>r.add(s));return Array.from(r)}getItemText(n){return n}onChooseItem(n,r){this.onChooseTag(n)}};rn();var uV=N(U());vt();var omt=N(U(),1),Rt=N(U(),1),_X=(0,Rt.createContext)(null);_X.displayName="PanelGroupContext";var Yi={group:"data-panel-group",groupDirection:"data-panel-group-direction",groupId:"data-panel-group-id",panel:"data-panel",panelCollapsible:"data-panel-collapsible",panelId:"data-panel-id",panelSize:"data-panel-size",resizeHandle:"data-resize-handle",resizeHandleActive:"data-resize-handle-active",resizeHandleEnabled:"data-panel-resize-handle-enabled",resizeHandleId:"data-panel-resize-handle-id",resizeHandleState:"data-resize-handle-state"},JIe=10,SE=Rt.useLayoutEffect,Zpt=omt.useId,JQt=typeof Zpt=="function"?Zpt:()=>null,XQt=0;function XIe(t=null){let e=JQt(),n=(0,Rt.useRef)(t||e||null);return n.current===null&&(n.current=""+XQt++),t??n.current}function imt({children:t,className:e="",collapsedSize:n,collapsible:r,defaultSize:o,forwardedRef:i,id:s,maxSize:a,minSize:l,onCollapse:c,onExpand:u,onResize:d,order:f,style:p,tagName:m="div",...h}){let g=(0,Rt.useContext)(_X);if(g===null)throw Error("Panel components must be rendered within a PanelGroup container");let{collapsePanel:y,expandPanel:w,getPanelSize:v,getPanelStyle:x,groupId:b,isPanelCollapsed:_,reevaluatePanelConstraints:T,registerPanel:S,resizePanel:P,unregisterPanel:A}=g,O=XIe(s),D=(0,Rt.useRef)({callbacks:{onCollapse:c,onExpand:u,onResize:d},constraints:{collapsedSize:n,collapsible:r,defaultSize:o,maxSize:a,minSize:l},id:O,idIsFromProps:s!==void 0,order:f});(0,Rt.useRef)({didLogMissingDefaultSizeWarning:!1}),SE(()=>{let{callbacks:B,constraints:W}=D.current,F={...W};D.current.id=O,D.current.idIsFromProps=s!==void 0,D.current.order=f,B.onCollapse=c,B.onExpand=u,B.onResize=d,W.collapsedSize=n,W.collapsible=r,W.defaultSize=o,W.maxSize=a,W.minSize=l,(F.collapsedSize!==W.collapsedSize||F.collapsible!==W.collapsible||F.maxSize!==W.maxSize||F.minSize!==W.minSize)&&T(D.current,F)}),SE(()=>{let B=D.current;return S(B),()=>{A(B)}},[f,O,S,A]),(0,Rt.useImperativeHandle)(i,()=>({collapse:()=>{y(D.current)},expand:B=>{w(D.current,B)},getId(){return O},getSize(){return v(D.current)},isCollapsed(){return _(D.current)},isExpanded(){return!_(D.current)},resize:B=>{P(D.current,B)}}),[y,w,v,_,O,P]);let $=x(D.current,o);return(0,Rt.createElement)(m,{...h,children:t,className:e,id:O,style:{...$,...p},[Yi.groupId]:b,[Yi.panel]:"",[Yi.panelCollapsible]:r||void 0,[Yi.panelId]:O,[Yi.panelSize]:parseFloat(""+$.flexGrow).toFixed(1)})}var QIe=(0,Rt.forwardRef)((t,e)=>(0,Rt.createElement)(imt,{...t,forwardedRef:e}));imt.displayName="Panel";QIe.displayName="forwardRef(Panel)";var QQt;function een(){return QQt}var ZIe=null,ten=!0,xX=-1,Cx=null;function nen(t,e){if(e){let n=(e&umt)!==0,r=(e&dmt)!==0,o=(e&fmt)!==0,i=(e&pmt)!==0;if(n)return o?"se-resize":i?"ne-resize":"e-resize";if(r)return o?"sw-resize":i?"nw-resize":"w-resize";if(o)return"s-resize";if(i)return"n-resize"}switch(t){case"horizontal":return"ew-resize";case"intersection":return"move";case"vertical":return"ns-resize"}}function ren(){Cx!==null&&(document.head.removeChild(Cx),ZIe=null,Cx=null,xX=-1)}function HIe(t,e){var n,r;if(!ten)return;let o=nen(t,e);if(ZIe!==o){if(ZIe=o,Cx===null){Cx=document.createElement("style");let s=een();s&&Cx.setAttribute("nonce",s),document.head.appendChild(Cx)}if(xX>=0){var i;(i=Cx.sheet)===null||i===void 0||i.removeRule(xX)}xX=(n=(r=Cx.sheet)===null||r===void 0?void 0:r.insertRule(`*{cursor: ${o} !important;}`))!==null&&n!==void 0?n:-1}}function smt(t){return t.type==="keydown"}function amt(t){return t.type.startsWith("pointer")}function lmt(t){return t.type.startsWith("mouse")}function SX(t){if(amt(t)){if(t.isPrimary)return{x:t.clientX,y:t.clientY}}else if(lmt(t))return{x:t.clientX,y:t.clientY};return{x:1/0,y:1/0}}function oen(){if(typeof matchMedia=="function")return matchMedia("(pointer:coarse)").matches?"coarse":"fine"}function ien(t,e,n){return n?t.x<e.x+e.width&&t.x+t.width>e.x&&t.y<e.y+e.height&&t.y+t.height>e.y:t.x<=e.x+e.width&&t.x+t.width>=e.x&&t.y<=e.y+e.height&&t.y+t.height>=e.y}function sen(t,e){if(t===e)throw new Error("Cannot compare node with itself");let n={a:Qpt(t),b:Qpt(e)},r;for(;n.a.at(-1)===n.b.at(-1);)t=n.a.pop(),e=n.b.pop(),r=t;cr(r,"Stacking order can only be calculated for elements with a common ancestor");let o={a:Xpt(Jpt(n.a)),b:Xpt(Jpt(n.b))};if(o.a===o.b){let i=r.childNodes,s={a:n.a.at(-1),b:n.b.at(-1)},a=i.length;for(;a--;){let l=i[a];if(l===s.a)return 1;if(l===s.b)return-1}}return Math.sign(o.a-o.b)}var aen=/\b(?:position|zIndex|opacity|transform|webkitTransform|mixBlendMode|filter|webkitFilter|isolation)\b/;function len(t){var e;let n=getComputedStyle((e=cmt(t))!==null&&e!==void 0?e:t).display;return n==="flex"||n==="inline-flex"}function cen(t){let e=getComputedStyle(t);return!!(e.position==="fixed"||e.zIndex!=="auto"&&(e.position!=="static"||len(t))||+e.opacity<1||"transform"in e&&e.transform!=="none"||"webkitTransform"in e&&e.webkitTransform!=="none"||"mixBlendMode"in e&&e.mixBlendMode!=="normal"||"filter"in e&&e.filter!=="none"||"webkitFilter"in e&&e.webkitFilter!=="none"||"isolation"in e&&e.isolation==="isolate"||aen.test(e.willChange)||e.webkitOverflowScrolling==="touch")}function Jpt(t){let e=t.length;for(;e--;){let n=t[e];if(cr(n,"Missing node"),cen(n))return n}return null}function Xpt(t){return t&&Number(getComputedStyle(t).zIndex)||0}function Qpt(t){let e=[];for(;t;)e.push(t),t=cmt(t);return e}function cmt(t){let{parentNode:e}=t;return e&&e instanceof ShadowRoot?e.host:e}var umt=1,dmt=2,fmt=4,pmt=8,uen=oen()==="coarse",$h=[],k1=!1,vS=new Map,TX=new Map,lV=new Set;function den(t,e,n,r,o){var i;let{ownerDocument:s}=e,a={direction:n,element:e,hitAreaMargins:r,setResizeHandlerState:o},l=(i=vS.get(s))!==null&&i!==void 0?i:0;return vS.set(s,l+1),lV.add(a),bX(),function(){var u;TX.delete(t),lV.delete(a);let d=(u=vS.get(s))!==null&&u!==void 0?u:1;if(vS.set(s,d-1),bX(),d===1&&vS.delete(s),$h.includes(a)){let f=$h.indexOf(a);f>=0&&$h.splice(f,1),t0e(),o("up",!0,null)}}}function fen(t){let{target:e}=t,{x:n,y:r}=SX(t);k1=!0,e0e({target:e,x:n,y:r}),bX(),$h.length>0&&(CX("down",t),t.preventDefault(),mmt(e)||t.stopImmediatePropagation())}function KIe(t){let{x:e,y:n}=SX(t);if(k1&&t.buttons===0&&(k1=!1,CX("up",t)),!k1){let{target:r}=t;e0e({target:r,x:e,y:n})}CX("move",t),t0e(),$h.length>0&&t.preventDefault()}function qIe(t){let{target:e}=t,{x:n,y:r}=SX(t);TX.clear(),k1=!1,$h.length>0&&(t.preventDefault(),mmt(e)||t.stopImmediatePropagation()),CX("up",t),e0e({target:e,x:n,y:r}),t0e(),bX()}function mmt(t){let e=t;for(;e;){if(e.hasAttribute(Yi.resizeHandle))return!0;e=e.parentElement}return!1}function e0e({target:t,x:e,y:n}){$h.splice(0);let r=null;(t instanceof HTMLElement||t instanceof SVGElement)&&(r=t),lV.forEach(o=>{let{element:i,hitAreaMargins:s}=o,a=i.getBoundingClientRect(),{bottom:l,left:c,right:u,top:d}=a,f=uen?s.coarse:s.fine;if(e>=c-f&&e<=u+f&&n>=d-f&&n<=l+f){if(r!==null&&document.contains(r)&&i!==r&&!i.contains(r)&&!r.contains(i)&&sen(r,i)>0){let m=r,h=!1;for(;m&&!m.contains(i);){if(ien(m.getBoundingClientRect(),a,!0)){h=!0;break}m=m.parentElement}if(h)return}$h.push(o)}})}function GIe(t,e){TX.set(t,e)}function t0e(){let t=!1,e=!1;$h.forEach(r=>{let{direction:o}=r;o==="horizontal"?t=!0:e=!0});let n=0;TX.forEach(r=>{n|=r}),t&&e?HIe("intersection",n):t?HIe("horizontal",n):e?HIe("vertical",n):ren()}var YIe=new AbortController;function bX(){YIe.abort(),YIe=new AbortController;let t={capture:!0,signal:YIe.signal};lV.size&&(k1?($h.length>0&&vS.forEach((e,n)=>{let{body:r}=n;e>0&&(r.addEventListener("contextmenu",qIe,t),r.addEventListener("pointerleave",KIe,t),r.addEventListener("pointermove",KIe,t))}),vS.forEach((e,n)=>{let{body:r}=n;r.addEventListener("pointerup",qIe,t),r.addEventListener("pointercancel",qIe,t)})):vS.forEach((e,n)=>{let{body:r}=n;e>0&&(r.addEventListener("pointerdown",fen,t),r.addEventListener("pointermove",KIe,t))}))}function CX(t,e){lV.forEach(n=>{let{setResizeHandlerState:r}=n,o=$h.includes(n);r(t,o,e)})}function pen(){let[t,e]=(0,Rt.useState)(0);return(0,Rt.useCallback)(()=>e(n=>n+1),[])}function cr(t,e){if(!t)throw console.error(e),Error(e)}function TE(t,e,n=JIe){return t.toFixed(n)===e.toFixed(n)?0:t>e?1:-1}function _x(t,e,n=JIe){return TE(t,e,n)===0}function Sf(t,e,n){return TE(t,e,n)===0}function men(t,e,n){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){let o=t[r],i=e[r];if(!Sf(o,i,n))return!1}return!0}function A1({panelConstraints:t,panelIndex:e,size:n}){let r=t[e];cr(r!=null,`Panel constraints not found for index ${e}`);let{collapsedSize:o=0,collapsible:i,maxSize:s=100,minSize:a=0}=r;if(TE(n,a)<0)if(i){let l=(o+a)/2;TE(n,l)<0?n=o:n=a}else n=a;return n=Math.min(s,n),n=parseFloat(n.toFixed(JIe)),n}function sV({delta:t,initialLayout:e,panelConstraints:n,pivotIndices:r,prevLayout:o,trigger:i}){if(Sf(t,0))return e;let s=[...e],[a,l]=r;cr(a!=null,"Invalid first pivot index"),cr(l!=null,"Invalid second pivot index");let c=0;if(i==="keyboard"){{let d=t<0?l:a,f=n[d];cr(f,`Panel constraints not found for index ${d}`);let{collapsedSize:p=0,collapsible:m,minSize:h=0}=f;if(m){let g=e[d];if(cr(g!=null,`Previous layout not found for panel index ${d}`),Sf(g,p)){let y=h-g;TE(y,Math.abs(t))>0&&(t=t<0?0-y:y)}}}{let d=t<0?a:l,f=n[d];cr(f,`No panel constraints found for index ${d}`);let{collapsedSize:p=0,collapsible:m,minSize:h=0}=f;if(m){let g=e[d];if(cr(g!=null,`Previous layout not found for panel index ${d}`),Sf(g,h)){let y=g-p;TE(y,Math.abs(t))>0&&(t=t<0?0-y:y)}}}}{let d=t<0?1:-1,f=t<0?l:a,p=0;for(;;){let h=e[f];cr(h!=null,`Previous layout not found for panel index ${f}`);let y=A1({panelConstraints:n,panelIndex:f,size:100})-h;if(p+=y,f+=d,f<0||f>=n.length)break}let m=Math.min(Math.abs(t),Math.abs(p));t=t<0?0-m:m}{let f=t<0?a:l;for(;f>=0&&f<n.length;){let p=Math.abs(t)-Math.abs(c),m=e[f];cr(m!=null,`Previous layout not found for panel index ${f}`);let h=m-p,g=A1({panelConstraints:n,panelIndex:f,size:h});if(!Sf(m,g)&&(c+=m-g,s[f]=g,c.toPrecision(3).localeCompare(Math.abs(t).toPrecision(3),void 0,{numeric:!0})>=0))break;t<0?f--:f++}}if(men(o,s))return o;{let d=t<0?l:a,f=e[d];cr(f!=null,`Previous layout not found for panel index ${d}`);let p=f+c,m=A1({panelConstraints:n,panelIndex:d,size:p});if(s[d]=m,!Sf(m,p)){let h=p-m,y=t<0?l:a;for(;y>=0&&y<n.length;){let w=s[y];cr(w!=null,`Previous layout not found for panel index ${y}`);let v=w+h,x=A1({panelConstraints:n,panelIndex:y,size:v});if(Sf(w,x)||(h-=x-w,s[y]=x),Sf(h,0))break;t>0?y--:y++}}}let u=s.reduce((d,f)=>f+d,0);return Sf(u,100)?s:o}function hen({layout:t,panelsArray:e,pivotIndices:n}){let r=0,o=100,i=0,s=0,a=n[0];cr(a!=null,"No pivot index found"),e.forEach((d,f)=>{let{constraints:p}=d,{maxSize:m=100,minSize:h=0}=p;f===a?(r=h,o=m):(i+=h,s+=m)});let l=Math.min(o,100-i),c=Math.max(r,100-s),u=t[a];return{valueMax:l,valueMin:c,valueNow:u}}function cV(t,e=document){return Array.from(e.querySelectorAll(`[${Yi.resizeHandleId}][data-panel-group-id="${t}"]`))}function hmt(t,e,n=document){let o=cV(t,n).findIndex(i=>i.getAttribute(Yi.resizeHandleId)===e);return o??null}function gmt(t,e,n){let r=hmt(t,e,n);return r!=null?[r,r+1]:[-1,-1]}function gen(t){return t instanceof HTMLElement?!0:typeof t=="object"&&t!==null&&"tagName"in t&&"getAttribute"in t}function ymt(t,e=document){if(gen(e)&&e.dataset.panelGroupId==t)return e;let n=e.querySelector(`[data-panel-group][data-panel-group-id="${t}"]`);return n||null}function IX(t,e=document){let n=e.querySelector(`[${Yi.resizeHandleId}="${t}"]`);return n||null}function yen(t,e,n,r=document){var o,i,s,a;let l=IX(e,r),c=cV(t,r),u=l?c.indexOf(l):-1,d=(o=(i=n[u])===null||i===void 0?void 0:i.id)!==null&&o!==void 0?o:null,f=(s=(a=n[u+1])===null||a===void 0?void 0:a.id)!==null&&s!==void 0?s:null;return[d,f]}function wen({committedValuesRef:t,eagerValuesRef:e,groupId:n,layout:r,panelDataArray:o,panelGroupElement:i,setLayout:s}){(0,Rt.useRef)({didWarnAboutMissingResizeHandle:!1}),SE(()=>{if(!i)return;let a=cV(n,i);for(let l=0;l<o.length-1;l++){let{valueMax:c,valueMin:u,valueNow:d}=hen({layout:r,panelsArray:o,pivotIndices:[l,l+1]}),f=a[l];if(f!=null){let p=o[l];cr(p,`No panel data found for index "${l}"`),f.setAttribute("aria-controls",p.id),f.setAttribute("aria-valuemax",""+Math.round(c)),f.setAttribute("aria-valuemin",""+Math.round(u)),f.setAttribute("aria-valuenow",d!=null?""+Math.round(d):"")}}return()=>{a.forEach((l,c)=>{l.removeAttribute("aria-controls"),l.removeAttribute("aria-valuemax"),l.removeAttribute("aria-valuemin"),l.removeAttribute("aria-valuenow")})}},[n,r,o,i]),(0,Rt.useEffect)(()=>{if(!i)return;let a=e.current;cr(a,"Eager values not found");let{panelDataArray:l}=a,c=ymt(n,i);cr(c!=null,`No group found for id "${n}"`);let u=cV(n,i);cr(u,`No resize handles found for group id "${n}"`);let d=u.map(f=>{let p=f.getAttribute(Yi.resizeHandleId);cr(p,"Resize handle element has no handle id attribute");let[m,h]=yen(n,p,l,i);if(m==null||h==null)return()=>{};let g=y=>{if(!y.defaultPrevented)switch(y.key){case"Enter":{y.preventDefault();let w=l.findIndex(v=>v.id===m);if(w>=0){let v=l[w];cr(v,`No panel data found for index ${w}`);let x=r[w],{collapsedSize:b=0,collapsible:_,minSize:T=0}=v.constraints;if(x!=null&&_){let S=sV({delta:Sf(x,b)?T-b:b-x,initialLayout:r,panelConstraints:l.map(P=>P.constraints),pivotIndices:gmt(n,p,i),prevLayout:r,trigger:"keyboard"});r!==S&&s(S)}}break}}};return f.addEventListener("keydown",g),()=>{f.removeEventListener("keydown",g)}});return()=>{d.forEach(f=>f())}},[i,t,e,n,r,o,s])}function emt(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}function wmt(t,e){let n=t==="horizontal",{x:r,y:o}=SX(e);return n?r:o}function ven(t,e,n,r,o){let i=n==="horizontal",s=IX(e,o);cr(s,`No resize handle element found for id "${e}"`);let a=s.getAttribute(Yi.groupId);cr(a,"Resize handle element has no group id attribute");let{initialCursorPosition:l}=r,c=wmt(n,t),u=ymt(a,o);cr(u,`No group element found for id "${a}"`);let d=u.getBoundingClientRect(),f=i?d.width:d.height;return(c-l)/f*100}function xen(t,e,n,r,o,i){if(smt(t)){let s=n==="horizontal",a=0;t.shiftKey?a=100:o!=null?a=o:a=10;let l=0;switch(t.key){case"ArrowDown":l=s?0:a;break;case"ArrowLeft":l=s?-a:0;break;case"ArrowRight":l=s?a:0;break;case"ArrowUp":l=s?0:-a;break;case"End":l=100;break;case"Home":l=-100;break}return l}else return r==null?0:ven(t,e,n,r,i)}function ben({panelDataArray:t}){let e=Array(t.length),n=t.map(i=>i.constraints),r=0,o=100;for(let i=0;i<t.length;i++){let s=n[i];cr(s,`Panel constraints not found for index ${i}`);let{defaultSize:a}=s;a!=null&&(r++,e[i]=a,o-=a)}for(let i=0;i<t.length;i++){let s=n[i];cr(s,`Panel constraints not found for index ${i}`);let{defaultSize:a}=s;if(a!=null)continue;let l=t.length-r,c=o/l;r++,e[i]=c,o-=c}return e}function P1(t,e,n){e.forEach((r,o)=>{let i=t[o];cr(i,`Panel data not found for index ${o}`);let{callbacks:s,constraints:a,id:l}=i,{collapsedSize:c=0,collapsible:u}=a,d=n[l];if(d==null||r!==d){n[l]=r;let{onCollapse:f,onExpand:p,onResize:m}=s;m&&m(r,d),u&&(f||p)&&(p&&(d==null||_x(d,c))&&!_x(r,c)&&p(),f&&(d==null||!_x(d,c))&&_x(r,c)&&f())}})}function vX(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}function Cen({defaultSize:t,dragState:e,layout:n,panelData:r,panelIndex:o,precision:i=3}){let s=n[o],a;return s==null?a=t!=null?t.toPrecision(i):"1":r.length===1?a="1":a=s.toPrecision(i),{flexBasis:0,flexGrow:a,flexShrink:1,overflow:"hidden",pointerEvents:e!==null?"none":void 0}}function _en(t,e=10){let n=null;return(...o)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{t(...o)},e)}}function tmt(t){try{if(typeof localStorage<"u")t.getItem=e=>localStorage.getItem(e),t.setItem=(e,n)=>{localStorage.setItem(e,n)};else throw new Error("localStorage not supported in this environment")}catch(e){console.error(e),t.getItem=()=>null,t.setItem=()=>{}}}function vmt(t){return`react-resizable-panels:${t}`}function xmt(t){return t.map(e=>{let{constraints:n,id:r,idIsFromProps:o,order:i}=e;return o?r:i?`${i}:${JSON.stringify(n)}`:JSON.stringify(n)}).sort((e,n)=>e.localeCompare(n)).join(",")}function bmt(t,e){try{let n=vmt(t),r=e.getItem(n);if(r){let o=JSON.parse(r);if(typeof o=="object"&&o!=null)return o}}catch{}return null}function Sen(t,e,n){var r,o;let i=(r=bmt(t,n))!==null&&r!==void 0?r:{},s=xmt(e);return(o=i[s])!==null&&o!==void 0?o:null}function Ten(t,e,n,r,o){var i;let s=vmt(t),a=xmt(e),l=(i=bmt(t,o))!==null&&i!==void 0?i:{};l[a]={expandToSizes:Object.fromEntries(n.entries()),layout:r};try{o.setItem(s,JSON.stringify(l))}catch(c){console.error(c)}}function nmt({layout:t,panelConstraints:e}){let n=[...t],r=n.reduce((i,s)=>i+s,0);if(n.length!==e.length)throw Error(`Invalid ${e.length} panel layout: ${n.map(i=>`${i}%`).join(", ")}`);if(!Sf(r,100)&&n.length>0)for(let i=0;i<e.length;i++){let s=n[i];cr(s!=null,`No layout data found for index ${i}`);let a=100/r*s;n[i]=a}let o=0;for(let i=0;i<e.length;i++){let s=n[i];cr(s!=null,`No layout data found for index ${i}`);let a=A1({panelConstraints:e,panelIndex:i,size:s});s!=a&&(o+=s-a,n[i]=a)}if(!Sf(o,0))for(let i=0;i<e.length;i++){let s=n[i];cr(s!=null,`No layout data found for index ${i}`);let a=s+o,l=A1({panelConstraints:e,panelIndex:i,size:a});if(s!==l&&(o-=l-s,n[i]=l,Sf(o,0)))break}return n}var Ien=100,aV={getItem:t=>(tmt(aV),aV.getItem(t)),setItem:(t,e)=>{tmt(aV),aV.setItem(t,e)}},rmt={};function Cmt({autoSaveId:t=null,children:e,className:n="",direction:r,forwardedRef:o,id:i=null,onLayout:s=null,keyboardResizeBy:a=null,storage:l=aV,style:c,tagName:u="div",...d}){let f=XIe(i),p=(0,Rt.useRef)(null),[m,h]=(0,Rt.useState)(null),[g,y]=(0,Rt.useState)([]),w=pen(),v=(0,Rt.useRef)({}),x=(0,Rt.useRef)(new Map),b=(0,Rt.useRef)(0),_=(0,Rt.useRef)({autoSaveId:t,direction:r,dragState:m,id:f,keyboardResizeBy:a,onLayout:s,storage:l}),T=(0,Rt.useRef)({layout:g,panelDataArray:[],panelDataArrayChanged:!1});(0,Rt.useRef)({didLogIdAndOrderWarning:!1,didLogPanelConstraintsWarning:!1,prevPanelIds:[]}),(0,Rt.useImperativeHandle)(o,()=>({getId:()=>_.current.id,getLayout:()=>{let{layout:j}=T.current;return j},setLayout:j=>{let{onLayout:G}=_.current,{layout:J,panelDataArray:M}=T.current,E=nmt({layout:j,panelConstraints:M.map(R=>R.constraints)});emt(J,E)||(y(E),T.current.layout=E,G&&G(E),P1(M,E,v.current))}}),[]),SE(()=>{_.current.autoSaveId=t,_.current.direction=r,_.current.dragState=m,_.current.id=f,_.current.onLayout=s,_.current.storage=l}),wen({committedValuesRef:_,eagerValuesRef:T,groupId:f,layout:g,panelDataArray:T.current.panelDataArray,setLayout:y,panelGroupElement:p.current}),(0,Rt.useEffect)(()=>{let{panelDataArray:j}=T.current;if(t){if(g.length===0||g.length!==j.length)return;let G=rmt[t];G==null&&(G=_en(Ten,Ien),rmt[t]=G);let J=[...j],M=new Map(x.current);G(t,J,M,g,l)}},[t,g,l]),(0,Rt.useEffect)(()=>{});let S=(0,Rt.useCallback)(j=>{let{onLayout:G}=_.current,{layout:J,panelDataArray:M}=T.current;if(j.constraints.collapsible){let E=M.map(Y=>Y.constraints),{collapsedSize:R=0,panelSize:L,pivotIndices:K}=_E(M,j,J);if(cr(L!=null,`Panel size not found for panel "${j.id}"`),!_x(L,R)){x.current.set(j.id,L);let re=E1(M,j)===M.length-1?L-R:R-L,ae=sV({delta:re,initialLayout:J,panelConstraints:E,pivotIndices:K,prevLayout:J,trigger:"imperative-api"});vX(J,ae)||(y(ae),T.current.layout=ae,G&&G(ae),P1(M,ae,v.current))}}},[]),P=(0,Rt.useCallback)((j,G)=>{let{onLayout:J}=_.current,{layout:M,panelDataArray:E}=T.current;if(j.constraints.collapsible){let R=E.map(ve=>ve.constraints),{collapsedSize:L=0,panelSize:K=0,minSize:Y=0,pivotIndices:re}=_E(E,j,M),ae=G??Y;if(_x(K,L)){let ve=x.current.get(j.id),Te=ve!=null&&ve>=ae?ve:ae,nt=E1(E,j)===E.length-1?K-Te:Te-K,rt=sV({delta:nt,initialLayout:M,panelConstraints:R,pivotIndices:re,prevLayout:M,trigger:"imperative-api"});vX(M,rt)||(y(rt),T.current.layout=rt,J&&J(rt),P1(E,rt,v.current))}}},[]),A=(0,Rt.useCallback)(j=>{let{layout:G,panelDataArray:J}=T.current,{panelSize:M}=_E(J,j,G);return cr(M!=null,`Panel size not found for panel "${j.id}"`),M},[]),O=(0,Rt.useCallback)((j,G)=>{let{panelDataArray:J}=T.current,M=E1(J,j);return Cen({defaultSize:G,dragState:m,layout:g,panelData:J,panelIndex:M})},[m,g]),D=(0,Rt.useCallback)(j=>{let{layout:G,panelDataArray:J}=T.current,{collapsedSize:M=0,collapsible:E,panelSize:R}=_E(J,j,G);return cr(R!=null,`Panel size not found for panel "${j.id}"`),E===!0&&_x(R,M)},[]),$=(0,Rt.useCallback)(j=>{let{layout:G,panelDataArray:J}=T.current,{collapsedSize:M=0,collapsible:E,panelSize:R}=_E(J,j,G);return cr(R!=null,`Panel size not found for panel "${j.id}"`),!E||TE(R,M)>0},[]),B=(0,Rt.useCallback)(j=>{let{panelDataArray:G}=T.current;G.push(j),G.sort((J,M)=>{let E=J.order,R=M.order;return E==null&&R==null?0:E==null?-1:R==null?1:E-R}),T.current.panelDataArrayChanged=!0,w()},[w]);SE(()=>{if(T.current.panelDataArrayChanged){T.current.panelDataArrayChanged=!1;let{autoSaveId:j,onLayout:G,storage:J}=_.current,{layout:M,panelDataArray:E}=T.current,R=null;if(j){let K=Sen(j,E,J);K&&(x.current=new Map(Object.entries(K.expandToSizes)),R=K.layout)}R==null&&(R=ben({panelDataArray:E}));let L=nmt({layout:R,panelConstraints:E.map(K=>K.constraints)});emt(M,L)||(y(L),T.current.layout=L,G&&G(L),P1(E,L,v.current))}}),SE(()=>{let j=T.current;return()=>{j.layout=[]}},[]);let W=(0,Rt.useCallback)(j=>{let G=!1,J=p.current;return J&&window.getComputedStyle(J,null).getPropertyValue("direction")==="rtl"&&(G=!0),function(E){E.preventDefault();let R=p.current;if(!R)return()=>null;let{direction:L,dragState:K,id:Y,keyboardResizeBy:re,onLayout:ae}=_.current,{layout:ve,panelDataArray:Te}=T.current,{initialLayout:Ee}=K??{},nt=gmt(Y,j,R),rt=xen(E,j,L,K,re,R),Jt=L==="horizontal";Jt&&G&&(rt=-rt);let ke=Te.map(Ie=>Ie.constraints),Ln=sV({delta:rt,initialLayout:Ee??ve,panelConstraints:ke,pivotIndices:nt,prevLayout:ve,trigger:smt(E)?"keyboard":"mouse-or-touch"}),He=!vX(ve,Ln);(amt(E)||lmt(E))&&b.current!=rt&&(b.current=rt,!He&&rt!==0?Jt?GIe(j,rt<0?umt:dmt):GIe(j,rt<0?fmt:pmt):GIe(j,0)),He&&(y(Ln),T.current.layout=Ln,ae&&ae(Ln),P1(Te,Ln,v.current))}},[]),F=(0,Rt.useCallback)((j,G)=>{let{onLayout:J}=_.current,{layout:M,panelDataArray:E}=T.current,R=E.map(ve=>ve.constraints),{panelSize:L,pivotIndices:K}=_E(E,j,M);cr(L!=null,`Panel size not found for panel "${j.id}"`);let re=E1(E,j)===E.length-1?L-G:G-L,ae=sV({delta:re,initialLayout:M,panelConstraints:R,pivotIndices:K,prevLayout:M,trigger:"imperative-api"});vX(M,ae)||(y(ae),T.current.layout=ae,J&&J(ae),P1(E,ae,v.current))},[]),Z=(0,Rt.useCallback)((j,G)=>{let{layout:J,panelDataArray:M}=T.current,{collapsedSize:E=0,collapsible:R}=G,{collapsedSize:L=0,collapsible:K,maxSize:Y=100,minSize:re=0}=j.constraints,{panelSize:ae}=_E(M,j,J);ae!=null&&(R&&K&&_x(ae,E)?_x(E,L)||F(j,L):ae<re?F(j,re):ae>Y&&F(j,Y))},[F]),V=(0,Rt.useCallback)((j,G)=>{let{direction:J}=_.current,{layout:M}=T.current;if(!p.current)return;let E=IX(j,p.current);cr(E,`Drag handle element not found for id "${j}"`);let R=wmt(J,G);h({dragHandleId:j,dragHandleRect:E.getBoundingClientRect(),initialCursorPosition:R,initialLayout:M})},[]),H=(0,Rt.useCallback)(()=>{h(null)},[]),te=(0,Rt.useCallback)(j=>{let{panelDataArray:G}=T.current,J=E1(G,j);J>=0&&(G.splice(J,1),delete v.current[j.id],T.current.panelDataArrayChanged=!0,w())},[w]),fe=(0,Rt.useMemo)(()=>({collapsePanel:S,direction:r,dragState:m,expandPanel:P,getPanelSize:A,getPanelStyle:O,groupId:f,isPanelCollapsed:D,isPanelExpanded:$,reevaluatePanelConstraints:Z,registerPanel:B,registerResizeHandle:W,resizePanel:F,startDragging:V,stopDragging:H,unregisterPanel:te,panelGroupElement:p.current}),[S,m,r,P,A,O,f,D,$,Z,B,W,F,V,H,te]),me={display:"flex",flexDirection:r==="horizontal"?"row":"column",height:"100%",overflow:"hidden",width:"100%"};return(0,Rt.createElement)(_X.Provider,{value:fe},(0,Rt.createElement)(u,{...d,children:e,className:n,id:i,ref:p,style:{...me,...c},[Yi.group]:"",[Yi.groupDirection]:r,[Yi.groupId]:f}))}var n0e=(0,Rt.forwardRef)((t,e)=>(0,Rt.createElement)(Cmt,{...t,forwardedRef:e}));Cmt.displayName="PanelGroup";n0e.displayName="forwardRef(PanelGroup)";function E1(t,e){return t.findIndex(n=>n===e||n.id===e.id)}function _E(t,e,n){let r=E1(t,e),i=r===t.length-1?[r-1,r]:[r,r+1],s=n[r];return{...e.constraints,panelSize:s,pivotIndices:i}}function Pen({disabled:t,handleId:e,resizeHandler:n,panelGroupElement:r}){(0,Rt.useEffect)(()=>{if(t||n==null||r==null)return;let o=IX(e,r);if(o==null)return;let i=s=>{if(!s.defaultPrevented)switch(s.key){case"ArrowDown":case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"End":case"Home":{s.preventDefault(),n(s);break}case"F6":{s.preventDefault();let a=o.getAttribute(Yi.groupId);cr(a,`No group element found for id "${a}"`);let l=cV(a,r),c=hmt(a,e,r);cr(c!==null,`No resize element found for id "${e}"`);let u=s.shiftKey?c>0?c-1:l.length-1:c+1<l.length?c+1:0;l[u].focus();break}}};return o.addEventListener("keydown",i),()=>{o.removeEventListener("keydown",i)}},[r,t,e,n])}function r0e({children:t=null,className:e="",disabled:n=!1,hitAreaMargins:r,id:o,onBlur:i,onClick:s,onDragging:a,onFocus:l,onPointerDown:c,onPointerUp:u,style:d={},tabIndex:f=0,tagName:p="div",...m}){var h,g;let y=(0,Rt.useRef)(null),w=(0,Rt.useRef)({onClick:s,onDragging:a,onPointerDown:c,onPointerUp:u});(0,Rt.useEffect)(()=>{w.current.onClick=s,w.current.onDragging=a,w.current.onPointerDown=c,w.current.onPointerUp=u});let v=(0,Rt.useContext)(_X);if(v===null)throw Error("PanelResizeHandle components must be rendered within a PanelGroup container");let{direction:x,groupId:b,registerResizeHandle:_,startDragging:T,stopDragging:S,panelGroupElement:P}=v,A=XIe(o),[O,D]=(0,Rt.useState)("inactive"),[$,B]=(0,Rt.useState)(!1),[W,F]=(0,Rt.useState)(null),Z=(0,Rt.useRef)({state:O});SE(()=>{Z.current.state=O}),(0,Rt.useEffect)(()=>{if(n)F(null);else{let fe=_(A);F(()=>fe)}},[n,A,_]);let V=(h=r?.coarse)!==null&&h!==void 0?h:15,H=(g=r?.fine)!==null&&g!==void 0?g:5;return(0,Rt.useEffect)(()=>{if(n||W==null)return;let fe=y.current;cr(fe,"Element ref not attached");let me=!1;return den(A,fe,x,{coarse:V,fine:H},(G,J,M)=>{if(!J){D("inactive");return}switch(G){case"down":{D("drag"),me=!1,cr(M,'Expected event to be defined for "down" action'),T(A,M);let{onDragging:E,onPointerDown:R}=w.current;E?.(!0),R?.();break}case"move":{let{state:E}=Z.current;me=!0,E!=="drag"&&D("hover"),cr(M,'Expected event to be defined for "move" action'),W(M);break}case"up":{D("hover"),S();let{onClick:E,onDragging:R,onPointerUp:L}=w.current;R?.(!1),L?.(),me||E?.();break}}})},[V,x,n,H,_,A,W,T,S]),Pen({disabled:n,handleId:A,resizeHandler:W,panelGroupElement:P}),(0,Rt.createElement)(p,{...m,children:t,className:e,id:o,onBlur:()=>{B(!1),i?.()},onFocus:()=>{B(!0),l?.()},ref:y,role:"separator",style:{...{touchAction:"none",userSelect:"none"},...d},tabIndex:f,[Yi.groupDirection]:x,[Yi.groupId]:b,[Yi.resizeHandle]:"",[Yi.resizeHandleActive]:O==="drag"?"pointer":$?"keyboard":void 0,[Yi.resizeHandleEnabled]:!n,[Yi.resizeHandleId]:A,[Yi.resizeHandleState]:O})}r0e.displayName="PanelResizeHandle";Kt();var _mt=({className:t,...e})=>uV.createElement(n0e,{className:oe("tw-flex tw-size-full data-[panel-group-direction=vertical]:tw-flex-col",t),...e}),o0e=QIe,Smt=({withHandle:t,className:e,...n})=>uV.createElement(r0e,{className:oe("tw-relative tw-flex tw-w-px tw-items-center tw-justify-center tw-bg-[var(--background-modifier-border)] after:tw-absolute after:tw-inset-y-0 after:tw-left-1/2 after:tw-w-1 after:tw--translate-x-1/2 focus-visible:tw-outline-none focus-visible:tw-ring-1 focus-visible:tw-ring-ring focus-visible:tw-ring-offset-1 data-[panel-group-direction=vertical]:tw-h-px data-[panel-group-direction=vertical]:tw-w-full data-[panel-group-direction=vertical]:after:tw-left-0 data-[panel-group-direction=vertical]:after:tw-h-1 data-[panel-group-direction=vertical]:after:tw-w-full data-[panel-group-direction=vertical]:after:tw--translate-y-1/2 data-[panel-group-direction=vertical]:after:tw-translate-x-0 [&[data-panel-group-direction=vertical]>div]:tw-rotate-90",e),...n},t&&uV.createElement("div",{className:"tw-z-sidedock tw-flex tw-h-4 tw-w-3 tw-items-center tw-justify-center tw-rounded-sm tw-border tw-border-solid tw-border-border"},uV.createElement(bm,{className:"tw-size-2.5"})));Kt();fc();qe();vt();var Fh=require("obsidian"),Ce=N(U());ws();function Aen({extension:t,size:e="tw-size-4"}){let n=t.toLowerCase().replace("*.","");return["jpg","jpeg","png","gif","svg"].includes(n)?Ce.default.createElement(qS,{className:`tw-text-context-manager-blue ${e}`}):["mp3","wav","ogg"].includes(n)?Ce.default.createElement(g$,{className:`tw-text-context-manager-purple ${e}`}):["mp4","mov","avi"].includes(n)?Ce.default.createElement(GS,{className:`tw-text-context-manager-orange ${e}`}):["md","txt","mdx","markdown"].includes(n)?Ce.default.createElement(Ur,{className:`${e}`}):Ce.default.createElement(Ur,{className:`tw-text-faint ${e}`})}var i0e=({IconComponent:t,title:e,iconColorClassName:n,onAddClick:r,tooltip:o})=>Ce.default.createElement("div",{className:"tw-mb-3 tw-flex tw-items-center tw-justify-between"},Ce.default.createElement("div",{className:"tw-flex tw-items-center"},Ce.default.createElement(t,{className:`tw-mr-2 tw-size-4 ${n}`}),Ce.default.createElement("h3",{className:`tw-text-sm tw-font-semibold ${n}`},e),o&&Ce.default.createElement(Nn,{buttonClassName:"tw-ml-2 tw-size-4 tw-text-muted",content:Ce.default.createElement("div",{className:"tw-max-w-80"},o)})),Ce.default.createElement(X,{variant:"ghost",size:"fit",className:"tw-text-muted hover:tw-bg-secondary",title:`Add new ${e.toLowerCase()}`,onClick:r},Ce.default.createElement(Md,{className:`tw-size-4 ${n}`}))),Tmt=({title:t,IconComponent:e,iconColorClassName:n,items:r,activeItem:o,activeSection:i,sectionType:s,renderIcon:a,onItemClick:l,onAddClick:c,onDeleteItem:u,tooltip:d})=>Ce.default.createElement("div",null,Ce.default.createElement(i0e,{IconComponent:e,title:t,iconColorClassName:n,onAddClick:c,tooltip:d}),Ce.default.createElement("div",{className:"tw-space-y-1"},r.map(f=>Ce.default.createElement("div",{key:f.id,className:oe("tw-group tw-flex tw-cursor-pointer tw-items-center tw-justify-between tw-rounded-md tw-p-2 hover:tw-bg-secondary/50",i===s&&o===f.id&&"tw-bg-secondary tw-text-normal"),onClick:()=>l(f.id,f.name)},Ce.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-center"},a?a(f):Ce.default.createElement(e,{className:`tw-mr-2 tw-size-4 ${n}`}),Ce.default.createElement(go,{className:"tw-flex-1 tw-text-sm"},f.name)),Ce.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ce.default.createElement("span",{className:"tw-text-xs tw-text-muted group-hover:tw-hidden"},f.count||0),Ce.default.createElement(Sn,{className:"tw-hidden tw-size-4 tw-shrink-0 tw-text-muted hover:tw-text-warning group-hover:tw-block group-hover:tw-flex-none",onClick:p=>u(p,f)}))))));function ken(t,e){if(e.isCurrentProject){if(e.processingFiles.has(t))return{status:"processing"};let n=e.failedByPath.get(t);return n?{status:"failed",failedItem:n}:e.success.has(t)?{status:"success"}:{status:"notStarted"}}return e.cachedFiles.has(t)?{status:"success"}:{status:"notStarted"}}var Imt={success:"Processed",failed:"Failed",processing:"Processing",notStarted:"Not started"};function Men({item:t,viewMode:e,loadStatus:n,onDelete:r,onOpenCached:o}){let i=t.id.split(".").pop()||"",s=t.isIgnored?Lc:Sn;return Ce.default.createElement("div",{className:"tw-group tw-flex tw-cursor-pointer tw-items-center tw-rounded-lg tw-border tw-border-solid tw-border-border tw-p-2 tw-transition-shadow hover:tw-shadow-md"},Ce.default.createElement("div",{className:"tw-mr-2 tw-shrink-0"},Ce.default.createElement(Aen,{extension:i,size:"tw-size-8"})),Ce.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col"},Ce.default.createElement(go,{className:"tw-flex-1 tw-text-sm tw-font-medium"},t.isIgnored&&Ce.default.createElement("span",{className:"tw-text-sm tw-text-error"}," (Ignored files)"),t.name),t.id&&Ce.default.createElement(go,{className:"tw-flex-1 tw-text-xs tw-text-faint"},t.id)),Ce.default.createElement("div",{className:"tw-ml-auto tw-flex tw-min-w-[24px] tw-items-center tw-justify-end tw-gap-2"},n&&Ce.default.createElement(ro,{variant:"outline",className:oe("tw-flex tw-items-center tw-gap-1 tw-whitespace-nowrap",n.status==="success"&&"tw-text-success",n.status==="failed"&&"tw-text-error",n.status==="processing"&&"tw-text-accent",n.status==="notStarted"&&"tw-text-muted"),title:n.status==="failed"&&n.failedItem?.error?`Failed: ${n.failedItem.error}`:Imt[n.status]},n.status==="processing"?Ce.default.createElement(Pr,{className:"tw-size-3 tw-animate-spin"}):n.status==="success"?Ce.default.createElement(Pu,{className:"tw-size-3"}):n.status==="failed"?Ce.default.createElement(Fs,{className:"tw-size-3"}):Ce.default.createElement("div",{className:"tw-size-2 tw-rounded-full tw-border tw-border-solid tw-border-border"}),Ce.default.createElement("span",{className:"tw-hidden md:tw-inline"},Imt[n.status])),o&&n?.status==="success"&&Ce.default.createElement(X,{variant:"ghost2",size:"icon",className:"tw-hidden tw-size-5 group-hover:tw-block",onClick:a=>{a.stopPropagation(),o()},title:"View Parsed Content"},Ce.default.createElement(Oc,{className:"tw-size-4"})),Ce.default.createElement(s,{className:"tw-hidden tw-size-4 tw-shrink-0 tw-text-muted hover:tw-text-warning group-hover:tw-block group-hover:tw-flex-none",onClick:a=>r(a,t)})))}function Nen({item:t,onClick:e}){let n,r;switch(t.type){case"tag":n=_m,r="tw-text-context-manager-orange";break;case"folder":n=es,r="tw-text-context-manager-yellow";break;case"files":n=Ur,r="tw-text-context-manager-blue";break;case"ignoreFiles":n=Sn,r="tw-text-context-manager-red";break}return Ce.default.createElement("div",{className:"tw-group tw-flex tw-cursor-pointer tw-items-center tw-rounded-lg tw-border tw-border-solid tw-border-border tw-p-2 tw-transition-shadow hover:tw-shadow-md",onClick:()=>e(t)},Ce.default.createElement("div",{className:"tw-mr-2 tw-shrink-0"},Ce.default.createElement(n,{className:`tw-size-6 ${r}`})),Ce.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-flex-col"},Ce.default.createElement(go,{className:"tw-flex-1 tw-text-sm tw-font-medium"},t.type==="tag"&&Ce.default.createElement("span",{className:"tw-mr-2 tw-text-faint"},"#"),t.name),Ce.default.createElement(go,{className:"tw-flex-1 tw-text-xs tw-text-faint"},t.count," ",t.count===1?"item":"items")))}function Pmt(t){return"type"in t}function Oen({initialProject:t,onSave:e,onCancel:n,app:r}){let o=Fh.Platform.isMobile,[i]=Yx(),[s,a]=(0,Ce.useState)(null);(0,Ce.useEffect)(()=>{let R=!0;return(async()=>{let K=await ti.getInstance().get(t);R&&a(K)})(),()=>{R=!1}},[t]);let l=(0,Ce.useMemo)(()=>br()?.id===t.id,[t.id]),c=(0,Ce.useMemo)(()=>s?.fileContexts?new Set(Object.entries(s.fileContexts).filter(([,R])=>R?.cacheKey).map(([R])=>R)):new Set,[s]),u=(0,Ce.useMemo)(()=>({success:new Set(i.success),failedByPath:new Map(i.failed.map(R=>[R.path,R])),processingFiles:new Set(i.processingFiles),total:new Set(i.total),cachedFiles:c,isCurrentProject:l}),[i.success,i.failed,i.processingFiles,i.total,c,l]),{inclusions:d,exclusions:f}=(0,Ce.useMemo)(()=>Bo({inclusions:t?.contextSource.inclusions,exclusions:t?.contextSource.exclusions,isProject:!0}),[t.contextSource]),p=(0,Ce.useMemo)(()=>r.vault.getFiles(),[r.vault]),m=(0,Ce.useCallback)((R,L,K)=>{let Y=R.filter(nt=>Qr(nt,L,K,!0)),re=(nt,rt,Jt,ke)=>{rt&&rt.forEach(Ln=>{let He={[Jt]:[Ln]};Qr(nt,He,null,!0)&&!ke[Ln].some(Ie=>Ie.id===nt.path)&&ke[Ln].push({id:nt.path,name:nt.basename})})},ae={},ve={},Te={},Ee=[];return(L?.tagPatterns??[]).forEach(nt=>{ae[nt]=[]}),(L?.folderPatterns??[]).forEach(nt=>{ve[nt]=[]}),(L?.extensionPatterns??[]).forEach(nt=>{Te[nt]=[]}),Y.forEach(nt=>{re(nt,L?.tagPatterns,"tagPatterns",ae),re(nt,L?.folderPatterns,"folderPatterns",ve),re(nt,L?.extensionPatterns,"extensionPatterns",Te),L?.notePatterns&&Qr(nt,{notePatterns:L.notePatterns},null,!0)&&!Ee.some(rt=>rt.id===nt.path)&&Ee.push({id:nt.path,name:nt.basename})}),{tags:ae,folders:ve,extensions:Te,notes:Ee}},[]),[h,g]=(0,Ce.useState)(()=>m(p,d,f)),[y,w]=(0,Ce.useState)(()=>{let R=p.filter(L=>f&&Qr(L,f,null,!0));return{files:new Set(R)}}),v=(0,Ce.useRef)(h),x=(0,Ce.useRef)(y),[b,_]=(0,Ce.useState)(""),[T,S]=(0,Ce.useState)(null),[P,A]=(0,Ce.useState)(null),O=(0,Ce.useCallback)((R,L)=>{let K=Object.keys(R.tags),Y=Object.keys(R.folders),re=Object.keys(R.extensions),ae=R.notes.map(ve=>{let Te=r.vault.getAbstractFileByPath(ve.id);if(Te instanceof Fh.TFile)return KN(Te)}).filter(Boolean);return ty({tagPatterns:K,folderPatterns:Y,extensionPatterns:re,notePatterns:ae})},[r.vault]),D=(0,Ce.useCallback)(R=>{let L=new Array(...R.files).map(K=>KN(K));return ty({notePatterns:L})||""},[]);(0,Ce.useEffect)(()=>{v.current=h,x.current=y},[h,y]);let $=(0,Ce.useMemo)(()=>{let R=[],L=(Y,re)=>{re.forEach(ae=>{Y.some(ve=>ve.id===ae.id)||Y.push({id:ae.id,name:ae.name})})};return[h.tags,h.folders,h.extensions,{notes:h.notes}].forEach(Y=>{Object.values(Y).forEach(re=>{L(R,re)})}),R},[h]),B=(0,Ce.useCallback)(R=>{let L=[],K=[],Y=[];return R.split(",").map(ae=>ae.trim()).filter(ae=>ae).forEach(ae=>{ae.startsWith("#")?L.push(ae.substring(1)):ae.startsWith(".")||ae.startsWith("*.")?Y.push(ae.replace("*","")):K.push(ae)}),{tags:L,titles:K,extensions:Y}},[]),W=(0,Ce.useCallback)(R=>[...R].sort((L,K)=>L.name.toLowerCase().localeCompare(K.name.toLowerCase())),[]),F=(0,Ce.useMemo)(()=>{if(b){let R=B(b);return $.filter(L=>{let K=r.vault.getAbstractFileByPath(L.id);if(!(K instanceof Fh.TFile))return!1;let Y=K.extension==="md",re=R.tags.length>0&&Y&&R.tags.some(Ee=>eg(K).some(rt=>(rt.startsWith("#")?rt.substring(1):rt).toLowerCase().includes(Ee.toLowerCase()))),ae=R.titles.length>0&&R.titles.some(Ee=>K.basename.toLowerCase().includes(Ee.toLowerCase())),ve=R.extensions.length>0&&R.extensions.some(Ee=>`.${K.extension}`.toLowerCase()===Ee.toLowerCase());return R.tags.length>0||R.titles.length>0||R.extensions.length>0?re||ae||ve:!1}).map(L=>({id:L.id,name:L.name}))}if(T==="tags"&&P){let R=h.tags[P];return R||[]}if(T==="folders"&&P){let R=h.folders[P];return R||[]}if(T==="files")return h.notes;if(T==="extensions"&&P){let R=h.extensions[P];return R||[]}if(T==="ignoreFiles")return Array.from(y.files).map(R=>({id:R.path,name:R.basename}));if(!T){let R=W(Object.entries(h.tags).map(([re,ae])=>({id:`tag:${re}`,name:re.slice(1),type:"tag",originalId:re,count:ae.length}))),L=W(Object.entries(h.folders).map(([re,ae])=>({id:`folder:${re}`,name:re,type:"folder",originalId:re,count:ae.length}))),K=h.notes.length>0?[{id:"files:all",name:"Files",type:"files",count:h.notes.length}]:[],Y=y.files.size>0?[{id:"ignoreFiles:all",name:"Ignore Files",type:"ignoreFiles",count:y.files.size}]:[];return[...R,...L,...K,...Y]}return[]},[b,T,P,B,$,r.vault,h.tags,h.folders,h.notes,h.extensions,y.files,W]),Z=(0,Ce.useCallback)((R,L)=>Object.entries(R).sort(([K],[Y])=>K.localeCompare(Y)).map(([K,Y])=>({id:K,name:L?L(K):K,count:Y.length})),[]),V=(0,Ce.useCallback)((R,L,K)=>{let Y=ve=>p.filter(Te=>Qr(Te,ve,null,!0)).map(Te=>({id:Te.path,name:Te.basename})),re=[...x.current.files],ae=Y(K).map(ve=>({...ve,isIgnored:re.some(Te=>Te.path===ve.id)}));g(ve=>({...ve,[R]:{...ve[R],[L]:ae}}))},[p]),H=(0,Ce.useCallback)((R,L)=>{let K={tags:{...R.tags},folders:{...R.folders},extensions:{...R.extensions},notes:[...R.notes]},Y=re=>{Object.keys(re).forEach(ae=>{re[ae]=re[ae].filter(ve=>ve.id!==L)})};return Y(K.tags),Y(K.folders),Y(K.extensions),K.notes=K.notes.filter(re=>re.id!==L),K},[]),te=(0,Ce.useCallback)((R,L=null,K=!0)=>{S(R),A(L),K&&_("")},[]),fe=(0,Ce.useMemo)(()=>{let R=L=>(K,Y)=>{K.stopPropagation(),g(re=>{let ae={...re[L]};return delete ae[Y.id],{...re,[L]:ae}})};return{delete:{tag:R("tags"),folder:R("folders"),extension:R("extensions")},add:{tag:()=>{new I1(r,L=>{let K=tB(L);V("tags",K,{tagPatterns:[K]})}).open()},folder:()=>{new S1(r,L=>{V("folders",L,{folderPatterns:[L]})}).open()},file:()=>{new iV({app:r,onFileSelect:L=>{h.notes.find(Y=>Y.id===L.path)||(w(Y=>{let re=new Set(Y.files);return re.delete(L),{...Y,files:re}}),g(Y=>({...Y,notes:[...Y.notes,{id:L.path,name:L.basename}]})))},excludeFilePaths:[],titleOnly:!1}).open()},extension:()=>{new Fh.Notice("Adding extension is temporarily not supported.")},ignoreFile:()=>{new iV({app:r,onFileSelect:L=>{y.files.has(L)||(w(Y=>{let re=new Set(Y.files);return re.add(L),{...Y,files:re}}),g(Y=>H(Y,L.path)))},excludeFilePaths:[],titleOnly:!1}).open()}},click:{tag:L=>{te("tags",L)},folder:L=>{te("folders",L)},extension:L=>{te("extensions",L)},files:()=>{te("files")},ignoreFiles:()=>{te("ignoreFiles")}}}},[r,h.notes,y.files,V,H,te]),me=(0,Ce.useCallback)(R=>{R.type==="tag"&&R.originalId?fe.click.tag(R.originalId):R.type==="folder"&&R.originalId?fe.click.folder(R.originalId):R.type==="files"?fe.click.files():R.type==="ignoreFiles"&&fe.click.ignoreFiles()},[fe]),j=()=>b?`Search Results for: "${b}"`:T==="tags"&&P?`Tag: ${P}`:T==="folders"&&P?`Folder: ${P}`:T==="files"?"Files":T==="extensions"&&P?`Extension: ${P}`:T==="ignoreFiles"?"Ignore Files":"All Categories",G=(R,L)=>{R.stopPropagation();let K=r.vault.getAbstractFileByPath(L.id);K instanceof Fh.TFile&&(w(Y=>{let re=new Set(Y.files);return re.add(K),{...Y,files:re}}),g(Y=>H(Y,L.id)))},J=(0,Ce.useCallback)(()=>{let R=O(v.current,p),L=D(x.current),{inclusions:K,exclusions:Y}=Bo({inclusions:R,exclusions:L,isProject:!0}),re=m(p,K,Y);g(re)},[p,D,O,m]),M=(R,L)=>{R.stopPropagation();let K=r.vault.getAbstractFileByPath(L.id);K instanceof Fh.TFile&&(w(Y=>{let re=new Set(Y.files);return re.delete(K),{...Y,files:re}}),J())},E=()=>{let R=O(h,p),L=D(y);e({...t,contextSource:{...t.contextSource,inclusions:R,exclusions:L}})};return Ce.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},Ce.default.createElement(_mt,{direction:"horizontal",className:"tw-flex-1"},Ce.default.createElement(o0e,{defaultSize:o?35:30,minSize:20,maxSize:40},Ce.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},Ce.default.createElement("div",{className:"tw-border-b tw-p-4"},Ce.default.createElement("h2",{className:"tw-text-lg tw-font-semibold"},"File Context")),Ce.default.createElement(Sy,{className:"tw-max-h-[500px] tw-flex-1"},Ce.default.createElement("div",{className:"tw-space-y-6 tw-p-4"},Ce.default.createElement(Tmt,{title:"Tags",IconComponent:_m,iconColorClassName:"tw-text-context-manager-orange",items:Z(h.tags,R=>R.slice(1)),activeItem:P,activeSection:T,sectionType:"tags",renderIcon:R=>Ce.default.createElement("span",{className:"tw-mr-2 tw-text-faint"},"#"),onItemClick:fe.click.tag,onAddClick:fe.add.tag,onDeleteItem:(R,L)=>fe.delete.tag(R,L),tooltip:"must be in note property"}),Ce.default.createElement(Jp,null),Ce.default.createElement(Tmt,{title:"Folders",IconComponent:es,iconColorClassName:"tw-text-context-manager-yellow",items:Z(h.folders),activeItem:P,activeSection:T,sectionType:"folders",onItemClick:fe.click.folder,onAddClick:fe.add.folder,onDeleteItem:(R,L)=>fe.delete.folder(R,L)}),Ce.default.createElement(Jp,null),Ce.default.createElement("div",null,Ce.default.createElement(i0e,{IconComponent:Ur,title:"Files",iconColorClassName:"tw-text-context-manager-blue",onAddClick:fe.add.file}),Ce.default.createElement("div",{className:oe("tw-cursor-pointer tw-rounded-md tw-p-2 tw-text-sm hover:tw-bg-secondary/50",T==="files"&&"tw-bg-secondary tw-text-normal"),onClick:fe.click.files},"Files (",h.notes.length,")")),Ce.default.createElement(Jp,null),Ce.default.createElement("div",null,Ce.default.createElement(i0e,{IconComponent:Sn,title:"Ignore Files",iconColorClassName:"tw-text-context-manager-red",onAddClick:fe.add.ignoreFile}),Ce.default.createElement("div",{className:oe("tw-cursor-pointer tw-rounded-md tw-p-2 tw-text-sm hover:tw-bg-secondary/50",T==="ignoreFiles"&&"tw-bg-secondary tw-text-normal"),onClick:fe.click.ignoreFiles},"Files (",y.files.size,")")))))),Ce.default.createElement(Smt,{withHandle:!0}),Ce.default.createElement(o0e,{defaultSize:o?65:70},Ce.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},Ce.default.createElement("div",{className:"tw-border-b tw-p-4"},Ce.default.createElement(_L,{placeholder:"Custom search: title, #tag1, .jpg",value:b,onChange:R=>{_(R),R&&te("search",null,!1)}})),Ce.default.createElement("div",{className:"tw-p-4"},Ce.default.createElement("h3",{className:"tw-text-lg tw-font-medium tw-text-muted"},j())),Ce.default.createElement(Sy,{className:"tw-max-h-[400px] tw-flex-1 tw-p-4 tw-pt-0"},F.length===0?Ce.default.createElement("div",{className:"tw-mt-10 tw-text-center tw-text-muted"},T?"No items found.":"No categories found. Add tags, folders, or files using the sidebar."):Ce.default.createElement("div",{className:"tw-space-y-2",style:{display:"block"}},T||b?W(F).map(R=>Pmt(R)?null:Ce.default.createElement(Men,{key:R.id,item:R,viewMode:"list",loadStatus:T==="ignoreFiles"||R.isIgnored?void 0:ken(R.id,u),onDelete:T==="ignoreFiles"||R.isIgnored?M:G,onOpenCached:!R.isIgnored&&R.id.split(".").pop()?.toLowerCase()!=="md"?()=>{let L=R.name||R.id.split("/").pop()||R.id;Gpt(r,s,R.id,L)}:void 0})).filter(Boolean):F.map(R=>Pmt(R)?Ce.default.createElement(Nen,{key:R.id,item:R,onClick:me}):null).filter(Boolean)))))),Ce.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2 tw-border-t tw-p-1"},Ce.default.createElement(X,{variant:"ghost",onClick:n},"Cancel"),Ce.default.createElement(X,{onClick:E},"Save")))}var M1=class extends Fh.Modal{constructor(n,r,o){super(n);this.onSave=r;this.initialProject=o}onOpen(){let{contentEl:n,modalEl:r}=this;this.root=sr(n,this.app),r.addClass("tw-min-w-[50vw]");let o=s=>{this.onSave(s),this.close()},i=()=>{this.close()};this.root.render(Ce.default.createElement(Oen,{initialProject:this.initialProject,onSave:o,onCancel:i,app:this.app}))}onClose(){this.root&&this.root.unmount()}};rn();var dV=N(U());var a0e=N(U(),1);var Sx=N(U(),1),Emt=N(Ve(),1);function Amt(t,e=[]){let n=[];function r(i,s){let a=Sx.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=Sx.useMemo(()=>m,Object.values(m));return(0,Emt.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=Sx.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>Sx.createContext(s));return function(a){let l=a?.[t]||i;return Sx.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,Ren(o,...e)]}function Ren(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return Sx.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var Omt=N(U(),1),zen=N(yo(),1);var ba=N(U(),1);var Len=N(U(),1);function kmt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function Mmt(...t){return e=>{let n=!1,r=t.map(o=>{let i=kmt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():kmt(t[o],null)}}}}var PX=N(Ve(),1);function Nmt(t){let e=Den(t),n=ba.forwardRef((r,o)=>{let{children:i,...s}=r,a=ba.Children.toArray(i),l=a.find(Fen);if(l){let c=l.props.children,u=a.map(d=>d===l?ba.Children.count(c)>1?ba.Children.only(null):ba.isValidElement(c)?c.props.children:null:d);return(0,PX.jsx)(e,{...s,ref:o,children:ba.isValidElement(c)?ba.cloneElement(c,void 0,u):null})}return(0,PX.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function Den(t){let e=ba.forwardRef((n,r)=>{let{children:o,...i}=n;if(ba.isValidElement(o)){let s=Ben(o),a=Uen(i,o.props);return o.type!==ba.Fragment&&(a.ref=r?Mmt(r,s):s),ba.cloneElement(o,a)}return ba.Children.count(o)>1?ba.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var $en=Symbol("radix.slottable");function Fen(t){return ba.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===$en}function Uen(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function Ben(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Rmt=N(Ve(),1),jen=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],s0e=jen.reduce((t,e)=>{let n=Nmt(`Primitive.${e}`),r=Omt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,Rmt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var EX=N(Ve(),1),l0e="Progress",c0e=100,[Ven,Eqr]=Amt(l0e),[Wen,Hen]=Ven(l0e),$mt=a0e.forwardRef((t,e)=>{let{__scopeProgress:n,value:r=null,max:o,getValueLabel:i=Ken,...s}=t;(o||o===0)&&!Lmt(o)&&console.error(qen(`${o}`,"Progress"));let a=Lmt(o)?o:c0e;r!==null&&!Dmt(r,a)&&console.error(Gen(`${r}`,"Progress"));let l=Dmt(r,a)?r:null,c=AX(l)?i(l,a):void 0;return(0,EX.jsx)(Wen,{scope:n,value:l,max:a,children:(0,EX.jsx)(s0e.div,{"aria-valuemax":a,"aria-valuemin":0,"aria-valuenow":AX(l)?l:void 0,"aria-valuetext":c,role:"progressbar","data-state":Bmt(l,a),"data-value":l??void 0,"data-max":a,...s,ref:e})})});$mt.displayName=l0e;var Fmt="ProgressIndicator",Umt=a0e.forwardRef((t,e)=>{let{__scopeProgress:n,...r}=t,o=Hen(Fmt,n);return(0,EX.jsx)(s0e.div,{"data-state":Bmt(o.value,o.max),"data-value":o.value??void 0,"data-max":o.max,...r,ref:e})});Umt.displayName=Fmt;function Ken(t,e){return`${Math.round(t/e*100)}%`}function Bmt(t,e){return t==null?"indeterminate":t===e?"complete":"loading"}function AX(t){return typeof t=="number"}function Lmt(t){return AX(t)&&!isNaN(t)&&t>0}function Dmt(t,e){return AX(t)&&!isNaN(t)&&t<=e&&t>=0}function qen(t,e){return`Invalid prop \`max\` of value \`${t}\` supplied to \`${e}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${c0e}\`.`}function Gen(t,e){return`Invalid prop \`value\` of value \`${t}\` supplied to \`${e}\`. The \`value\` prop must be:
  - a positive number
  - less than the value passed to \`max\` (or ${c0e} if no \`max\` prop is set)
  - \`null\` or \`undefined\` if the progress is indeterminate.

Defaulting to \`null\`.`}var u0e=$mt,zmt=Umt;Kt();var IE=dV.forwardRef(({className:t,value:e,...n},r)=>dV.createElement(u0e,{ref:r,className:oe("tw-relative tw-h-2 tw-w-full tw-overflow-hidden tw-rounded-full tw-bg-interactive-accent/20 tw-border-interactive-accent/30",t),...n},dV.createElement(zmt,{className:"tw-size-full tw-flex-1 tw-bg-interactive-accent tw-transition-all",style:{transform:`translateX(-${100-Math.min(Math.max(e||0,0),100)}%)`}})));IE.displayName=u0e.displayName;vt();var Ze=N(U());function Zen({status:t,contentEmpty:e}){if(t==="ready"&&e)return Ze.default.createElement(Uf,{className:"tw-size-3.5 tw-text-warning"});switch(t){case"ready":return Ze.default.createElement(vm,{className:"tw-size-3.5 tw-text-success"});case"processing":return Ze.default.createElement(Pr,{className:"tw-size-3.5 tw-animate-spin tw-text-loading"});case"failed":return Ze.default.createElement(Fs,{className:"tw-size-3.5 tw-text-error"});case"pending":return Ze.default.createElement(jA,{className:"tw-size-3.5 tw-text-muted"});case"unsupported":return Ze.default.createElement(Uf,{className:"tw-size-3.5 tw-text-muted"})}}function Jen({fileType:t}){switch(t){case"pdf":return Ze.default.createElement(Ur,{className:"tw-size-3.5 tw-text-error"});case"image":return Ze.default.createElement(qS,{className:"tw-size-3.5 tw-text-accent"});case"web":case"youtube":return Ze.default.createElement(Br,{className:"tw-size-3.5 tw-text-accent"});case"audio":return Ze.default.createElement(GS,{className:"tw-size-3.5 tw-text-warning"});default:return Ze.default.createElement(Ur,{className:"tw-size-3.5 tw-text-muted"})}}function Xen(t){return{ready:t.filter(e=>e.status==="ready").length,processing:t.filter(e=>e.status==="processing").length,failed:t.filter(e=>e.status==="failed").length,pending:t.filter(e=>e.status==="pending").length,unsupported:t.filter(e=>e.status==="unsupported").length,total:t.length}}function Qen(t,e){if(t==="ready"&&e)return"No content";switch(t){case"ready":return"Converted";case"processing":return"Converting...";case"failed":return"Failed";case"pending":return"Queued";case"unsupported":return"Unsupported"}}var jmt={processing:0,failed:1,pending:2,unsupported:3,ready:4};function Vmt(t){return[...t].sort((e,n)=>(jmt[e.status]??99)-(jmt[n.status]??99))}function kX({items:t,onRetry:e,onOpenCachedItem:n,onRemoveUrl:r,defaultExpanded:o=!1,maxHeight:i,showHeader:s=!0}){let[a,l]=(0,Ze.useState)(o),c=Xen(t),u=Vmt(t.filter(f=>f.source==="file")),d=Vmt(t.filter(f=>f.source==="url"));return Ze.default.createElement("div",{className:"tw-space-y-2"},s&&Ze.default.createElement("div",{className:"tw-space-y-1"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ze.default.createElement("h4",{className:"tw-text-sm tw-font-medium tw-text-normal"},"Content Conversion")),Ze.default.createElement("p",{className:"tw-text-ui-smaller tw-text-muted"},"Non-markdown files (PDF, images, web pages, ...) are converted to text for AI.")),t.length===0&&Ze.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-3 tw-bg-muted/10"},Ze.default.createElement("div",{className:"tw-text-ui-smaller tw-text-muted"},"No non-markdown files or URLs need conversion for this project.")),t.length>0&&Ze.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border"},Ze.default.createElement(cs,{open:a,onOpenChange:l},Ze.default.createElement(hu,{asChild:!0},Ze.default.createElement(X,{variant:"secondary",className:" tw-flex tw-h-auto tw-w-full tw-items-center tw-justify-between tw-rounded-lg tw-p-3 tw-text-left tw-transition-colors hover:tw-bg-modifier-hover"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},c.ready>0&&Ze.default.createElement(ro,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-bg-success tw-px-1.5 tw-text-ui-smaller tw-text-success"},Ze.default.createElement(vm,{className:"tw-size-3"}),c.ready),c.processing>0&&Ze.default.createElement(ro,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-px-1.5 tw-text-ui-smaller"},Ze.default.createElement(Pr,{className:"tw-size-3 tw-animate-spin"}),c.processing),c.pending>0&&Ze.default.createElement(ro,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-px-1.5 tw-text-ui-smaller"},Ze.default.createElement(jA,{className:"tw-size-3"}),c.pending),c.failed>0&&Ze.default.createElement(ro,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-bg-error tw-px-1.5 tw-text-ui-smaller tw-text-error"},Ze.default.createElement(Fs,{className:"tw-size-3"}),c.failed),c.unsupported>0&&Ze.default.createElement(ro,{variant:"secondary",className:"tw-h-5 tw-gap-1 tw-px-1.5 tw-text-ui-smaller tw-text-muted"},Ze.default.createElement(Uf,{className:"tw-size-3"}),c.unsupported)),Ze.default.createElement("span",{className:"tw-text-ui-smaller tw-text-muted"},c.total," items")),a?Ze.default.createElement(hr,{className:"tw-size-4 tw-text-muted"}):Ze.default.createElement(Di,{className:"tw-size-4 tw-text-muted"}))),Ze.default.createElement(us,null,Ze.default.createElement("div",{className:"tw-space-y-3 tw-border-t tw-border-border tw-p-3"},u.length>0&&Ze.default.createElement("div",{className:"tw-space-y-2"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-px-1"},Ze.default.createElement(v$,{className:"tw-size-3.5 tw-text-accent"}),Ze.default.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"From Files (",u.length,")")),Ze.default.createElement(Wmt,{maxHeight:i||"200px"},u.map(f=>Ze.default.createElement(Hmt,{key:f.id,item:f,onRetry:e,onOpenCached:n?()=>n(f):void 0})))),d.length>0&&Ze.default.createElement("div",{className:"tw-space-y-2"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-px-1"},Ze.default.createElement(Br,{className:"tw-size-3.5 tw-text-accent"}),Ze.default.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"From URLs (",d.length,")")),Ze.default.createElement(Wmt,{maxHeight:i||"200px"},d.map(f=>Ze.default.createElement(Hmt,{key:f.id,item:f,onRetry:e,onOpenCached:n?()=>n(f):void 0,onRemove:r?()=>r(f):void 0})))))))))}function Wmt({maxHeight:t,children:e}){let n=(0,Ze.useRef)(null),[r,o]=(0,Ze.useState)(!1),i=(0,Ze.useCallback)(a=>{n.current=a,a&&o(a.scrollHeight>a.clientHeight)},[]),s=(0,Ze.useCallback)(()=>{let a=n.current;if(!a)return;let l=a.scrollHeight-a.scrollTop-a.clientHeight<4;o(!l)},[]);return Ze.default.createElement("div",{className:"tw-relative"},Ze.default.createElement("div",{ref:i,className:"tw-space-y-1 tw-overflow-y-auto",style:{maxHeight:t},onScroll:s},e),r&&Ze.default.createElement("div",{className:"copilot-fade-mask-bottom tw-pointer-events-none tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-8 tw-rounded-b-md"}))}function Hmt({item:t,onRetry:e,onOpenCached:n,onRemove:r}){let o=t.status==="processing",i=t.status==="failed",s=n&&t.status==="ready"&&!t.contentEmpty;return Ze.default.createElement("div",{className:"tw-group tw-rounded-md tw-border tw-border-border tw-bg-primary tw-p-2.5"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ze.default.createElement(Jen,{fileType:t.fileType}),Ze.default.createElement("div",{className:"tw-min-w-0 tw-flex-1"},Ze.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},Ze.default.createElement(go,{className:"tw-text-sm tw-text-normal"},t.source==="url"?t.id:t.name),Ze.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-1.5"},s&&Ze.default.createElement(X,{variant:"ghost2",size:"icon","aria-label":"View Parsed Content",onClick:a=>{a.stopPropagation(),n()},title:"View Parsed Content",className:"tw-size-5"},Ze.default.createElement(Oc,{className:"tw-size-4"})),(t.status!=="ready"||t.contentEmpty)&&Ze.default.createElement("span",{className:"tw-text-ui-smaller tw-text-muted"},Qen(t.status,t.contentEmpty)),Ze.default.createElement(Zen,{status:t.status,contentEmpty:t.contentEmpty}))))),o&&t.progress!==void 0&&Ze.default.createElement("div",{className:"tw-mt-2 tw-flex tw-items-center tw-gap-2"},Ze.default.createElement(IE,{value:t.progress,className:"tw-h-1.5 tw-flex-1"}),Ze.default.createElement("span",{className:"tw-w-8 tw-text-ui-smaller tw-text-muted"},t.progress,"%")),i&&Ze.default.createElement("div",{className:"tw-mt-2 tw-flex tw-items-center tw-justify-between"},Ze.default.createElement(go,{className:"tw-flex-1 tw-text-ui-smaller tw-text-error"},t.error||"Conversion failed"),Ze.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-gap-1"},e&&Ze.default.createElement(X,{variant:"ghost2",size:"icon","aria-label":"Retry",onClick:()=>e(t.id),title:"Retry",className:"tw-size-5 tw-text-muted hover:tw-text-accent"},Ze.default.createElement(zf,{className:"tw-size-3.5"})),r&&Ze.default.createElement(X,{variant:"ghost2",size:"icon","aria-label":"Remove URL from project",onClick:a=>{a.stopPropagation(),r()},title:"Remove URL from project",className:"tw-size-5 tw-text-muted hover:tw-text-error"},Ze.default.createElement(Sn,{className:"tw-size-3.5"})))))}Ir();dZ();function etn(t,e){return`${t}:${e}`}function MX(t){let e=t.startsWith("http")?t:`https://${t}`;return k_(e)!==null?"youtube":"web"}function Kmt(t,e){let n=new Set,r=[],o=(i,s)=>{if(!i)return;let a=i.split(`
`);for(let l of a){let c=l.trim();if(!c)continue;let u=etn(s,c);n.has(u)||(n.add(u),r.push({id:u,url:c,type:s}))}};return o(t,"web"),o(e,"youtube"),r}function NX(t){let e=new Set,n=new Set,r=[],o=[];for(let i of t){let s=i.url.trim();if(s)if(i.type==="youtube"){if(n.has(s))continue;n.add(s),o.push(s)}else{if(e.has(s))continue;e.add(s),r.push(s)}}return{webUrls:r.join(`
`),youtubeUrls:o.join(`
`)}}function d0e(t){let e=t.trim();if(!e)return!1;try{let n=new URL(e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`);if(n.protocol!=="http:"&&n.protocol!=="https:"||n.username)return!1;let r=n.hostname.toLowerCase();return r?!!(r==="localhost"||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(r)||r.startsWith("[")&&r.endsWith("]")||r.includes(".")):!1}catch{return!1}}var ttn=new Set(["jpg","jpeg","png","gif","bmp","webp","svg","tiff"]),ntn=new Set(["mp3","wav","m4a","ogg","flac","aac","mp4","mpeg","mpga","webm"]);function qmt(t){let e=t.split(".").pop()?.toLowerCase()??"";return e==="pdf"?"pdf":ttn.has(e)?"image":ntn.has(e)?"audio":"other"}function rtn(t){return MX(t)}function OX(t){if(t.startsWith("http://")||t.startsWith("https://"))try{let n=new URL(t),r=n.hostname.replace("www.",""),o=n.pathname+n.search;if(o&&o!=="/"){let s=o.length>30?o.slice(0,30)+"...":o;return r+s}return r}catch{return t.slice(0,50)}let e=t.split("/");return e[e.length-1]||t}function Gmt(t){return t?[...new Set(t.split(`
`).map(e=>e.trim()).filter(Boolean))]:[]}function f0e(t,e,n,r){if(e.has(t))return{status:"processing"};if(n.has(t)){let o=n.get(t);return{status:"failed",error:o.error,failedItem:o}}return r.has(t)?{status:"ready"}:{status:"pending"}}function Ymt(t,e,n){if(!n)return!1;if(e==="youtube"){let o=n.youtubeContexts?.[t];return!o||o.trim().length===0}let r=n.webContexts?.[t];return!r||r.trim().length===0}function p0e(t,e,n,r){if(!r)return"pending";if(e&&n){if(n==="youtube"){let s=r.youtubeContexts?.[t];return s&&s.trim().length>0?"ready":"pending"}let i=r.webContexts?.[t];return i&&i.trim().length>0?"ready":"pending"}return r.fileContexts?.[t]?.cacheKey?"ready":"pending"}function Zmt(t){let{project:e,isCurrentProject:n,liveState:r,projectCache:o,projectFiles:i,supportedExtensions:s}=t,a=new Set(r.success),l=new Set(r.processingFiles),c=new Map;for(let p of r.failed)c.set(p.path,p);let u=[],d=new Map,f=new Set;for(let p of i){if(p.extension==="md")continue;let m=p.path;if(f.has(m))continue;f.add(m);let h=p.extension.toLowerCase();if(!s.has(h)){u.push({id:m,name:OX(m),source:"file",fileType:qmt(m),status:"unsupported",cacheKind:"file"});continue}let g,y;if(n){let w=f0e(m,l,c,a);g=w.status,y=w.error,w.failedItem&&d.set(m,w.failedItem)}else g=p0e(m,!1,null,o);u.push({id:m,name:OX(m),source:"file",fileType:qmt(m),status:g,error:y,cacheKind:"file"})}for(let p of Gmt(e.contextSource?.webUrls)){if(f.has(p))continue;f.add(p);let m=rtn(p),h,g,y;if(n){let w=f0e(p,l,c,a);h=w.status,g=w.error,w.failedItem&&d.set(p,w.failedItem),h==="ready"&&(y=Ymt(p,"web",o)||void 0)}else h=p0e(p,!0,"web",o);u.push({id:p,name:OX(p),source:"url",fileType:m,status:h,error:g,contentEmpty:y,cacheKind:"web"})}for(let p of Gmt(e.contextSource?.youtubeUrls)){if(f.has(p))continue;f.add(p);let m="youtube",h,g,y;if(n){let w=f0e(p,l,c,a);h=w.status,g=w.error,w.failedItem&&d.set(p,w.failedItem),h==="ready"&&(y=Ymt(p,"youtube",o)||void 0)}else h=p0e(p,!0,"youtube",o);u.push({id:p,name:OX(p),source:"url",fileType:m,status:h,error:g,contentEmpty:y,cacheKind:"youtube"})}return{items:u,failedItemMap:n?d:new Map}}bi();fc();var Uh=N(U());function RX(t){let e=tr(),{cacheProject:n,contextSource:r}=t,[o,i]=(0,Uh.useState)(void 0),[s]=Yx(),a=n?.id;(0,Uh.useEffect)(()=>{i(void 0)},[a]),(0,Uh.useEffect)(()=>{if(!n){i(void 0);return}let g=!0;return ti.getInstance().get(n).then(y=>{g&&i(y)}),()=>{g=!1}},[n,s]);let l=!!n&&n.id===br()?.id,c=r?.inclusions??n?.contextSource?.inclusions,u=r?.exclusions??n?.contextSource?.exclusions,[d,f]=(0,Uh.useState)([]);(0,Uh.useEffect)(()=>{if(!n){f([]);return}let{inclusions:g,exclusions:y}=Bo({inclusions:c,exclusions:u,isProject:!0});f(e.vault.getFiles().filter(w=>Qr(w,g,y,!0)))},[e,n,c,u]);let p=(0,Uh.useMemo)(()=>iy.getProjectSupportedExtensions(),[]),m=(0,Uh.useMemo)(()=>n?r?{...n,contextSource:r}:n:null,[n,r]);return{processingData:(0,Uh.useMemo)(()=>!m||o===void 0&&!l?null:Zmt({project:m,isCurrentProject:l,liveState:s,projectCache:o,projectFiles:d,supportedExtensions:p}),[m,l,s,o,d,p]),projectCache:o,isCurrentProject:l}}rn();var N1=N(U());Kt();function fV({value:t,onChange:e,min:n,max:r,step:o,disabled:i,className:s,suffix:a}){let[l,c]=(0,N1.useState)(null),u=l??t;return N1.default.createElement("div",{className:oe("tw-flex tw-items-center tw-gap-4",s)},N1.default.createElement(u4,{value:[u],onValueChange:([d])=>c(d),onValueCommit:([d])=>{c(null),e?.(d)},min:n,max:r,step:o,disabled:i,className:"tw-flex-1"}),N1.default.createElement("div",{className:"tw-min-w-[60px] tw-text-right tw-text-sm tw-tabular-nums"},u>=1e3?`${u%1e3===0?u/1e3:(u/1e3).toFixed(1)}k`:u,a))}rn();vt();var rr=N(U());function otn(){return Math.random().toString(36).substring(2,9)}function Qmt({urls:t,onAdd:e,onRemove:n}){let[r,o]=(0,rr.useState)(""),[i,s]=(0,rr.useState)(!1),a=(0,rr.useRef)(null),l=new Set(t.map(h=>h.url.trim())),c=h=>{let g=h.split(/[\n\s]+/).map(w=>w.trim()).filter(w=>w.length>0&&d0e(w));if(g.length===0)return;let y=[];for(let w of g){let v=w.startsWith("http")?w:`https://${w}`;l.has(v)||(l.add(v),y.push({id:otn(),url:v,type:MX(w)}))}y.length>0&&e(y),o("")},u=h=>{h.key==="Enter"&&r.trim()&&(h.preventDefault(),c(r)),h.key==="Backspace"&&!r&&t.length>0&&n(t[t.length-1].id)},d=h=>{let g=h.clipboardData.getData("text");(g.includes(`
`)||g.split(/\s+/).filter(d0e).length>1)&&(h.preventDefault(),c(g))},f=async()=>{try{let h=await navigator.clipboard.readText();h&&c(h)}catch{}},p=t.filter(h=>h.type==="web"),m=t.filter(h=>h.type==="youtube");return rr.default.createElement("div",{className:"tw-space-y-3"},rr.default.createElement("div",{className:"tw-flex tw-gap-2"},rr.default.createElement("div",{className:`tw-flex tw-min-h-[40px] tw-flex-1 tw-items-center tw-rounded-md tw-border tw-border-border tw-px-3 tw-transition-colors ${i?"tw-border-interactive-accent tw-ring-1 tw-ring-ring":""}`,onClick:()=>a.current?.focus()},rr.default.createElement(_$,{className:"tw-mr-2 tw-size-4 tw-text-muted"}),rr.default.createElement("input",{ref:a,type:"text",value:r,onChange:h=>o(h.target.value),onKeyDown:u,onPaste:d,onFocus:()=>s(!0),onBlur:()=>s(!1),className:"tw-flex-1 tw-bg-transparent tw-text-sm tw-text-normal tw-outline-none placeholder:tw-text-muted",placeholder:"Enter URL and press Enter..."})),rr.default.createElement(X,{variant:"secondary",onClick:f,title:"Paste from clipboard",className:"tw-px-2"},rr.default.createElement(KS,{className:"tw-size-4"}))),t.length>0&&rr.default.createElement("div",{className:"tw-divide-y tw-divide-border tw-rounded-md tw-border tw-border-border"},p.length>0&&rr.default.createElement("div",{className:"tw-p-2"},rr.default.createElement("div",{className:"tw-mb-2 tw-flex tw-items-center tw-gap-1.5 tw-px-1"},rr.default.createElement(Br,{className:"tw-size-3.5 tw-text-accent"}),rr.default.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"Web (",p.length,")")),rr.default.createElement(Jmt,{maxHeight:"120px"},[...p].reverse().map(h=>rr.default.createElement(Xmt,{key:h.id,url:h,onRemove:n})))),m.length>0&&rr.default.createElement("div",{className:"tw-p-2"},rr.default.createElement("div",{className:"tw-mb-2 tw-flex tw-items-center tw-gap-1.5 tw-px-1"},rr.default.createElement(Br,{className:"tw-size-3.5 tw-text-accent"}),rr.default.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"YouTube (",m.length,")")),rr.default.createElement(Jmt,{maxHeight:"120px"},[...m].reverse().map(h=>rr.default.createElement(Xmt,{key:h.id,url:h,onRemove:n}))))),t.length===0&&rr.default.createElement("p",{className:"tw-text-ui-smaller tw-text-muted"},"Add web pages or YouTube videos. Supports batch paste (one URL per line)."))}function Jmt({maxHeight:t,children:e}){let n=(0,rr.useRef)(null),[r,o]=(0,rr.useState)(!1),i=(0,rr.useCallback)(a=>{n.current=a,a&&o(a.scrollHeight>a.clientHeight)},[]),s=(0,rr.useCallback)(()=>{let a=n.current;if(!a)return;let l=a.scrollHeight-a.scrollTop-a.clientHeight<4;o(!l)},[]);return rr.default.createElement("div",{className:"tw-relative"},rr.default.createElement("div",{ref:i,className:"tw-space-y-1 tw-overflow-y-auto",style:{maxHeight:t},onScroll:s},e),r&&rr.default.createElement("div",{className:"copilot-fade-mask-bottom tw-pointer-events-none tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-8 tw-rounded-b-md"}))}function Xmt({url:t,onRemove:e}){return rr.default.createElement("div",{className:"tw-group tw-flex tw-items-center tw-justify-between tw-rounded tw-px-2 tw-py-1.5 hover:tw-bg-modifier-hover"},rr.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-flex-1 tw-items-center tw-gap-2"},rr.default.createElement(Br,{className:"tw-size-3.5 tw-shrink-0 tw-text-accent"}),rr.default.createElement(go,{className:"tw-text-sm tw-text-normal",tooltipContent:t.url},t.url.replace(/^https?:\/\//,""))),rr.default.createElement(X,{type:"button",variant:"ghost2",size:"fit",onClick:()=>e(t.id),className:"tw-rounded tw-p-1 tw-opacity-0 tw-transition-opacity hover:tw-bg-modifier-hover group-hover:tw-opacity-100",title:"Remove"},rr.default.createElement(Sn,{className:"tw-size-3.5 tw-text-muted"})))}It();var ur=N(U());vt();rn();Kt();fc();var itn={folder:{icon:es,colorClass:"tw-text-context-manager-yellow"},tag:{icon:_m,colorClass:"tw-text-context-manager-orange"},note:{icon:Ur,colorClass:"tw-text-context-manager-blue"},extension:{icon:cg,colorClass:"tw-text-context-manager-green"}},stn=["folder","tag","note","extension"],nht={folder:"folderPatterns",tag:"tagPatterns",note:"notePatterns",extension:"extensionPatterns"};function eht(t){let e=[...new Set(eh(t||""))],n=ey(e),r=[];return stn.forEach(o=>{n[nht[o]].forEach(i=>r.push({pattern:i,type:o}))}),r}function tht(t,e,n){let r=[...new Set(eh(t||""))],o=ey(r),i=nht[n];return ty({...o,[i]:o[i].filter(s=>s!==e)})}var rht=({inclusions:t,exclusions:e,onInclusionsChange:n,onExclusionsChange:r,maxCollapsedHeight:o=84,maxExpandedHeight:i=200,actionSlot:s})=>{let[a,l]=(0,ur.useState)(!1),[c,u]=(0,ur.useState)(!1),[d,f]=(0,ur.useState)(0),p=(0,ur.useRef)(null),m=(0,ur.useMemo)(()=>eht(t),[t]),h=(0,ur.useMemo)(()=>eht(e),[e]),g=m.length>0||h.length>0;(0,ur.useLayoutEffect)(()=>{let _=p.current;if(!_)return;let T=()=>{let P=_.scrollHeight;f(P);let A=P>o;u(A),A||l(!1)};if(T(),typeof ResizeObserver>"u")return;let S=new ResizeObserver(T);return S.observe(_),()=>S.disconnect()},[o,m,h]);let y=c&&!a,w=a?Math.min(d,i):o,v=(_,T)=>{n?.(tht(t,_,T))},x=(_,T)=>{r?.(tht(e,_,T))},b=(_,T,S)=>{let P=itn[_.type],A=P.icon;return ur.default.createElement(ro,{key:`${T?"ex":"in"}:${_.type}:${_.pattern}`,variant:"secondary",className:oe("tw-group tw-flex tw-h-7 tw-items-center tw-gap-1.5 tw-py-1 tw-pl-2 tw-pr-1.5 sm:tw-h-6 sm:tw-py-0.5 sm:tw-pl-1.5",T&&"tw-opacity-60")},ur.default.createElement(A,{className:oe("tw-size-4 tw-shrink-0 sm:tw-size-3",P.colorClass)}),ur.default.createElement(go,{className:"tw-max-w-[100px] sm:tw-max-w-[120px]"},_.pattern),S&&ur.default.createElement(X,{variant:"ghost2",size:"fit","aria-label":`Remove ${_.pattern}`,className:"tw-h-auto tw-p-0",onClick:()=>S(_.pattern,_.type)},ur.default.createElement(Sn,{className:"tw-size-4 tw-shrink-0 tw-text-muted hover:tw-text-warning sm:tw-size-3"})))};return g?ur.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},ur.default.createElement("div",{className:"tw-relative tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-2"},ur.default.createElement("div",{ref:p,className:oe("tw-transition-[max-height] tw-duration-300 tw-ease-in-out",a&&d>i?"tw-overflow-y-auto":"tw-overflow-hidden"),style:{maxHeight:c?w:void 0}},m.length>0&&ur.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-gap-1.5"},m.map(_=>b(_,!1,n?v:void 0))),h.length>0&&ur.default.createElement(ur.default.Fragment,null,m.length>0&&ur.default.createElement("div",{className:"tw-my-2 tw-border-t tw-border-dashed tw-border-border"}),ur.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-items-center tw-gap-1.5"},ur.default.createElement("span",{className:"tw-mr-1 tw-text-xs tw-font-medium tw-text-muted"},"Excluded:"),h.map(_=>b(_,!0,r?x:void 0))))),y&&ur.default.createElement("div",{className:"copilot-fade-mask-bottom tw-pointer-events-none tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-10 tw-rounded-b-md"})),(c||s)&&ur.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-justify-between"},c?ur.default.createElement(X,{variant:"ghost2",size:"sm",onClick:()=>l(_=>!_),className:"tw-h-9 tw-gap-1 tw-px-3 tw-text-accent sm:tw-h-auto sm:tw-px-2"},a?ur.default.createElement(ur.default.Fragment,null,"Show less ",ur.default.createElement($s,{className:"tw-size-4 sm:tw-size-3"})):ur.default.createElement(ur.default.Fragment,null,"Show all (",m.length+h.length,")"," ",ur.default.createElement(hr,{className:"tw-size-4 sm:tw-size-3"}))):ur.default.createElement("div",null),s)):ur.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},ur.default.createElement("div",{className:"tw-rounded-md tw-border tw-border-dashed tw-border-border tw-py-4 tw-text-center"},ur.default.createElement("span",{className:"tw-text-sm tw-italic tw-text-muted"},"No file patterns configured")),s&&ur.default.createElement("div",{className:"tw-flex tw-justify-end"},s))};Se();qe();vt();ws();var pV=require("obsidian"),Dt=N(U());function atn({initialProject:t,onSave:e,onCancel:n,plugin:r}){let o=tr(),i=Ht(),[s,a]=(0,Dt.useState)(!1),[l,c]=(0,Dt.useState)({name:!1,systemPrompt:!1,projectModelKey:!1,inclusions:!1}),[u,d]=(0,Dt.useState)(()=>t||{id:zAe(),name:"",description:"",systemPrompt:"",projectModelKey:"",modelConfigs:{temperature:Pc.TEMPERATURE,maxTokens:Pc.MAX_TOKENS},contextSource:{inclusions:"",exclusions:"",webUrls:"",youtubeUrls:""},created:Date.now(),UsageTimestamps:Date.now()}),f=(0,Dt.useMemo)(()=>Kmt(u.contextSource?.webUrls||"",u.contextSource?.youtubeUrls||""),[u.contextSource?.webUrls,u.contextSource?.youtubeUrls]),{processingData:p,projectCache:m,isCurrentProject:h}=RX({cacheProject:t??null,contextSource:u.contextSource}),g=O=>{new M1(o,$=>{d(B=>({...B,contextSource:{...B.contextSource,inclusions:$.contextSource?.inclusions,exclusions:$.contextSource?.exclusions}}))},O).open()},y=()=>u.name&&u.projectModelKey,w=(O,D)=>{d($=>{if(typeof D=="string"&&O==="projectModelKey"&&(D=D.trim()),Array.isArray(D)&&D.every(B=>typeof B=="string")&&(D=D.map(B=>B.trim()).filter(Boolean)),O.includes(".")){let[B,W]=O.split("."),Z=$[B];if(typeof Z=="object"&&Z!==null)return{...$,[B]:{...Z,[W]:D}}}return{...$,[O]:D}})},v=O=>{let D=[...f,...O],{webUrls:$,youtubeUrls:B}=NX(D);w("contextSource.webUrls",$),w("contextSource.youtubeUrls",B)},x=O=>{let D=f.filter(W=>W.id!==O),{webUrls:$,youtubeUrls:B}=NX(D);w("contextSource.webUrls",$),w("contextSource.youtubeUrls",B)},b=O=>{w("contextSource.inclusions",O)},_=O=>{w("contextSource.exclusions",O)},T=O=>{yX(o,m,O)},S=O=>{let D=O.cacheKind==="youtube"?"youtube":"web",$=f.filter(F=>!(F.type===D&&F.url===O.id)),{webUrls:B,youtubeUrls:W}=NX($);w("contextSource.webUrls",B),w("contextSource.youtubeUrls",W)},P=O=>{if(!r?.projectManager||!p)return;let D=p.failedItemMap.get(O);D&&r.projectManager.retryFailedItem(D)},A=async()=>{let O=u.name?.trim()??"",D={...u,name:O},B=["name","projectModelKey"].filter(W=>!D[W]);if(B.length>0){c(W=>({...W,...Object.fromEntries(B.map(F=>[F,!0]))})),new pV.Notice("Please fill in all required fields");return}try{a(!0),await e(D)}catch(W){new pV.Notice(Xt(W)),c(F=>({...F,name:!0}))}finally{a(!1)}};return Dt.default.createElement("div",{className:"tw-flex tw-h-full tw-flex-col"},Dt.default.createElement("div",{className:"tw-shrink-0 tw-px-4 tw-pb-2 tw-pt-4"},Dt.default.createElement("div",{className:"tw-text-xl tw-font-bold tw-text-normal"},t?"Edit Project":"New Project"),Dt.default.createElement("p",{className:"tw-mt-1 tw-text-sm tw-text-muted"},"Configure your project settings and context sources")),Dt.default.createElement(Sy,{className:"tw-min-h-0 tw-flex-1"},Dt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-6 tw-p-4"},Dt.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-4 tw-bg-secondary/50"},Dt.default.createElement("h3",{className:"tw-mb-3 tw-text-sm tw-font-medium tw-text-normal"},"Basic Info"),Dt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},Dt.default.createElement(Zn,{label:"Project Name",required:!0,error:l.name&&!u.name,errorMessage:"Project name is required"},Dt.default.createElement(Xn,{type:"text",value:u.name,onChange:O=>w("name",O.target.value),onBlur:()=>c(O=>({...O,name:!0})),className:"tw-w-full"})),Dt.default.createElement(Zn,{label:"Description",description:"Briefly describe the purpose and goals of the project"},Dt.default.createElement(Xn,{type:"text",value:u.description,onChange:O=>w("description",O.target.value),className:"tw-w-full"})),Dt.default.createElement(Zn,{label:"Project System Prompt",description:"Custom instructions for how the AI should behave in this project context"},Dt.default.createElement(CZ,null),Dt.default.createElement(hf,{value:u.systemPrompt,onChange:O=>w("systemPrompt",O.target.value),onBlur:()=>c(O=>({...O,systemPrompt:!0})),placeholder:"Enter your project system prompt here... Use {[[Note Name]]} to include note contents.",className:"tw-min-h-32"})))),Dt.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-4 tw-bg-secondary/50"},Dt.default.createElement("h3",{className:"tw-mb-3 tw-text-sm tw-font-medium tw-text-normal"},"Model Configuration"),Dt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3"},Dt.default.createElement(Zn,{label:"Default Model",required:!0,error:l.projectModelKey&&!u.projectModelKey,errorMessage:"Default model is required"},Dt.default.createElement(Ty,{value:u.projectModelKey,onChange:O=>{let D=O.target.value,$=i.activeModels.find(F=>F.enabled&&ln(F)===D);if(!$)return;let{hasApiKey:B,errorNotice:W}=kA($,i);w("projectModelKey",D)},onBlur:()=>c(O=>({...O,projectModelKey:!0})),placeholder:"Select a model",options:i.activeModels.filter(O=>O.enabled&&O.projectEnabled).map(O=>({label:OR(O),value:ln(O)}))})),Dt.default.createElement(Zn,{label:"Temperature"},Dt.default.createElement(fV,{value:u.modelConfigs?.temperature??Pc.TEMPERATURE,onChange:O=>w("modelConfigs.temperature",O),min:0,max:2,step:.01,className:"tw-w-full"})),Dt.default.createElement(Zn,{label:"Token Limit"},Dt.default.createElement(fV,{value:u.modelConfigs?.maxTokens??Pc.MAX_TOKENS,onChange:O=>w("modelConfigs.maxTokens",O),min:1,max:65e3,step:1,className:"tw-w-full"})))),Dt.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-4 tw-bg-secondary/50"},Dt.default.createElement("h3",{className:"tw-mb-3 tw-text-sm tw-font-medium tw-text-normal"},"Context Sources"),Dt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Dt.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-4"},Dt.default.createElement(Zn,{label:Dt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Dt.default.createElement("span",null,"File Context"),Dt.default.createElement(Nn,{buttonClassName:"tw-size-4 tw-text-muted",content:Dt.default.createElement("div",{className:"tw-max-w-80"},Dt.default.createElement("strong",null,"Supported File Types:"),Dt.default.createElement("br",null),Dt.default.createElement("strong",null,"\u2022 Documents:")," pdf, doc, docx, ppt, pptx, epub, txt, rtf and many more",Dt.default.createElement("br",null),Dt.default.createElement("strong",null,"\u2022 Images:")," jpg, png, svg, gif, bmp, webp, tiff",Dt.default.createElement("br",null),Dt.default.createElement("strong",null,"\u2022 Spreadsheets:")," xlsx, xls, csv, numbers",Dt.default.createElement("br",null),Dt.default.createElement("br",null),"Non-markdown files are converted to markdown in the background.",Dt.default.createElement("br",null),Dt.default.createElement("strong",null,"Rate limit:")," 50 files or 100MB per 3 hours, whichever is reached first.")})),description:"Define patterns to include specific files, folders or tags (specified in the note property) in the project context."},Dt.default.createElement(rht,{inclusions:u.contextSource?.inclusions,exclusions:u.contextSource?.exclusions,onInclusionsChange:b,onExclusionsChange:_,actionSlot:Dt.default.createElement(X,{size:"lg",className:"tw-h-9 tw-gap-1 tw-px-3 sm:tw-h-auto sm:tw-px-2",onClick:()=>g(u)},Dt.default.createElement(XS,{className:"tw-size-4 sm:tw-size-3.5"}),"Manage Context")}))),Dt.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-4"},Dt.default.createElement("div",{className:"tw-mb-3"},Dt.default.createElement("span",{className:"tw-text-sm tw-font-medium tw-text-normal"},"URLs"),Dt.default.createElement("p",{className:"tw-mt-1 tw-text-ui-smaller tw-text-muted"},"Add web pages or YouTube videos as context sources")),Dt.default.createElement(Qmt,{urls:f,onAdd:v,onRemove:x})))),t&&p&&Dt.default.createElement(kX,{items:p.items,onRetry:h?P:void 0,onOpenCachedItem:m!=null?T:void 0,onRemoveUrl:S,defaultExpanded:!1,maxHeight:"200px"}))),Dt.default.createElement("div",{className:"tw-shrink-0 tw-border-t tw-border-border tw-px-4 tw-py-3"},Dt.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-end tw-gap-2"},Dt.default.createElement(X,{variant:"ghost",onClick:n,disabled:s},"Cancel"),Dt.default.createElement(X,{onClick:A,disabled:s||!y()},s?"Saving...":"Save"))))}var mV=class extends pV.Modal{constructor(n,r,o,i){super(n);this.onSave=r;this.initialProject=o;this.plugin=i}onOpen(){let{contentEl:n,modalEl:r}=this;r.addClass("!tw-max-h-[85vh]"),this.root=sr(n,this.app);let o=async s=>{await this.onSave(s),this.close()},i=()=>{this.close()};this.root.render(Dt.default.createElement(atn,{initialProject:this.initialProject,onSave:o,onCancel:i,plugin:this.plugin}))}onClose(){this.root.unmount()}};rn();bi();Kt();ye();Se();Ky();vt();var LX=require("obsidian"),Ne=N(U());function ltn(t,e,n={}){let{caseSensitive:r=!1,searchInName:o=!0,searchInDescription:i=!0}=n;if(!e.trim())return!0;let s=r?e:e.toLowerCase();return!!(o&&(r?t.name:t.name.toLowerCase()).includes(s)||i&&t.description&&(r?t.description:t.description.toLowerCase()).includes(s))}function oht(t,e,n={}){return!t||t.length===0?[]:e.trim()?t.filter(r=>ltn(r,e,n)):t}function ctn(t){let e=(0,Ne.useCallback)(r=>t?.subscribe(r)??(()=>{}),[t]),n=(0,Ne.useCallback)(()=>t?.getRevision()??0,[t]);return(0,Ne.useSyncExternalStore)(e,n)}function utn({project:t,loadContext:e,onEdit:n,onDelete:r}){let o=tr();return Ne.default.createElement("div",{className:"tw-group tw-flex tw-cursor-pointer tw-items-center tw-justify-between tw-gap-2 tw-rounded-lg tw-border tw-border-solid tw-border-border tw-p-3 tw-transition-all tw-duration-200 tw-bg-secondary/40 hover:tw-border-interactive-accent hover:tw-text-accent hover:tw-shadow-[0_2px_12px_rgba(0,0,0,0.1)] active:tw-scale-[0.98]",onClick:()=>e(t)},Ne.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-gap-2 tw-overflow-hidden"},Ne.default.createElement("div",{className:"tw-text-accent"},Ne.default.createElement(es,{className:"tw-size-4"})),Ne.default.createElement("div",{className:"tw-flex tw-flex-1 tw-flex-col tw-gap-1.5 tw-overflow-hidden"},Ne.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[13px] tw-font-medium tw-text-normal"},t.name),t.description&&Ne.default.createElement("span",{className:"tw-w-full tw-truncate tw-text-[12px] tw-text-muted/80"},t.description))),Ne.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-1 tw-opacity-100 tw-transition-opacity tw-duration-200"},Ne.default.createElement(cn,null,Ne.default.createElement(un,{asChild:!0},Ne.default.createElement(X,{variant:"ghost2",size:"icon","aria-label":"Edit Project",onClick:i=>{i.stopPropagation(),n(t)}},Ne.default.createElement(Rc,{className:"tw-size-4"}))),Ne.default.createElement(on,{side:"bottom"},"Edit Project")),Ne.default.createElement(cn,null,Ne.default.createElement(un,{asChild:!0},Ne.default.createElement(X,{variant:"ghost2",size:"icon","aria-label":"Start Chat",onClick:i=>{i.stopPropagation(),e(t)}},Ne.default.createElement(HA,{className:"tw-size-4"}))),Ne.default.createElement(on,{side:"bottom"},"Start Chat")),Ne.default.createElement(cn,null,Ne.default.createElement(un,{asChild:!0},Ne.default.createElement(X,{variant:"ghost2",size:"icon","aria-label":"Open Project File",onClick:i=>{i.stopPropagation();let s=ef(t.id);s?.filePath&&(o.vault.getAbstractFileByPath(s.filePath)?o.workspace.openLinkText(s.filePath,"",!0):new LX.Notice("Project file is in a hidden folder and cannot be opened from the file explorer."))}},Ne.default.createElement(Oc,{className:"tw-size-4"}))),Ne.default.createElement(on,{side:"bottom"},"Open Project File")),Ne.default.createElement(cn,null,Ne.default.createElement(un,{asChild:!0},Ne.default.createElement(X,{variant:"ghost2",size:"icon","aria-label":"Delete Project",onClick:i=>{i.stopPropagation(),new Cr(o,()=>r(t),`Are you sure you want to delete project "${t.name}"?`,"Delete Project").open()}},Ne.default.createElement(ka,{className:"tw-size-4"}))),Ne.default.createElement(on,{side:"bottom"},"Delete Project"))))}var m0e=(0,Ne.memo)(({className:t,projects:e,defaultOpen:n=!1,app:r,plugin:o,onProjectAdded:i,onEditProject:s,hasMessages:a=!1,showChatUI:l,onClose:c,onProjectClose:u})=>{let[d,f]=(0,Ne.useState)(n),[p,m]=(0,Ne.useState)(!1),[h,g]=(0,Ne.useState)(null),[y,w]=(0,Ne.useState)(""),v=gS(),x=Ht();(0,Ne.useEffect)(()=>{!h||e.some(Z=>Z.id===h.id)||(g(null),m(!1),f(!0),l(!1))},[e,h,l]);let b=o?.projectManager?.getProjectUsageTimestampsManager?.(),_=ctn(b),[T,S]=(0,Ne.useState)(a);!T&&a?(S(!0),f(!1)):T&&!a&&S(!1);let P=(0,Ne.useMemo)(()=>Xh(e,x.projectListSortStrategy,{getName:F=>F.name,getCreatedAtMs:F=>F.created,getLastUsedAtMs:F=>b?b.getEffectiveLastUsedAt(F.id,F.UsageTimestamps):F.UsageTimestamps}),[e,x.projectListSortStrategy,b,_]),A=(0,Ne.useMemo)(()=>oht(P,y),[P,y]),O=()=>{new mV(r,async Z=>{await i(Z)},void 0,o).open()},D=F=>{new mV(r,async V=>{await s(F,V),h&&h.id===F.id&&g(V)},F,o).open()},$=async F=>{let Z=Xu.getInstance(r);try{await Z.deleteProject(F.id),h?.id===F.id&&(g(null),m(!1),f(!0),l(!1)),new LX.Notice(`Project "${F.name}" deleted successfully`)}catch(V){z("[Projects] Failed to delete project",V);let H=V instanceof Error?V.message:String(V);new LX.Notice(`Failed to delete project: ${H}`)}},B=(F,Z)=>{if(F){if(!Z){ee("[Projects] No project provided for context loading");return}g(Z),m(!0),f(!1)}else{g(null),m(!1),f(!0),l(!1),Gx(null);return}},W=F=>{g(F),m(!0),f(!1),l(!0),Gx(F),window.setTimeout(()=>{v.focusInput()},0)};return Ne.default.createElement("div",{className:oe("tw-flex tw-flex-col",t)},Ne.default.createElement("div",{className:"tw-overflow-y-auto"},Ne.default.createElement("div",{className:"tw-flex tw-flex-col"},p&&h?Ne.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-px-2 tw-py-3"},Ne.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2"},Ne.default.createElement("span",{className:"tw-font-semibold tw-text-normal"},"Projects"),Ne.default.createElement(ZP,{value:h.id,onValueChange:F=>{let Z=P.find(V=>V.id===F);Z&&W(Z)}},Ne.default.createElement(z_,{className:"tw-truncate"},Ne.default.createElement(JP,null,Ne.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2"},Ne.default.createElement(es,{className:"tw-size-4 tw-shrink-0 tw-text-accent/70"}),Ne.default.createElement("span",{className:"tw-flex-1 tw-truncate"},h.name)))),Ne.default.createElement(j_,{className:"tw-truncate"},P.map(F=>Ne.default.createElement(V_,{key:F.id,value:F.id,className:"tw-flex tw-items-center tw-gap-2"},Ne.default.createElement("div",{className:"tw-flex tw-min-w-0 tw-items-center tw-gap-2"},Ne.default.createElement(es,{className:"tw-size-4 tw-shrink-0"}),Ne.default.createElement("span",{className:"tw-truncate"},F.name))))))),Ne.default.createElement("div",{className:"tw-ml-1 tw-flex tw-items-center tw-gap-2"},Ne.default.createElement(X,{variant:"secondary",onClick:()=>D(h),className:"hover:tw-text-on-accent hover:tw-bg-accent/50"},Ne.default.createElement(Rc,{className:"tw-mr-1 tw-size-4"}),"Edit"),Ne.default.createElement(cn,null,Ne.default.createElement(un,{asChild:!0},Ne.default.createElement(X,{variant:"ghost2",size:"icon",onClick:()=>{B(!1),u()},"aria-label":"Close Current Project"},Ne.default.createElement(Sn,{className:"tw-size-4"}))),Ne.default.createElement(on,{side:"bottom"},"Close Current Project")))):Ne.default.createElement(cs,{open:d,onOpenChange:f,className:"tw-transition-all tw-duration-200 tw-ease-in-out"},Ne.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-px-4 tw-py-3"},Ne.default.createElement("div",{className:"tw-flex tw-flex-1 tw-items-center tw-gap-2"},Ne.default.createElement("span",{className:"tw-font-semibold tw-text-normal"},"Projects"),Ne.default.createElement(Nn,{content:"Manage your projects with different contexts and configurations.",contentClassName:"tw-w-64",buttonClassName:"tw-size-4 tw-text-muted"})),Ne.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ne.default.createElement(X,{className:"tw-px-2",variant:"secondary",onClick:O},"Create",Ne.default.createElement(Lc,{className:"tw-size-3"})),e.length>0&&Ne.default.createElement(hu,{asChild:!0},Ne.default.createElement(X,{variant:"ghost2",size:"icon"},d?Ne.default.createElement($s,{className:"tw-size-5"}):Ne.default.createElement(hr,{className:"tw-size-5"}))),Ne.default.createElement(cn,null,Ne.default.createElement(un,{asChild:!0},Ne.default.createElement(X,{variant:"ghost2",size:"icon",onClick:()=>c(),"aria-label":"close project mode"},Ne.default.createElement(Sn,{className:"tw-size-4"}))),Ne.default.createElement(on,{side:"bottom"},"Close Project Mode")))),e.length===0&&Ne.default.createElement("div",{className:"tw-px-4 tw-py-2 tw-text-xs tw-text-muted tw-bg-secondary/30"},"No projects available"),Ne.default.createElement(us,{className:"tw-transition-all tw-duration-200 tw-ease-in-out"},Ne.default.createElement("div",{className:"tw-relative tw-bg-secondary/30"},e.length>0&&Ne.default.createElement("div",{className:"tw-px-4 tw-pb-2 tw-pt-3"},Ne.default.createElement(_L,{value:y,onChange:w,placeholder:"Search projects..."})),Ne.default.createElement("div",{className:"tw-max-h-[calc(3*5.7rem)] tw-overflow-y-auto tw-px-4 tw-pb-6 tw-pt-3"},Ne.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 @2xl:tw-grid @2xl:tw-grid-cols-2 @4xl:tw-grid-cols-3"},A.map(F=>Ne.default.createElement(utn,{key:F.id,project:F,loadContext:W,onEdit:D,onDelete:$}))),y.trim()&&A.length===0&&Ne.default.createElement("div",{className:"tw-flex tw-flex-col tw-items-center tw-justify-center tw-py-8 tw-text-muted"},Ne.default.createElement(ZS,{className:"tw-mb-3 tw-size-12 tw-text-muted/50"}),Ne.default.createElement("p",{className:"tw-text-base tw-font-medium"},"No matching projects found"),Ne.default.createElement("p",{className:"tw-mt-1 tw-text-sm"},"Try searching with different keywords"))),e.length>0&&Ne.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-8 tw-bg-[linear-gradient(to_top,var(--background-primary)_0%,var(--background-primary)_30%,transparent_100%)]"}))))),!p&&Ne.default.createElement("div",{className:"tw-flex tw-flex-col tw-items-center tw-justify-center tw-gap-4 tw-p-8 tw-text-muted tw-bg-secondary/30"},Ne.default.createElement("div",{className:"tw-max-w-[600px] tw-space-y-4"},Ne.default.createElement("p",{className:"tw-text-center tw-text-base"},"Create your project-based AI assistants with custom instructions, context, and model configurations."),Ne.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3 tw-text-sm"},Ne.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ne.default.createElement(HA,{className:"tw-size-4"}),Ne.default.createElement("span",null,"Click a project card to start chatting")))))))});m0e.displayName="ProjectList";var Or=N(U()),DX=N(U());rn();vt();Ir();function h0e({onClose:t,onPause:e,onResume:n,onStop:r}){let[o]=DA(),i=(0,DX.useRef)(null),{isActive:s,isPaused:a,indexedCount:l,totalFiles:c,errors:u,completionStatus:d}=o,f=c>0?Math.round(l/c*100):0;(0,DX.useEffect)(()=>(i.current&&(window.clearTimeout(i.current),i.current=null),!s&&d!=="none"&&!(d==="error"&&c===0)&&(i.current=window.setTimeout(()=>{t()},3e3)),()=>{i.current&&(window.clearTimeout(i.current),i.current=null)}),[s,d,c,t]);let p=()=>d==="success"?c===0?"Index Up to Date":"Indexing Complete":d==="cancelled"?"Indexing Cancelled":d==="error"?c===0?"Indexing Failed":"Indexing Complete (with errors)":a?"Indexing Paused":"Indexing Vault";return Or.createElement(wx,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},Or.createElement(vx,null,Or.createElement(CE,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},Or.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},!s&&d!=="none"?d==="error"?Or.createElement(Fs,{className:"tw-size-4 tw-text-error"}):d==="success"?Or.createElement(Pu,{className:"tw-size-4 tw-text-success"}):Or.createElement(xm,{className:"tw-size-4"}):a?Or.createElement(KA,{className:"tw-size-4 tw-text-warning"}):Or.createElement(Pr,{className:"tw-size-4 tw-animate-spin tw-text-accent"}),Or.createElement("span",{className:"tw-text-sm"},p())),Or.createElement(X,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close",onClick:t},Or.createElement(Sn,{className:"tw-size-4"})))),Or.createElement(xx,{className:"tw-space-y-3"},c>0&&Or.createElement("div",{className:"tw-space-y-2"},Or.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},Or.createElement("span",{className:"tw-text-muted"},l,"/",c," files"),Or.createElement("span",{className:"tw-font-medium"},f,"%")),Or.createElement(IE,{value:f,className:"tw-h-2"})),u.length>0&&Or.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1"},Or.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Or.createElement(Fs,{className:"tw-size-3 tw-text-error"}),Or.createElement(ro,{variant:"destructive",className:"tw-text-xs"},u.length," ",u.length===1?"error":"errors")),c===0&&u[0]&&Or.createElement("span",{className:"tw-text-xs tw-text-error"},u[0])),s&&Or.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Or.createElement(X,{size:"sm",variant:"ghost",className:"tw-h-6 tw-px-2 tw-text-xs",onClick:a?n:e},a?Or.createElement(Or.Fragment,null,Or.createElement(I$,{className:"tw-mr-1 tw-size-3"}),"Resume"):Or.createElement(Or.Fragment,null,Or.createElement(KA,{className:"tw-mr-1 tw-size-3"}),"Pause")),Or.createElement(X,{size:"sm",variant:"ghost",className:"tw-h-6 tw-px-2 tw-text-xs",onClick:r},Or.createElement(QS,{className:"tw-mr-1 tw-size-3"}),"Stop"))))}var En=N(U()),hV=N(U());Ir();vt();rn();bi();ye();function g0e({plugin:t,setHiddenCard:e,onEditContext:n}){let r=tr(),[o,i]=(0,hV.useState)(!1),[s]=Yx(),a=s.total,l=s.success,c=s.failed,u=s.processingFiles,d=l.length+c.length,f=a.length>0?Math.round(d/a.length*100):0,p=br()??null,{processingData:m,projectCache:h}=RX({cacheProject:p}),g=(0,hV.useMemo)(()=>u.filter(S=>S.endsWith(".md")),[u]),y=(0,hV.useMemo)(()=>c.filter(S=>S.type==="md"),[c]),w=g.length>0||y.length>0,v=m&&m.items.length>0||w,x=S=>{if(!t?.projectManager||!m)return;let P=m.failedItemMap.get(S);P&&t.projectManager.retryFailedItem(P).catch(A=>{z(`Error retrying failed item: ${A}`)})},b=S=>{t?.projectManager&&t.projectManager.retryFailedItem(S).catch(P=>{z(`Error retrying failed item: ${P}`)})},_=async S=>{if(!p)return;let P=S.cacheKind==="youtube"?"youtubeUrls":"webUrls",O=rh(p.contextSource?.[P]||"").filter($=>$!==S.id),D={...p,contextSource:{...p.contextSource,[P]:O.join(`
`)}};try{await Xu.getInstance().updateProject(p.id,D)}catch($){z(`Error removing URL from project: ${$}`)}},T=S=>{yX(r,h,S)};return En.createElement(wx,{className:"tw-w-full tw-border tw-border-solid tw-border-border tw-bg-transparent tw-shadow-none"},En.createElement(vx,null,En.createElement(CE,{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},En.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},En.createElement(Ur,{className:"tw-size-5"}),"Context Loading",En.createElement(X,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Edit Context",onClick:()=>n?.()},En.createElement(Di,{className:"tw-size-4"}),En.createElement("span",{className:"tw-sr-only"},"Edit Context"))),En.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-rounded tw-p-1"},En.createElement(X,{size:"sm",variant:"ghost2",className:"tw-size-6 tw-p-0 tw-text-muted",title:"Close Progress Bar",onClick:()=>e(!0)},En.createElement(Sn,{className:"tw-size-4"}))))),En.createElement(xx,{className:"tw-space-y-4"},En.createElement("div",{className:"tw-space-y-2"},En.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-text-sm"},En.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},En.createElement("span",{className:"tw-text-muted"},"Total progress"),En.createElement("span",{className:"tw-text-xs tw-text-muted"},"(Success:"," ",En.createElement("span",{className:"tw-font-medium tw-text-success"},l.length),", Failed: ",En.createElement("span",{className:"tw-font-medium tw-text-error"},c.length),")")),En.createElement("span",{className:"tw-font-medium"},d,"/",a.length," (",f,"%)")),En.createElement(IE,{value:f,className:"tw-h-2"})),v&&En.createElement(cs,{open:o,onOpenChange:i},En.createElement(hu,{asChild:!0},En.createElement(X,{variant:"secondary",className:"tw-flex tw-h-auto tw-w-full tw-items-center tw-justify-between tw-rounded-md tw-p-2 tw-text-left tw-transition-colors hover:tw-bg-modifier-hover"},En.createElement("span",{className:"tw-text-ui-smaller tw-text-muted"},"View Details"),o?En.createElement(hr,{className:"tw-size-4 tw-text-muted"}):En.createElement(Di,{className:"tw-size-4 tw-text-muted"}))),En.createElement(us,null,En.createElement("div",{className:"tw-mt-2 tw-space-y-3"},m&&m.items.length>0&&En.createElement(kX,{items:m.items,onRetry:x,onOpenCachedItem:h!=null?T:void 0,onRemoveUrl:_,defaultExpanded:!0,maxHeight:"200px"}),w&&En.createElement("div",{className:"tw-space-y-1.5"},En.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-px-1"},En.createElement(Ur,{className:"tw-size-3.5 tw-text-muted"}),En.createElement("span",{className:"tw-text-ui-smaller tw-font-medium tw-text-muted"},"Markdown Files"),g.length>0&&En.createElement(ro,{variant:"secondary",className:"tw-h-4 tw-gap-0.5 tw-px-1 tw-text-[10px]"},En.createElement(Pr,{className:"tw-size-2.5 tw-animate-spin"}),g.length),y.length>0&&En.createElement(ro,{variant:"secondary",className:"tw-h-4 tw-gap-0.5 tw-bg-error tw-px-1 tw-text-[10px] tw-text-error"},En.createElement(Fs,{className:"tw-size-2.5"}),y.length)),g.map(S=>En.createElement("div",{key:`md-proc-${S}`,className:"tw-flex tw-items-center tw-gap-2 tw-rounded-md tw-border tw-border-border tw-bg-primary tw-p-2"},En.createElement(Pr,{className:"tw-size-3.5 tw-animate-spin tw-text-loading"}),En.createElement(go,{className:"tw-flex-1 tw-text-ui-smaller tw-text-normal",title:S},S))),y.map(S=>En.createElement("div",{key:`md-fail-${S.path}`,className:"tw-rounded-md tw-border tw-border-border tw-bg-primary tw-p-2"},En.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},En.createElement(Fs,{className:"tw-size-3.5 tw-shrink-0 tw-text-error"}),En.createElement(go,{className:"tw-flex-1 tw-text-ui-smaller tw-text-normal",title:S.path},S.path),En.createElement(X,{size:"sm",variant:"ghost",className:"tw-h-5 tw-shrink-0 tw-px-1.5 tw-text-ui-smaller",title:"Retry",onClick:()=>b(S)},En.createElement(zf,{className:"tw-mr-1 tw-size-3"}),"Retry")),S.error&&En.createElement(go,{className:"tw-mt-1 tw-pl-5.5 tw-text-ui-smaller tw-text-error"},S.error)))))))))}It();bi();var Tc=N(U());ye();function iht(t){let[e,n]=(0,Tc.useState)([]);(0,Tc.useEffect)(()=>(n([...t.getMessages()]),t.subscribe(()=>{n([...t.getMessages()])})),[t]);let r=(0,Tc.useCallback)(async(m,h,g,y=!1,w=!1)=>await t.sendMessage(m,h,g,y,w),[t]),o=(0,Tc.useCallback)(async(m,h,g,y=!1)=>await t.editMessage(m,h,g,y),[t]),i=(0,Tc.useCallback)(async(m,h,g)=>await t.regenerateMessage(m,h,g),[t]),s=(0,Tc.useCallback)(async m=>await t.deleteMessage(m),[t]),a=(0,Tc.useCallback)(()=>{t.clearMessages()},[t]),l=(0,Tc.useCallback)(async m=>{await t.truncateAfterMessageId(m)},[t]),c=(0,Tc.useCallback)(m=>{t.addMessage(m)},[t]),u=(0,Tc.useCallback)(m=>{t.loadMessages(m).catch(h=>z("loadMessages failed",h))},[t]),d=(0,Tc.useCallback)(m=>t.getMessage(m),[t]),f=(0,Tc.useCallback)(()=>t.getLLMMessages(),[t]),p=(0,Tc.useCallback)(()=>t.getDebugInfo(),[t]);return{messages:e,sendMessage:r,editMessage:o,regenerateMessage:i,deleteMessage:s,addMessage:c,clearMessages:a,truncateAfterMessageId:l,loadMessages:u,getMessage:d,getLLMMessages:f,getDebugInfo:p}}qe();var PE=require("obsidian"),$X=N(U());function dtn(t,e){let n=e.match(/obsidian:\/\/open\?vault=.*?&file=(.*)$/);if(!n)return null;let r=decodeURIComponent(n[1]),o=t.vault.getAbstractFileByPath(r);return o instanceof PE.TFile||(o=t.vault.getAbstractFileByPath(r+".md"),o instanceof PE.TFile)?o:null}function ftn(t,e){let n=e.split(`
`).filter(o=>o.trim()),r=[];for(let o of n){let i=dtn(t,o.trim());i&&r.push(i)}return r}function sht(t){let{app:e,contextNotes:n,setContextNotes:r,selectedImages:o,onAddImage:i,containerRef:s}=t,[a,l]=(0,$X.useState)(!1);return(0,$X.useEffect)(()=>{let c=s.current;if(!c)return;let u=m=>{if(m.preventDefault(),m.dataTransfer){if(m.dataTransfer.dropEffect="copy",m.dataTransfer.types.includes("copilot/internal-drag"))return;let h=Array.from(m.dataTransfer.items).some(y=>y.kind==="string"),g=Array.from(m.dataTransfer.items).some(y=>y.kind==="file");(h||g)&&l(!0)}},d=m=>{let h=c.getBoundingClientRect(),g=m.clientX,y=m.clientY;(g<h.left||g>=h.right||y<h.top||y>=h.bottom)&&l(!1)},f=async m=>{if(!m.dataTransfer)return;m.preventDefault(),l(!1);let h=m.dataTransfer.items,g=[],y=[];for(let w=0;w<h.length;w++){let v=h[w];v.kind==="string"?g.push(v):v.kind==="file"&&y.push(v)}if(g.length>0){m.stopPropagation();let w=g.map(b=>new Promise(_=>{b.getAsString(T=>_(T))})),v=await Promise.all(w),x=new Map;for(let b of v){let _=ftn(e,b);for(let T of _)x.set(T.path,T)}for(let b of x.values())if(["png","gif","jpeg","jpg","webp"].includes(b.extension)){if(o.some(O=>O.name===b.name)){new PE.Notice("This image is already in the context");continue}let S=await e.vault.readBinary(b),P=new Blob([S]),A=new File([P],b.name,{type:`image/${b.extension}`});i([A])}else if(tg(b)){if(n.some(S=>S.path===b.path)){new PE.Notice("This note is already in the context");continue}r(S=>[...S,b])}else new PE.Notice(`Unsupported file type: ${b.extension}. Supported types: md, pdf, canvas, and images.`)}else if(y.length>0){let w=[];for(let v of y){let x=v.getAsFile();x&&x.type.startsWith("image/")&&w.push(x)}w.length>0&&i(w)}},p=m=>{f(m)};return c.addEventListener("dragover",u),c.addEventListener("dragleave",d),c.addEventListener("drop",p),()=>{c.removeEventListener("dragover",u),c.removeEventListener("dragleave",d),c.removeEventListener("drop",p)}},[e,n,o,i,r,s]),{isDragActive:a}}It();qe();ye();qh();var y0e=async(t,e,n,r,o,i={})=>{let s=new AbortController;o(s);try{await e.runChain(t,s,r,n,i)}catch(a){z("Model request failed:",a);let l=IG("Model request failed: "+Xt(a));n({id:si(),sender:Sd,isErrorMessage:!0,message:l,isVisible:!0,timestamp:ll(new Date)})}};HS();ns();Se();qe();pG();var ds=require("obsidian");var tt=N(U());qh();var ptn=({chainManager:t,onSaveChat:e,updateUserMessageHistory:n,fileParserManager:r,plugin:o,chatUIState:i,chatInput:s})=>{let a=Ht(),l=L5e(),c=(0,tt.useContext)(qA),{messages:u,addMessage:d}=iht(i),[f]=qx(),[p]=kd(),[m,h]=(0,tt.useState)(""),[g,y]=(0,tt.useState)(""),w=(0,tt.useRef)(null),v=(0,tt.useRef)(null),x=(0,tt.useCallback)(ge=>{let ht=v.current,Ef=ht&&ge.sender===Sd&&!ge.isErrorMessage&&!ge.id?{...ge,id:ht}:ge;d(Ef)},[d]),b=(0,tt.useCallback)(ge=>{w.current=ge},[]),[_,T]=(0,tt.useState)(!1),[S,P]=(0,tt.useState)(Td.DEFAULT),[A,O]=(0,tt.useState)([]),[D,$]=(0,tt.useState)(a.autoAddActiveContentToContext===!0&&p!=="project"),[B,W]=(0,tt.useState)(a.autoAddActiveContentToContext===!0&&p!=="project"),[F,Z]=(0,tt.useState)([]),[V,H]=(0,tt.useState)(!1),[te,fe]=(0,tt.useState)([]),[me,j]=(0,tt.useState)(null),[G,J]=(0,tt.useState)(null),[M]=DA(),E=(0,tt.useRef)(!1),R=(0,tt.useRef)(null),L=(0,tt.useCallback)(()=>{o.chatSelectionHighlightController.persistFromPointerDown()},[o]),K=(0,tt.useMemo)(()=>({setCurrentAiMessage:ge=>E.current&&h(ge),setLoadingMessage:ge=>E.current&&P(ge),setLoading:ge=>E.current&&T(ge)}),[]),[Y]=nke(),re=Y.length>0,ae=D&&!re,ve=B&&!re,{activeWebTabForMentions:Te}=iS(),Ee=_Z(),nt=()=>oo!=="project"?!1:me!==null?me:Ee==="loading"||Ee==="error",[rt,Jt]=(0,tt.useState)(Ee);rt!==Ee&&(Jt(Ee),j(null));let ke=()=>oo==="project"||G===!1?!1:M.isActive||M.completionStatus!=="none",[Ln,He]=(0,tt.useState)({isActive:M.isActive,completionStatus:M.completionStatus});(Ln.isActive!==M.isActive||Ln.completionStatus!==M.completionStatus)&&(He({isActive:M.isActive,completionStatus:M.completionStatus}),(M.isActive||M.completionStatus!=="none")&&J(null));let Ie=(0,tt.useCallback)(()=>{J(!1),M.isActive||ul({completionStatus:"none"})},[M.isActive]),dt=(0,tt.useCallback)(async()=>{(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().pauseIndexing()},[]),Me=(0,tt.useCallback)(async()=>{(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().resumeIndexing()},[]),Ue=(0,tt.useCallback)(async()=>{await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().cancelIndexing()},[]),it=(0,tt.useMemo)(()=>{for(let ge=u.length-1;ge>=0;ge--){let ht=u[ge];if(ht.sender===Sd)return ht.responseMetadata?.tokenUsage?.totalTokens??null}return null},[u]),[St,$r]=(0,tt.useState)(null),[oo,Bn]=kd(),Tr=ZN(),Px=(0,tt.useContext)(D$),Zi=o.app||Px,Hh=(0,tt.useCallback)(ge=>{Z(ht=>i7(ht,ge))},[]),{isDragActive:_d}=sht({app:Zi,contextNotes:A,setContextNotes:O,selectedImages:F,onAddImage:Hh,containerRef:R}),Q1=async({toolCalls:ge,urls:ht,contextNotes:ir,contextTags:Ef,contextFolders:HQ,webTabs:GE}={})=>{if(!g&&F.length===0)return;ht&&ht.length>0&&!Mc(p)&&new ds.Notice(XE.URL_PROCESSING_RESTRICTED);try{let YE=[];g&&YE.push({type:"text",text:g});for(let YV of F){let KQ=await YV.arrayBuffer(),qQ=EC(KQ);YE.push({type:"image_url",image_url:{url:`data:${YV.type};base64,${qQ}`}})}let nwt=[...ir||[],...A].filter((YV,KQ,qQ)=>qQ.findIndex(iwt=>iwt.path===YV.path)===KQ),nPe=g.trim();ge&&(nPe+=" "+ge.join(`
`));let rwt={notes:nwt,urls:Mc(p)?ht||[]:[],tags:Ef||[],folders:HQ||[],selectedTextContexts:Y,webTabs:GE||[]};y(""),Z([]),v.current=`msg-${si()}`,K.setLoading(!0),K.setLoadingMessage(Td.DEFAULT);let owt=await i.sendMessage(nPe,rwt,p,ae,ve,YE.length>0?YE:void 0,K.setLoadingMessage);g&&n(g),a.autosaveChat&&await zl();let rPe=i.getLLMMessage(owt);rPe&&await y0e(rPe,t,x,K.setCurrentAiMessage,b,{debug:a.debug,updateLoadingMessage:K.setLoadingMessage}),a.autosaveChat&&await zl()}catch(YE){z("Error sending message:",YE),new ds.Notice("Failed to send message. Please try again.")}finally{K.setLoading(!1),K.setLoadingMessage(Td.DEFAULT),v.current=null}},zl=(0,tt.useCallback)(async()=>{if(!Zi){z("App instance is not available.");return}try{await i.saveChat(f)}catch(ge){z("Error saving chat as note:",Xt(ge)),new ds.Notice("Failed to save chat as note. Check console for details.")}},[Zi,i,f]),zy=(0,tt.useCallback)(ge=>{w.current&&(k(`stopping generation..., reason: ${ge}`),w.current.abort(ge),K.setLoading(!1),K.setLoadingMessage(Td.DEFAULT))},[K]);(0,tt.useEffect)(()=>(E.current=!0,()=>{E.current=!1,w.current&&w.current.abort("component-unmount")}),[]);let eD=(0,tt.useCallback)(async ge=>{if(ge<=0){new ds.Notice("Cannot regenerate the first message.");return}let ht=u[ge];if(!ht){new ds.Notice("Message not found.");return}K.setCurrentAiMessage(""),v.current=`msg-${si()}`,K.setLoading(!0);try{await i.regenerateMessage(ht.id,K.setCurrentAiMessage,x)?a.debug&&k("Message regenerated successfully"):new ds.Notice("Failed to regenerate message. Please try again."),a.autosaveChat&&await zl()}catch(ir){z("Error regenerating message:",ir),new ds.Notice("Failed to regenerate message. Please try again.")}finally{K.setLoading(!1),v.current=null}},[u,i,a.debug,a.autosaveChat,zl,x,K]),tD=(0,tt.useCallback)(async(ge,ht)=>{let ir=u[ge];if(!(!ir||ir.message===ht))try{if(!await i.editMessage(ir.id,ht,p,ae)){new ds.Notice("Failed to edit message. Please try again.");return}if(ir.sender===uo){let HQ=ge<u.length-1;if(await i.truncateAfterMessageId(ir.id),HQ){v.current=`msg-${si()}`,K.setLoading(!0);try{let GE=i.getLLMMessage(ir.id);GE&&await y0e(GE,t,x,K.setCurrentAiMessage,b,{debug:a.debug,updateLoadingMessage:K.setLoadingMessage})}catch(GE){z("Error regenerating AI response:",GE),new ds.Notice("Failed to regenerate AI response. Please try again.")}finally{K.setLoading(!1),v.current=null}}}a.autosaveChat&&await zl()}catch(Ef){z("Error editing message:",Ef),new ds.Notice("Failed to edit message. Please try again.")}},[u,i,p,ae,x,t,a.debug,a.autosaveChat,zl,K,b]);(0,tt.useEffect)(()=>{e&&e(zl)},[e,zl]);let hs=(0,tt.useCallback)(async ge=>{await Xu.getInstance(o.app).createProject(ge),new ds.Notice(`${ge.name} added successfully`),br()?.id===ge.id&&W_e(o.app)},[o.app]),Ta=(0,tt.useCallback)(async(ge,ht)=>{await Xu.getInstance(o.app).updateProject(ge.id,ht),new ds.Notice(`${ge.name} updated successfully`)},[o.app]),sl=(0,tt.useCallback)(ge=>{let ir=wm().find(Ef=>Ef.id===ge);eke(ge),ir?.sourceType==="web"&&o.suppressCurrentWebSelection(ir.url)},[o]);(0,tt.useEffect)(()=>{o.chatSelectionHighlightController.clearIfNoNoteContexts(Y)},[Y,o]),(0,tt.useEffect)(()=>{let ge=()=>{s.focusInput()};return c?.addEventListener(kf.CHAT_IS_VISIBLE,ge),()=>{c?.removeEventListener(kf.CHAT_IS_VISIBLE,ge)}},[c,s]);let If=(0,tt.useCallback)(async ge=>{let ht=u[ge];if(!ht){new ds.Notice("Message not found.");return}try{await i.deleteMessage(ht.id)||new ds.Notice("Failed to delete message. Please try again.")}catch(ir){z("Error deleting message:",ir),new ds.Notice("Failed to delete message. Please try again.")}},[u,i]),jl=(0,tt.useCallback)(async()=>{if(sO(),await Ds.clear(),zy("new-chat"),a.enableRecentConversations)try{let ht=t.chatModelManager.getChatModel();o.userMemoryManager.addRecentConversation(i.getMessages(),ht)}catch(ht){k("Failed to analyze chat messages for memory:",ht)}a.autosaveChat&&await zl(),i.clearMessages(),Yve(),K.setCurrentAiMessage(""),O([]);let ge=Y.find(ht=>ht.sourceType==="web")?.url;tke(),o.chatSelectionHighlightController.clearForNewChat(),o.suppressCurrentWebSelection(ge),oo==="project"?($(!1),W(!1)):($(a.autoAddActiveContentToContext),W(a.autoAddActiveContentToContext))},[zy,t.chatModelManager,i,a.autosaveChat,a.enableRecentConversations,a.autoAddActiveContentToContext,oo,zl,K,o,Y]),Ji=(0,tt.useCallback)(async()=>{try{let ge=await o.getChatHistoryItems();fe(ge)}catch(ge){z("Error loading chat history:",ge),new ds.Notice("Failed to load chat history.")}},[o]),xu=(0,tt.useCallback)(async(ge,ht)=>{try{await o.updateChatTitle(ge,ht),await Ji()}catch(ir){throw z("Error updating chat title:",ir),new ds.Notice("Failed to update chat title."),ir}},[o,Ji]),Kh=(0,tt.useCallback)(async ge=>{try{await o.deleteChatHistory(ge),await Ji()}catch(ht){throw z("Error deleting chat:",ht),new ds.Notice("Failed to delete chat."),ht}},[o,Ji]),Xi=(0,tt.useCallback)(async ge=>{try{await o.loadChatById(ge),Yve()}catch(ht){z("Error loading chat:",ht),new ds.Notice("Failed to load chat.")}},[o]),Pf=(0,tt.useCallback)(async ge=>{try{await o.openChatSourceFile(ge)}catch(ht){z("Error opening source file:",ht),new ds.Notice("Failed to open source file.")}},[o]);(0,tt.useEffect)(()=>{let ge=ht=>{let ir=ht.detail?.reason||"new-chat";zy(ir)};return c?.addEventListener(kf.ABORT_STREAM,ge),()=>{c?.removeEventListener(kf.ABORT_STREAM,ge)}},[c,zy]);let[gt,Je]=(0,tt.useState)({autoAdd:a.autoAddActiveContentToContext,chain:oo});(gt.autoAdd!==a.autoAddActiveContentToContext||gt.chain!==oo)&&(Je({autoAdd:a.autoAddActiveContentToContext,chain:oo}),a.autoAddActiveContentToContext!==void 0&&(oo==="project"?($(!1),W(!1)):($(a.autoAddActiveContentToContext),W(a.autoAddActiveContentToContext))));let xt=()=>tt.default.createElement(tt.default.Fragment,null,tt.default.createElement("div",{className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},tt.default.createElement(Kpt,{currentVersion:o.manifest.version}),tt.default.createElement(Hpt,{chatHistory:u,currentAiMessage:m,streamingMessageId:v.current,loading:_,loadingMessage:S,app:Zi,onRegenerate:eD,onEdit:tD,onDelete:If,onReplaceChat:y,showHelperComponents:oo!=="project"}),nt()?tt.default.createElement("div",{className:"tw-inset-0 tw-z-modal tw-flex tw-items-center tw-justify-center tw-rounded-xl"},tt.default.createElement(g0e,{plugin:o,setHiddenCard:()=>{j(!1)},onEditContext:()=>{let ge=br();ge&&new M1(Zi,ht=>{Ta(ge,ht)},ge).open()}})):ke()?tt.default.createElement("div",{className:"tw-inset-0 tw-z-modal tw-flex tw-items-center tw-justify-center tw-rounded-xl"},tt.default.createElement(h0e,{onClose:Ie,onPause:()=>void dt(),onResume:()=>void Me(),onStop:()=>void Ue()})):tt.default.createElement(tt.default.Fragment,null,tt.default.createElement(Vst,{onNewChat:()=>void jl(),onSaveAsNote:()=>zl(),onLoadHistory:()=>void Ji(),onModeChange:ge=>{$r(oo),ge==="project"&&H(!1)},chatHistory:te,onUpdateChatTitle:xu,onDeleteChat:Kh,onLoadChat:Xi,onOpenSourceFile:Pf,latestTokenCount:it}),tt.default.createElement(nX,{inputMessage:g,setInputMessage:y,handleSendMessage:Q1,isGenerating:_,onStopGenerating:()=>zy("user-stopped"),app:Zi,contextNotes:A,setContextNotes:O,includeActiveNote:D,setIncludeActiveNote:$,includeActiveWebTab:B,setIncludeActiveWebTab:W,activeWebTab:Te,selectedImages:F,onAddImage:Hh,setSelectedImages:Z,disableModelSwitch:oo==="project",selectedTextContexts:Y,onRemoveSelectedText:sl,showProgressCard:()=>{j(!0)},showIndexingCard:()=>{J(!0)}}))));return tt.default.createElement("div",{ref:R,onPointerDownCapture:L,className:"tw-flex tw-size-full tw-flex-col tw-overflow-hidden"},tt.default.createElement("div",{className:"tw-h-full"},tt.default.createElement("div",{className:"tw-relative tw-flex tw-h-full tw-flex-col"},_d&&tt.default.createElement("div",{className:"tw-absolute tw-inset-0 tw-z-modal tw-flex tw-items-center tw-justify-center tw-rounded-md tw-border tw-border-dashed tw-bg-primary tw-opacity-80"},tt.default.createElement("span",null,"Drop files here...")),oo==="project"&&tt.default.createElement("div",{className:`${oo==="project"?"tw-z-modal":""}`},tt.default.createElement(m0e,{projects:l,defaultOpen:!0,app:Zi,plugin:o,hasMessages:!1,onProjectAdded:hs,onEditProject:Ta,onClose:()=>{St?(Bn(St),$r(null)):Bn(Tr?"copilot_plus":"llm_chain")},showChatUI:ge=>H(ge),onProjectClose:()=>{j(null)}})),(oo!=="project"||oo==="project"&&V)&&xt())))},mtn=t=>tt.default.createElement(zft,null,tt.default.createElement(htn,{...t})),htn=t=>{let e=gS();return tt.default.createElement(ptn,{...t,chatInput:e})},aht=mtn;var lht=require("obsidian"),gtn=600,FX=class{constructor(e,n){this.containerEl=e;this.workspace=n;this.debounceTimer=null;this.cssChangeRef=null;this.setupStatusBarClearance()}destroy(){this.debounceTimer&&(window.clearTimeout(this.debounceTimer),this.debounceTimer=null),this.cssChangeRef&&(this.workspace.offref(this.cssChangeRef),this.cssChangeRef=null)}setupStatusBarClearance(){if(lht.Platform.isMobile)return;let e=()=>{let n=this.containerEl.doc.querySelector(".status-bar"),r=this.containerEl.querySelector(".view-content");if(!n||!r)return;r.setCssProps({"--copilot-status-bar-clearance":""});let o=r.getBoundingClientRect().bottom-n.getBoundingClientRect().top;if(o<=0)return;let i=getComputedStyle(n),s=i.display==="none"||i.visibility==="hidden"||parseFloat(i.opacity)===0;r.setCssProps({"--copilot-status-bar-clearance":`${s?0:Math.ceil(o)}px`})};e(),this.cssChangeRef=this.workspace.on("css-change",()=>{this.debounceTimer&&window.clearTimeout(this.debounceTimer),this.debounceTimer=window.setTimeout(e,gtn)})}};It();bi();ws();var gV=require("obsidian"),UX=N(U()),xS=class extends gV.ItemView{constructor(n,r){super(n);this.plugin=r;this.root=null;this.handleSaveAsNote=null;this.keyboardObserver=null;this.drawerHideObserver=null;this.layout=null;this.lastDrawerEl=null;this.windowMigrationDestroy=null;this.app=r.app,this.fileParserManager=r.fileParserManager,this.eventTarget=new EventTarget,this.plugin=r}get chainManager(){return this.plugin.projectManager.getCurrentChainManager()}getViewType(){return No}getIcon(){return"message-square"}getTitle(){return"Copilot Chat"}getDisplayText(){return"Copilot"}async onOpen(){this.root=sr(this.containerEl.children[1],this.app);let n=o=>{this.handleSaveAsNote=o},r=o=>{this.plugin.updateUserMessageHistory(o)};this.renderView(n,r),this.layout=new FX(this.containerEl,this.app.workspace),this.setupMobileKeyboardObserver(),this.setupDrawerHideObserver(),this.windowMigrationDestroy=this.containerEl.onWindowMigrated(()=>{this.root&&(this.root.unmount(),this.root=sr(this.containerEl.children[1],this.app),this.renderView(n,r))}),this.registerEvent(this.app.workspace.on("layout-change",()=>{window.requestAnimationFrame(()=>this.setupDrawerHideObserver())}))}setupMobileKeyboardObserver(){if(!gV.Platform.isMobile)return;this.keyboardObserver?.disconnect();let n=()=>{let r=this.containerEl.closest(".workspace-drawer");if(this.lastDrawerEl&&this.lastDrawerEl!==r&&this.lastDrawerEl.classList.remove("copilot-keyboard-open"),this.lastDrawerEl=r,!r)return;let o=!!this.containerEl.closest(".workspace-drawer-active-tab-content"),i=parseFloat(this.containerEl.doc.documentElement.style.getPropertyValue("--keyboard-height")||"0");r.classList.toggle("copilot-keyboard-open",o&&i>0)};this.keyboardObserver=new MutationObserver(n),this.keyboardObserver.observe(this.containerEl.doc.documentElement,{attributes:!0,attributeFilter:["style"]}),n()}setupDrawerHideObserver(){if(!gV.Platform.isMobile)return;this.drawerHideObserver?.disconnect();let n=this.containerEl.closest(".workspace-drawer");if(!n)return;let r=n.classList.contains("is-hidden");this.drawerHideObserver=new MutationObserver(()=>{let o=n.classList.contains("is-hidden");o&&!r&&this.containerEl.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0,cancelable:!0})),r=o}),this.drawerHideObserver.observe(n,{attributes:!0,attributeFilter:["class"]})}renderView(n,r){this.root&&this.root.render(UX.createElement(qA.Provider,{value:this.eventTarget},UX.createElement(rZ,{delayDuration:0},UX.createElement(aht,{chainManager:this.chainManager,updateUserMessageHistory:r,fileParserManager:this.fileParserManager,plugin:this.plugin,onSaveChat:n,chatUIState:this.plugin.chatUIState}))))}async saveChat(){this.handleSaveAsNote&&await this.handleSaveAsNote()}updateView(){let n=o=>{this.handleSaveAsNote=o},r=o=>{this.plugin.updateUserMessageHistory(o)};this.renderView(n,r)}async onClose(){this.keyboardObserver?.disconnect(),this.keyboardObserver=null,this.drawerHideObserver?.disconnect(),this.drawerHideObserver=null,this.windowMigrationDestroy?.(),this.windowMigrationDestroy=null,this.layout?.destroy(),this.layout=null,this.lastDrawerEl?.classList.remove("copilot-keyboard-open"),this.lastDrawerEl=null,this.root&&(this.root.unmount(),this.root=null)}};qe();av();var cht=require("obsidian");function ytn(t){return Sp().some(r=>{let o=`${Xc(r.project.id)}__`,i=`${r.project.id}__`;return t.startsWith(o)||t.startsWith(i)})}function uht(t){if(typeof t=="string")return t.trim()||void 0;if(typeof t=="number")return String(t)}async function dht(t,e){let n=t.metadataCache.getFileCache(e)?.frontmatter,r=n?.projectId;if(r===void 0&&!n)try{r=(await oy(t,e.path))?.projectId}catch{return}return uht(r)}async function fht(t,e){let n=t.vault.getAbstractFileByPath(e);if(n instanceof cht.TFile)return dht(t,n);try{let r=await oy(t,e);return uht(r?.projectId)}catch{return}}async function BX(t,e,n){return(await Promise.all(e.map(async o=>({file:o,projectId:await dht(t,o)})))).filter(({file:o,projectId:i})=>{if(n){if(i===n)return!0;if(i===void 0){let s=`${Xc(n)}__`,a=`${n}__`;return o.basename.startsWith(s)||o.basename.startsWith(a)}return!1}return!i&&!ytn(o.basename)}).map(({file:o})=>o)}function yV(t){let e=app.metadataCache.getFileCache(t)?.frontmatter;if(e?.topic&&typeof e.topic=="string"&&e.topic.trim())return e.topic.trim();let n=t.basename,r=e?.projectId,o=typeof r=="string"?r.trim():typeof r=="number"?String(r):"";if(o){let i=`${Xc(o)}__`,s=`${o}__`;n.startsWith(i)?n=n.slice(i.length):n.startsWith(s)&&(n=n.slice(s.length))}else n=n.replace(/^[a-zA-Z0-9_-]+__/,"");return n.replace(/\{\$date\}|\d{8}/g,"").replace(/\{\$time\}|\d{6}/g,"").replace(/[@_]/g," ").replace(/\s+/g," ").trim()}function wV(t){let e=app.metadataCache.getFileCache(t)?.frontmatter;return e&&e.epoch?new Date(e.epoch):new Date(t.stat.ctime)}function vV(t){let n=app.metadataCache.getFileCache(t)?.frontmatter?.lastAccessedAt;if(typeof n=="number"&&Number.isFinite(n)&&n>0)return n;if(typeof n=="string"){let r=Number(n);if(Number.isFinite(r)&&r>0)return r;let o=Date.parse(n);if(Number.isFinite(o))return o}return null}function pht(t){let e=yV(t),n=wV(t),r=ll(n);return`${e} - ${r.display}`}Se();Ky();var mht=require("obsidian"),zX=class extends mht.FuzzySuggestModal{constructor(n,r,o,i){super(n);this.chatFiles=r;this.chatHistoryLastAccessedAtManager=o;this.onChooseFile=i}getItems(){let n=q().chatHistorySortStrategy;return Xh(this.chatFiles,n,{getName:r=>yV(r),getCreatedAtMs:r=>wV(r).getTime(),getLastUsedAtMs:r=>{let o=vV(r);return this.chatHistoryLastAccessedAtManager.getEffectiveLastUsedAt(r.path,o)}})}getItemText(n){return pht(n)}onChooseItem(n,r){this.onChooseFile(n)}};It();function wtn(t){return typeof t.commands?.executeCommandById=="function"}function hht(t,e){if(!wtn(e))return;let n=r=>{e.commands.executeCommandById(r)};t.addItem(r=>{r.setTitle("Copilot"),r.setSubmenu();let o=r.submenu;if(!o)return;o.addItem(a=>{a.setTitle("Add selection to chat context").onClick(()=>{n(`copilot:${bt.ADD_SELECTION_TO_CHAT_CONTEXT}`)})}),o.addItem(a=>{a.setTitle("Quick Ask").onClick(()=>{n(`copilot:${bt.TRIGGER_QUICK_ASK}`)})}),o.addItem(a=>{a.setTitle("Trigger quick command").onClick(()=>{n(`copilot:${bt.TRIGGER_QUICK_COMMAND}`)})});let s=td().filter(a=>a.showInContextMenu);s.length>0&&o.addSeparator(),Sj(s).forEach(a=>{o.addItem(l=>{l.setTitle(a.title).onClick(()=>{n(`copilot:${LR(a.title)}`)})})})})}Hx();ye();var jX=class{constructor(e,n){this.handleFileModify=Li(async e=>{if(!$R(e)||bj(e.path))return;let n=await _j(e);this.registerCommand(n),xP(n,n.title)},1e3,{leading:!1,trailing:!0});this.handleFileCreation=async e=>{if(!(!$R(e)||bj(e.path)))try{let n=await _j(e);if(!jJe(e)){let r=X9();n={...n,order:r}}await dbe(e,n),xP(n,n.title),this.registerCommand(n)}catch(n){z(`Error processing custom command creation: ${e.path}`,n)}};this.handleFileDeletion=async e=>{if(!$R(e)||bj(e.path))return;let n=LR(e.basename);this.plugin.removeCommand(n),Cj(e.basename)};this.handleFileRename=async(e,n)=>{if(bj(e.path))return;let r=n.split("/").pop()?.replace(/\.md$/,"");if(r){let o=LR(r);this.plugin.removeCommand(o),Cj(r)}if($R(e)){let o=await _j(e);this.registerCommand(o),xP(o,o.title),await dbe(e,o)}};this.plugin=e,this.vault=n,this.initializeEventListeners()}async initialize(){await Z9(),this.registerCommands()}registerCommands(){td().forEach(n=>{this.registerCommand(n)})}cleanup(){this.vault.off("create",this.handleFileCreation),this.vault.off("delete",this.handleFileDeletion),this.vault.off("rename",this.handleFileRename),this.vault.off("modify",this.handleFileModify)}initializeEventListeners(){this.vault.on("create",this.handleFileCreation),this.vault.on("delete",this.handleFileDeletion),this.vault.on("rename",this.handleFileRename),this.vault.on("modify",this.handleFileModify)}registerCommand(e){let n=LR(e.title);this.plugin.removeCommand(n),this.plugin.addCommand({id:n,name:e.title,editorCallback:r=>{new A_(this.plugin.app,{selectedText:r.getSelection(),command:e}).open(),Xs.getInstance().recordUsage(e).catch(o=>z("recordUsage failed",o))}})}};Se();qe();ye();async function vtn(t){let n=`${h_()}/unsupported`;return await Fr(n),Promise.all(t.map(async r=>{let o=`${n}/${r.title}.md`,i=await app.vault.create(o,r.content);await app.fileManager.processFrontMatter(i,s=>{s[Av]=r.showInContextMenu,s[kv]=r.showInSlashMenu,s[gy]=r.order,s[Mv]=r.modelKey,s[Nv]=0})}))}async function ght(){let t=q().inlineEditCommands;if(!t||t.length===0)return;let e=[],n=[],r=td(),o=t.map((s,a)=>({title:s.name,content:s.prompt,showInContextMenu:s.showInContextMenu,showInSlashMenu:!1,order:a*10,modelKey:s.modelKey??"",lastUsedMs:0}));for(let s of o){let a=Y9(s.title,r);a?n.push({...s,title:encodeURIComponent(s.title),content:`> ${a} 

Original name: ${s.title} 

${s.content}`}):e.push(s)}await Xs.getInstance().updateCommands([...r.map(s=>({...s,showInSlashMenu:!0})),...e]);let i=`We have upgraded your commands to the new format. They are now also stored as notes in ${h_()}.`;n.length>0&&(await vtn(n),i+=`

We found ${n.length} unsupported commands. They are saved in ${h_()}/unsupported. To fix them, please resolve the errors and move the note file out of the unsupported folder.`),pe("inlineEditCommands",[]),new Cr(app,()=>{},i,"\u{1F680} New Copilot Custom Commands","OK","").open()}async function w0e(){let t=td(),e=zJe.filter(r=>!t.some(o=>o.title===r.title)),n=[...t,...e];await Xs.getInstance().updateCommands(n)}async function yht(){if(q().suggestedDefaultCommands)return;td().length===0&&(new Cr(app,()=>{w0e().catch(n=>z("generateDefaultCommands failed",n))},"Would you like to add Copilot recommended commands in your custom prompts folder? These commands will be available through the right-click context menu and slash commands in chat.","Welcome to Copilot","Confirm","Skip").open(),pe("suggestedDefaultCommands",!0))}Ir();ye();Se();Hx();var O1=require("obsidian"),VX=class{constructor(e){this.folderChangeRequestId=0;this.fileModifyDebouncers=new Map;this.handleSettingsChange=(e,n)=>{e.projectsFolder!==n.projectsFolder&&this.debouncedFolderChange(n.projectsFolder)};this.debouncedFolderChange=Li(e=>{this.handleProjectsFolderChange(e)},1e3,{leading:!1,trailing:!0});this.handleFileCreation=async e=>{if(!(!T0(e)||th(e.path)))try{let n=await E0(e);if(!n)return;let r=ef(n.project.id);if(r&&r.filePath!==n.filePath){ee(`[Projects] Duplicate id="${n.project.id}": existing=${r.filePath}, incoming=${n.filePath}; ignored`);return}await pB(e,n);let o=await E0(e);o&&m0(o)}catch(n){z(`[Projects] Error on file creation: ${e.path}`,n)}};this.handleFileDeletion=async e=>{if(!(!T0(e)||th(e.path))){this.evictFileModifyDebouncer(e.path);try{let n=eO(e.path);AC(e.path),n&&(br()?.id===n.project.id&&new O1.Notice(`Project "${n.project.name}" was deleted.`),await ti.getInstance().clearForProject(n.project).catch(o=>z("[Projects] Failed to clear context cache on external delete",o)),cv().catch(o=>z("[Projects] Rescan after delete failed",o)))}catch(n){z(`[Projects] Error on file deletion: ${e.path}`,n)}}};this.handleFileRename=async(e,n)=>{if(th(e.path)||th(n))return;let r=this.isProjectConfigPathString(n),o=T0(e);if(!(!r&&!o)){r&&this.evictFileModifyDebouncer(n);try{let i=r?eO(n):void 0;if(o){let s=await E0(e);if(!s){r&&AC(n);return}let a=ef(s.project.id);if(a&&a.filePath!==s.filePath&&a.filePath!==n){r&&AC(n),ee(`[Projects] Duplicate id="${s.project.id}" after rename: existing=${a.filePath}, incoming=${s.filePath}; ignored`);return}await pB(e,s);let c=await E0(e);c?r?uye(n,c):m0(c):r&&AC(n)}else r&&AC(n);r&&!o&&i&&(br()?.id===i.project.id&&new O1.Notice(`Project "${i.project.name}" was moved.`),await ti.getInstance().clearForProject(i.project).catch(a=>z("[Projects] Failed to clear context cache on rename-out",a)),cv().catch(a=>z("[Projects] Rescan after rename-out failed",a)))}catch(i){z(`[Projects] Error on file rename: ${n} -> ${e.path}`,i)}}};this.handleFileModify=e=>{!T0(e)||th(e.path)||this.getFileModifyDebouncer(e.path)(e)};this.vault=e.vault,this.manager=Xu.getInstance(e)}async initialize(){this.initializeEventListeners(),await this.manager.initialize()}cleanup(){for(let e of this.fileModifyDebouncers.values())e.cancel();this.fileModifyDebouncers.clear(),this.debouncedFolderChange.cancel(),this.settingsUnsubscriber?.(),this.vault.off("create",this.handleFileCreation),this.vault.off("delete",this.handleFileDeletion),this.vault.off("rename",this.handleFileRename),this.vault.off("modify",this.handleFileModify)}initializeEventListeners(){this.vault.on("create",this.handleFileCreation),this.vault.on("delete",this.handleFileDeletion),this.vault.on("rename",this.handleFileRename),this.vault.on("modify",this.handleFileModify),this.settingsUnsubscriber=Ho(this.handleSettingsChange)}async handleProjectsFolderChange(e){let n=++this.folderChangeRequestId;try{let r=await this.manager.fetchProjects();if(n!==this.folderChangeRequestId)return;for(let a of this.fileModifyDebouncers.values())a.cancel();this.fileModifyDebouncers.clear();let o=Sp(),i=ti.getInstance();await Promise.all(o.map(a=>i.clearForProject(a.project).catch(l=>z("[Projects] Failed to clear context cache on folder switch",l)))),uB(r);let s=br();s&&(ef(s.id)||new O1.Notice(`Project "${s.name}" not found in new folder. Cleared selection.`)),k(`[Projects] Folder changed -> reloaded: ${e}`),new O1.Notice(`Projects folder updated: ${e}`)}catch(r){if(n!==this.folderChangeRequestId)return;for(let s of this.fileModifyDebouncers.values())s.cancel();this.fileModifyDebouncers.clear();let o=Sp(),i=ti.getInstance();await Promise.all(o.map(s=>i.clearForProject(s.project).catch(a=>z("[Projects] Failed to clear context cache on folder switch failure",a)))),uB([]),z(`[Projects] Failed to reload after folder change: ${e}`,r),new O1.Notice(`Failed to reload projects from "${e}". Projects cleared \u2014 reopen settings to retry.`)}}isProjectConfigPathString(e){let n=ja();if(!e.startsWith(n+"/"))return!1;let r=e.slice(n.length+1);if(r.startsWith(`${nf}/`))return!1;let o=r.split("/");return o.length===2&&o[1]===sv}evictFileModifyDebouncer(e){let n=this.fileModifyDebouncers.get(e);n&&(n.cancel(),this.fileModifyDebouncers.delete(e))}async processFileModify(e){if(!(!T0(e)||th(e.path)))try{let n=await E0(e);if(!n){let i=eO(e.path);AC(e.path),i&&(ti.getInstance().clearForProject(i.project).catch(s=>z("[Projects] Failed to clear context cache on invalid edit",s)),cv().catch(s=>z("[Projects] Rescan after invalid edit failed",s)));return}let r=ef(n.project.id);if(r&&r.filePath!==n.filePath){let i=eO(e.path);AC(e.path),i&&(ti.getInstance().clearForProject(i.project).catch(s=>z("[Projects] Failed to clear context cache on duplicate edit",s)),cv().catch(s=>z("[Projects] Rescan after duplicate edit failed",s))),ee(`[Projects] Duplicate id="${n.project.id}" on modify: existing=${r.filePath}, incoming=${n.filePath}; ignored`);return}let o=eO(e.path);o&&o.project.id!==n.project.id&&await ti.getInstance().clearForProject(o.project).catch(i=>z("[Projects] Failed to clear context cache on id change",i)),uye(e.path,n)}catch(n){z(`[Projects] Error on file modify: ${e.path}`,n)}}getFileModifyDebouncer(e){let n=this.fileModifyDebouncers.get(e);return n||(n=Li(r=>{this.processFileModify(r)},1e3,{leading:!1,trailing:!0}),this.fileModifyDebouncers.set(e,n)),n}};It();Se();Qi();Ir();ye();It();async function wht(t,e){await e.clearChatMemory();for(let n=0;n<t.length-1;n++){let r=t[n];if(r.sender===uo){let o=t[n+1];o?.sender===Sd&&await e.saveContext({input:r.message},{output:o.message})}}}Ir();Qi();It();TC();ye();var vht=["L1_SYSTEM","L2_PREVIOUS","L3_TURN","L4_STRIP","L5_USER"],xht={L1_SYSTEM:"System Instructions",L2_PREVIOUS:"Previous Turn Context",L3_TURN:"Current Turn Context",L4_STRIP:"Conversation Strip",L5_USER:"User Message"};var bS=class bS{constructor(){}static getInstance(){return bS.instance||(bS.instance=new bS),bS.instance}buildEnvelope(e){let n=vht.map(a=>this.buildLayer(a,e.layerSegments[a]??[])),r=this.serializeLayers(n),o=this.collectLayerHashes(n),i=this.hash(r),s=typeof e.metadata?.debugLabel=="string"?e.metadata.debugLabel:void 0;return s&&k(`[PromptContextEngine] Built envelope for ${s}`,o),{version:bS.ENVELOPE_VERSION,conversationId:e.conversationId,messageId:e.messageId,layers:n,serializedText:r,layerHashes:o,combinedHash:i,debug:{warnings:this.collectWarnings(n)}}}buildLayer(e,n){let r=n.map((i,s)=>({...i,id:i.id||`${e}-segment-${s}`,content:this.normalizeWhitespace(i.content),stable:i.stable??!0})),o=this.normalizeWhitespace(r.map(i=>i.content).filter(Boolean).join(`

`));return{id:e,label:xht[e],text:o,segments:r,stable:r.every(i=>i.stable),metadata:r.length===1?r[0].metadata:void 0,hash:this.hash(o)}}serializeLayers(e){return e.map(n=>n.text).filter(n=>n.length>0).join(`

`)}collectLayerHashes(e){return e.reduce((n,r)=>(n[r.id]=r.hash,n),{})}hash(e){return p5e(e||"")}normalizeWhitespace(e){return e.replace(/\s+$/g,"").trim()}collectWarnings(e){let n=[];return e.forEach(r=>{if(!r.text)return;r.text.includes("\0")&&n.push(`Layer ${r.id} contains control characters and was normalized`)}),n}};bS.ENVELOPE_VERSION=1;var WX=bS;function xtn(t){let e=/<path>([^<]+)<\/path>/.exec(t);if(e)return e[1];let n=/<url>([^<]+)<\/url>/.exec(t);if(n)return n[1];let r=/<name>([^<]+)<\/name>/.exec(t);return r?r[1]:""}function btn(t,e,n,r={}){let o=r.verbatimThreshold??pf.verbatimThreshold;if(t.length<=o)return t;let i=r.previewCharsPerSection??pf.previewCharsPerSection,s=r.maxSections??pf.maxSections,a=fP(t,i,s);return`<prior_context source="${I9(e)}" type="${n}">
${a}
</prior_context>`}function bht(t,e,n={}){if(!T9(e))return t;let r=n.verbatimThreshold??pf.verbatimThreshold;if(t.length<=r)return t;let o=TR(t,e)||xtn(t),i=uj(t),s=dP(e);return btn(i,o,s,n)}function Cht(){return`<prior_context_note>
The above prior_context blocks contain previews of content from earlier turns.
To access full content: use [[note title]] for notes, or ask to read a specific URL/video.
</prior_context_note>`}function _ht(t,e){if(!t.trim())return[];let n=[],o=[...SR.map(l=>l.tag),"prior_context"],i=new RegExp(`<(${o.join("|")})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,"g"),s=new Map,a;for(;(a=i.exec(t))!==null;){let l=a[0],c=a[1];if(c==="prior_context"){let d=/source="([^"]+)"/.exec(l)?.[1]??"prior_context";n.push({id:d,content:l,stable:e,metadata:{source:"previous_turns_compacted",notePath:d}})}else{let u=TR(l,c),d;if(u)d=u;else{let p=(s.get(c)||0)+1;s.set(c,p),d=p===1?c:`${c}:${p}`}let f=dP(c)==="note";n.push({id:d,content:l,stable:e,metadata:{source:e?"previous_turns":"current_turn",...f?{notePath:d}:{}}})}}return n}Ir();It();ye();FP();aL();qe();fL();var xV=require("obsidian");It();var HX=class t{constructor(){}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processEmbeddedPDFs(e,n,r){let o=/!\[\[(.*?\.pdf)\]\]/g,i=[...e.matchAll(o)];for(let s of i){let a=s[1],l=n.getAbstractFileByPath(a);if(l instanceof xV.TFile)try{let c=await r.parseFile(l,n);e=e.replace(s[0],`

<${sD}>
<name>${a}</name>
<content>
${c}
</content>
</${sD}>

`)}catch(c){z(`Error processing embedded PDF ${a}:`,c),e=e.replace(s[0],`

<${sD}>
<name>${a}</name>
<error>Could not process PDF</error>
</${sD}>

`)}}return e}async processDataviewBlocks(e,n){let r=app.plugins?.plugins?.dataview;if(!r)return e;let o=r.api;if(!o)return e;let i=/```(dataview|dataviewjs)\s*\n([\s\S]*?)```/g,s=[...e.matchAll(i)];for(let a=s.length-1;a>=0;a--){let l=s[a],c=l[1],u=l[2].trim(),d=l.index,f=d+l[0].length;try{let p=await Promise.race([this.executeDataviewQuery(o,u,c,n),new Promise((g,y)=>window.setTimeout(()=>y(new Error("Query timeout")),5e3))]),m=typeof p=="string"?p:JSON.stringify(p),h=`

<${aD}>
<query_type>${c}</query_type>
<original_query>
${u}
</original_query>
<executed_result>
${m}
</executed_result>
</${aD}>

`;e=e.slice(0,d)+h+e.slice(f)}catch(p){z("Error executing Dataview query:",p);let m=`

<${aD}>
<query_type>${c}</query_type>
<original_query>
${u}
</original_query>
<error>${p instanceof Error?p.message:"Query execution failed"}</error>
</${aD}>

`;e=e.slice(0,d)+m+e.slice(f)}}return e}async executeDataviewQuery(e,n,r,o){if(r==="dataviewjs")return"[DataviewJS execution not yet supported - showing original query]";let i=await e.query(n,o);if(!i.successful)throw new Error(i.error??"Query failed");return this.formatDataviewResult(i.value)}formatDataviewResult(e){return e?e.type==="list"?this.formatDataviewList(e.values):e.type==="table"?this.formatDataviewTable(e.headers??[],e.values):e.type==="task"?this.formatDataviewTasks(e.values):Array.isArray(e)?e.map(n=>this.formatDataviewValue(n)).join(`
`):JSON.stringify(e):"No results"}formatDataviewList(e){return!e||e.length===0?"No results":e.map(n=>`- ${this.formatDataviewValue(n)}`).join(`
`)}formatDataviewTable(e,n){if(!n||n.length===0)return"No results";let r=`| ${e.join(" | ")} |
`;r+=`| ${e.map(()=>"---").join(" | ")} |
`;for(let o of n)r+=`| ${o.map(i=>this.formatDataviewValue(i)).join(" | ")} |
`;return r}formatDataviewTasks(e){return!e||e.length===0?"No results":e.map(n=>`- ${n.completed?"[x]":"[ ]"} ${this.formatDataviewValue(n.text??n)}`).join(`
`)}formatDataviewValue(e){return e==null?"":e&&typeof e=="object"&&"path"in e?`[[${e.path}]]`:Array.isArray(e)?e.map(n=>this.formatDataviewValue(n)).join(", "):typeof e=="object"?JSON.stringify(e):`${e}`}async buildMarkdownContextContent(e,n,r,o){let i=await r.parseFile(e,n);return i=await this.processEmbeddedNotes(i,e,n,r,o),Mc(o)&&(i=await this.processEmbeddedPDFs(i,n,r)),await this.processDataviewBlocks(i,e.path)}async processEmbeddedNotes(e,n,r,o,i){let s=/!\[\[([^\]]+)\]\]/g,a,l=0,c="";for(;(a=s.exec(e))!==null;){c+=e.slice(l,a.index);let u=a[1].trim(),d=await this.buildEmbeddedNoteBlock(u,a[0],n,r,o,i);c+=d,l=a.index+a[0].length}return c+=e.slice(l),c}async buildEmbeddedNoteBlock(e,n,r,o,i,s){let a=this.parseEmbeddedLinkTarget(e);if(!a)return n;let l=a.path===null?r:app.metadataCache.getFirstLinkpathDest(a.path,r.path);if(!(l instanceof xV.TFile))return this.formatEmbeddedNoteBlock({title:a.path??r.basename,path:a.path??r.path,heading:a.heading,blockId:a.blockId,error:"Embedded note not found"});if(l.extension!=="md")return n;try{let c=await i.parseFile(l,o);if(a.heading||a.blockId){let u=this.extractMarkdownSegment(l,c,a);if(!u.found){let d=a.blockId?`block reference "${a.blockId}"`:`heading "${a.heading??""}"`;throw new Error(`Embedded note ${d} not found in ${l.path}`)}c=u.content}return Mc(s)&&(c=await this.processEmbeddedPDFs(c,o,i)),c=await this.processDataviewBlocks(c,l.path),this.formatEmbeddedNoteBlock({title:l.basename,path:l.path,heading:a.heading,blockId:a.blockId,content:c})}catch(c){ee("Failed to process embedded note",c);let u=c instanceof Error?c.message:"Could not process embedded note";return this.formatEmbeddedNoteBlock({title:l.basename,path:l.path,heading:a.heading,blockId:a.blockId,error:u})}}parseEmbeddedLinkTarget(e){if(!e)return null;let n=e.indexOf("|"),o=(n>=0?e.slice(0,n):e).trim();if(!o)return{path:null};let i,s,a=o.indexOf("#^");a!==-1&&(i=o.slice(a+2).trim(),o=o.slice(0,a));let l=o.indexOf("#");return l!==-1&&(s=o.slice(l+1).trim(),o=o.slice(0,l)),{path:o.length>0?o:null,heading:s&&s.length>0?s:void 0,blockId:i&&i.length>0?i:void 0}}extractMarkdownSegment(e,n,r){let o=app.metadataCache.getFileCache(e);if(r.blockId){let i=o?.blocks?.[r.blockId],s=i?.position?.start?.offset,a=i?.position?.end?.offset;return s===void 0||a===void 0?{content:"",found:!1}:{content:n.slice(s,a),found:!0}}if(r.heading){let i=o?.headings??[],s=this.normalizeHeadingForMatch(r.heading),a=i.findIndex(d=>this.normalizeHeadingForMatch(d.heading)===s);if(a===-1)return{content:"",found:!1};let l=i[a],c=l.position?.start?.offset??0,u=n.length;for(let d=a+1;d<i.length;d++)if(i[d].level<=l.level){u=i[d].position?.start?.offset??u;break}return{content:n.slice(c,u),found:!0}}return{content:n,found:!0}}normalizeHeadingForMatch(e){return e.trim().toLowerCase().replace(/\s+/g," ")}formatEmbeddedNoteBlock(e){let{title:n,path:r,heading:o,blockId:i,content:s,error:a}=e,l=`

<${tee}>
<title>${n}</title>
<path>${r}</path>`;return o&&(l+=`
<heading>${o}</heading>`),i&&(l+=`
<block_id>${i}</block_id>`),a?l+=`
<error>${a}</error>`:l+=`
<content>
${s??""}
</content>`,l+=`
</${tee}>

`,l}async processContextNotes(e,n,r,o,i,s,a){let l="",c=async(d,f=oD)=>{try{if(e.has(d.path)){k(`Skipping note ${d.path} as it was included via custom prompt.`);return}if(!n.supportsExtension(d.extension)){ee(`Unsupported file type: ${d.extension}`);return}if(!Mc(a)&&!FW(d)){ee(`File type ${d.extension} requires Copilot Plus mode for context processing.`),new xV.Notice(XE.NON_MARKDOWN_FILES_RESTRICTED);return}let p=d.extension==="md"?await this.buildMarkdownContextContent(d,r,n,a):await n.parseFile(d,r),m=await r.adapter.stat(d.path),h=m?new Date(m.ctime).toISOString():"Unknown",g=m?new Date(m.mtime).toISOString():"Unknown";l+=`

<${f}>
<title>${Ai(d.basename)}</title>
<path>${d.path}</path>
<ctime>${h}</ctime>
<mtime>${g}</mtime>
<content>
${p}
</content>
</${f}>`}catch(p){z(`Error processing file ${d.path}:`,p),l+=`

<${f}_error>
<title>${Ai(d.basename)}</title>
<path>${d.path}</path>
<error>[Error: Could not process file]</error>
</${f}_error>`}},u=new Set;i&&s&&(await c(s,"active_note"),u.add(s.path));for(let d of o)u.has(d.path)||(await c(d),u.add(d.path));return l}async hasEmbeddedPDFs(e){return/!\[\[(.*?\.pdf)\]\]/g.test(e)}async addNoteToContext(e,n,r,o,i,s){if(r.some(c=>c.path===e.path))return;let a=await n.read(e),l=await this.hasEmbeddedPDFs(a);o&&e.path===o.path&&s(!0),i(c=>[...c,Object.assign(e,{wasAddedViaReference:!0,hasEmbeddedPDFs:l})])}processSelectedTextContexts(){let e=wm();if(!e||e.length===0)return"";let n="";for(let r of e)r.sourceType==="web"?n+=`

<${eee}>
<title>${Ai(r.title)}</title>
<url>${Ai(r.url)}</url>
<content>
${Ai(r.content)}
</content>
</${eee}>`:n+=`

<${bu}>
<title>${Ai(r.noteTitle)}</title>
<path>${Ai(r.notePath)}</path>
<start_line>${r.startLine.toString()}</start_line>
<end_line>${r.endLine.toString()}</end_line>
<content>
${r.content}
</content>
</${bu}>`;return n}async processContextWebTabs(e){if(!e||e.length===0)return"";let n=2500,r=8e3,o=15e3,i=2,s=(w,v)=>{let x=[`

<${w}>`,`
<title>${Ai(v.title)}</title>`,`
<url>${Ai(v.url)}</url>`];return v.mode&&x.push(`
<mode>${Ai(v.mode)}</mode>`),v.error?x.push(`
<error>${Ai(v.error)}</error>`):v.content!==void 0&&x.push(`
<content>
${Ai(v.content)}
</content>`),x.push(`
</${w}>`),x.join("")},a=w=>{let v=[`

<${oee}>`,`
<title>${Ai(w.title)}</title>`,`
<url>${Ai(w.url)}</url>`,`
<video_id>${Ai(w.videoId)}</video_id>`];w.isActive&&v.push(`
<is_active>true</is_active>`),w.channel&&v.push(`
<channel>${Ai(w.channel)}</channel>`),w.uploadDate&&v.push(`
<upload_date>${Ai(w.uploadDate)}</upload_date>`),w.duration&&v.push(`
<duration>${Ai(w.duration)}</duration>`),w.genre&&v.push(`
<genre>${Ai(w.genre)}</genre>`),w.description&&v.push(`
<description>${Ai(w.description)}</description>`),w.error&&v.push(`
<error>${Ai(w.error)}</error>`);let x=w.transcript||"No transcript available for this video";return v.push(`
<content>
${Ai(x)}
</content>`),v.push(`
</${oee}>`),v.join("")},l=null,c=[],u=new Set,d=new Set,f=ls(app),p=w=>{let v=f.getYouTubeVideoId(w);return v?d.has(v)?!0:(d.add(v),!1):u.has(w)?!0:(u.add(w),!1)};for(let w of e){let v=wc(w.url);v&&w.isActive&&!l&&(l={...w,url:v},p(v))}for(let w of e){let v=wc(w.url);!v||p(v)||c.push({...w,url:v})}if(!l&&c.length===0)return"";let m=f.getAvailability();if(!m.supported||!m.available){let w=m.reason??(m.supported?"Web Viewer is not available.":"Web Viewer is not supported on this platform."),v=[];l&&v.push(s(ZV,{title:l.title||"Unknown",url:l.url,error:w}));for(let x of c)v.push(s(ree,{title:x.title||"Unknown",url:x.url,error:w}));return v.join("")}let h=async(w,v)=>{try{let x=w.url,b=f.getYouTubeVideoId(x);if(b)return await g(w,b,v===ZV);let _=f.findLeafByUrl(x,{title:w.title});if(!_)return s(v,{title:w.title||"Unknown",url:x,error:"Web tab not found or closed"});let T=f.getPageInfo(_),S=_.view;if(!(S.webviewMounted===void 0||S.webviewFirstLoadFinished===void 0?!0:!!(S.webviewMounted&&S.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(_,n),T=f.getPageInfo(_)}catch(D){return ee(`Web tab content not loaded yet for ${x}:`,D),s(v,{title:T.title||w.title||"Untitled",url:T.url||x,mode:T.mode,error:"Web tab content not loaded yet"})}let A=new AbortController,O=window.setTimeout(()=>{A.abort()},r);try{let D=await f.getReaderModeMarkdown(_,{signal:A.signal});return T=f.getPageInfo(_),s(v,{title:T.title||w.title||"Untitled",url:T.url||x,mode:T.mode,content:D})}finally{window.clearTimeout(O)}}catch(x){return z(`Error processing web tab ${w.url}:`,x),s(v,{title:w.title||"Unknown",url:w.url,error:x instanceof M_?"Web tab content extraction timed out":"Could not process web tab"})}},g=async(w,v,x)=>{try{let b=null,_=w.url;for(let O of f.getLeaves()){let D=f.getPageInfo(O).url;if(f.getYouTubeVideoId(D)===v){b=O,_=D;break}}if(!b)return a({title:w.title||"YouTube Video",url:w.url,videoId:v,isActive:x,error:"Web tab not found or closed"});let T=b.view;if(!(T.webviewMounted===void 0||T.webviewFirstLoadFinished===void 0?!0:!!(T.webviewMounted&&T.webviewFirstLoadFinished)))try{await f.waitForWebviewReady(b,n)}catch(O){return ee(`YouTube tab content not loaded yet for ${_}:`,O),a({title:w.title||"YouTube Video",url:_,videoId:v,isActive:x,error:"Web tab content not loaded yet"})}let P=await f.getYouTubeTranscript(b,{timeoutMs:o}),A=P.transcript.length>0?P.transcript.map(O=>`${O.timestamp}: ${O.text}`).join(`
`):void 0;return a({title:P.title||w.title||"YouTube Video",url:_,videoId:P.videoId,channel:P.channel,description:P.description,uploadDate:P.uploadDate,duration:P.duration,genre:P.genre,transcript:A,isActive:x})}catch(b){return ee(`YouTube transcript extraction failed for ${w.url}:`,b),a({title:w.title||"YouTube Video",url:w.url,videoId:v,isActive:x,error:b instanceof Error?b.message:"Failed to extract video info"})}},y=[];if(l){let w=await h(l,ZV);y.push(w)}for(let w=0;w<c.length;w+=i){let v=c.slice(w,w+i),x=await Promise.all(v.map(b=>h(b,ree)));y.push(...x)}return y.join("")}};ye();Se();qe();var x0e=null;async function Ctn(){return x0e||(x0e=(await Promise.resolve().then(()=>(Tht(),Sht))).ContextCompactor),x0e.getInstance()}var KX=class t{constructor(){this.contextProcessor=HX.getInstance(),this.mention=tO.getInstance(),this.promptContextEngine=WX.getInstance()}static getInstance(){return t.instance||(t.instance=new t),t.instance}async processMessageContext(e,n,r,o,i,s,a,l,c=[],u){try{k(`[ContextManager] Processing context for message ${e.id}`);let d=e.originalMessage||e.message,{processedPrompt:f,includedFiles:p}=await Ij(d,"",r,s),{l2Context:m,l2Paths:h}=this.buildL2ContextFromPreviousTurns(e.id,a),g=e.context?.urls||[],y=o==="copilot_plus"?await this.mention.processUrlList(g):{urlContext:"",imageUrls:[]},w=new Set([...p.map(G=>G.path),...c.map(G=>G.path),...h]),v=new Set,b=(e.context?.notes||[]).filter(G=>!h.has(G.path));i&&o!=="project"&&s&&!w.has(s.path)&&!b.some(G=>G.path===s.path)&&b.push(s);let _=await this.contextProcessor.processContextNotes(w,n,r,b,i,s,o);b.forEach(G=>{w.add(G.path),v.add(G.path)});let T=e.context?.tags||[],S="",P=[];if(T.length>0){let J=$W(r,T).filter(M=>!w.has(M.path));J.length>0&&(S=await this.contextProcessor.processContextNotes(new Set,n,r,J,!1,null,o),J.forEach(M=>{w.add(M.path),v.add(M.path),P.push(M.path)}))}let A=e.context?.folders||[],O="",D=[];if(A.length>0){let J=A.flatMap(M=>JD(r,M)).filter(M=>!w.has(M.path));J.length>0&&(O=await this.contextProcessor.processContextNotes(new Set,n,r,J,!1,null,o),J.forEach(M=>{w.add(M.path),v.add(M.path),D.push(M.path)}))}let $=this.contextProcessor.processSelectedTextContexts(),B=e.context?.webTabs||[],W=await this.contextProcessor.processContextWebTabs(B),F=m+_+S+O+y.urlContext+$+W,Z=f+F,te=(o==="project"?1e6:q().autoCompactThreshold)*4,fe=!1,me=F;if(Z.length>te){u?.(Td.COMPACTING);let J=await(await Ctn()).compact(F);J.wasCompacted&&(me=J.content,Z=f+me,fe=!0,k(`[ContextManager] Compacted context: ${J.originalCharCount} -> ${J.compactedCharCount} chars`)),u?.(Td.DEFAULT)}k(`[ContextManager] Successfully processed context for message ${e.id}`);let j=fe?this.buildCompactedEnvelope({chainType:o,message:e,systemPrompt:l||"",processedUserMessage:f,compactedContext:me,compactedPaths:Array.from(v)}):this.buildPromptContextEnvelope({chainType:o,message:e,systemPrompt:l||"",processedUserMessage:f,l2PreviousContext:m,noteContextAddition:_,tagContextAddition:S,tagNotePaths:P,folderContextAddition:O,folderNotePaths:D,urlContext:y.urlContext,selectedText:$,webTabContext:W});return{processedContent:Z,contextEnvelope:j}}catch(d){return k(`[ContextManager] Error processing context for message ${e.id}:`,d),{processedContent:e.originalMessage||e.message,contextEnvelope:void 0}}}async reprocessMessageContext(e,n,r,o,i,s,a,l,c=[]){let u=n.getMessage(e);if(!u||u.sender!=="user"||!u.id)return;k(`[ContextManager] Reprocessing context for message ${e}`);let{processedContent:d,contextEnvelope:f}=await this.processMessageContext(u,r,o,i,s,a,n,l,c);n.updateProcessedText(u.id,d,f),k(`[ContextManager] Completed context reprocessing for message ${e}`)}buildL2ContextFromPreviousTurns(e,n){let r=n.getDisplayMessages(),o=r.findIndex(p=>p.id===e);if(o===-1||o===0)return{l2Context:"",l2Paths:new Set};let i=r.slice(0,o).filter(p=>p.sender==="user"),s=new Map,a=[],l=new Set,c=-1;for(let p=i.length-1;p>=0;p--)if(i[p].contextEnvelope?.layers?.find(y=>y.id==="L3_TURN")?.segments?.some(y=>y.metadata?.wasCompacted)){c=p;break}for(let p=0;p<i.length;p++){let h=i[p].contextEnvelope?.layers?.find(g=>g.id==="L3_TURN");if(h){if(p>=c){for(let g of h.segments||[])if(g.content){let y=this.compactSegmentForL2(g.content);if(!y.trim())continue;s.has(g.id)||a.push(g.id),s.set(g.id,y)}}for(let g of h.segments||[]){if(g.metadata?.notePath&&l.add(g.metadata.notePath),g.metadata?.compactedPaths)for(let y of g.metadata.compactedPaths)l.add(y);if(g.metadata?.notePaths)for(let y of g.metadata.notePaths)l.add(y)}}}let u=a.map(p=>s.get(p)).join(`
`);return{l2Context:/<prior_context\s+source=/.test(u)?u+`

`+Cht():u,l2Paths:l}}buildPromptContextEnvelope(e){let n=e.message.id;if(!n)return;let r={};if(e.systemPrompt&&(r.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.l2PreviousContext){let i=this.parseContextIntoSegments(e.l2PreviousContext,!0);i.length>0&&(r.L2_PREVIOUS=i)}let o=[];if(e.noteContextAddition){let i=this.parseContextIntoSegments(e.noteContextAddition,!1);o.push(...i)}return this.appendParsedSegments(o,e.tagContextAddition,{source:"tags",notePaths:e.tagNotePaths}),this.appendParsedSegments(o,e.folderContextAddition,{source:"folders",notePaths:e.folderNotePaths}),this.appendParsedSegments(o,e.urlContext),this.appendParsedSegments(o,e.selectedText),this.appendParsedSegments(o,e.webTabContext),o.length>0&&(r.L3_TURN=o),r.L5_USER=[{id:`${n}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:n,layerSegments:r,metadata:{debugLabel:`message:${n}`,chainType:e.chainType}})}buildCompactedEnvelope(e){let n=e.message.id;if(!n)return;let r={};return e.systemPrompt&&(r.L1_SYSTEM=[{id:"system",content:e.systemPrompt,stable:!0,metadata:{source:"system_prompt"}}]),e.compactedContext.trim()&&(r.L3_TURN=[{id:"compacted_context",content:e.compactedContext,stable:!1,metadata:{source:"compacted",wasCompacted:!0,compactedPaths:e.compactedPaths}}]),r.L5_USER=[{id:`${n}-user`,content:e.processedUserMessage,stable:!1,metadata:{source:"user_input"}}],this.promptContextEngine.buildEnvelope({conversationId:null,messageId:n,layerSegments:r,metadata:{debugLabel:`message:${n}:compacted`,chainType:e.chainType}})}parseContextIntoSegments(e,n){return _ht(e,n)}appendParsedSegments(e,n,r){let o=(n||"").trim();if(!o)return;let i=this.parseContextIntoSegments(o,!1);if(i.length>0)for(let s of i)r&&(s.metadata={...s.metadata,...r}),e.push(s);else e.push({id:`unparsed-${Date.now()}`,content:o,stable:!1,metadata:{source:"unparsed",...r}})}createMessageContext(e,n,r=wm()){return{notes:e,urls:n,selectedTextContexts:r}}async extractContextNotes(e,n,r=[]){return[...Df(e,n),...r].filter((a,l,c)=>c.findIndex(u=>u.path===a.path)===l)}needsContextReprocessing(e){return e.needsContextReprocessing===!0}getSelectedTextContexts(){return wm()}compactSegmentForL2(e){let n=[...SR.map(i=>i.tag),"prior_context","prior_context_note"].join("|"),r=new RegExp(`<(${n})(\\s[^>]*)?>[\\s\\S]*?</\\1>`,"g");return e.replace(r,(i,s)=>{let a=SR.find(l=>l.tag===s);return a&&!a.recoverable||s==="prior_context_note"?"":s==="prior_context"?i:a?bht(i,s):i}).trim()}};qe();ye();var R1=class{constructor(){this.messages=[]}generateId(){return`msg-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}addMessage(e,n,r,o,i){if(typeof e=="object"){let u=e,d=u.id||this.generateId(),f=u.timestamp||ll(new Date),p={id:d,displayText:u.message,processedText:u.originalMessage||u.message,sender:u.sender,timestamp:f,context:u.context,contextEnvelope:u.contextEnvelope,isVisible:u.isVisible!==!1,isErrorMessage:u.isErrorMessage,sources:u.sources,content:u.content,responseMetadata:u.responseMetadata};return this.messages.push(p),k(`[MessageRepository] Added message with ID: ${d}`),d}if(n===void 0||r===void 0)throw new Error("processedText and sender are required when using string-based addMessage");let s=e,a=this.generateId(),l=ll(new Date),c={id:a,displayText:s,processedText:n,sender:r,timestamp:l,context:o,contextEnvelope:void 0,isVisible:!0,isErrorMessage:!1,content:i};return this.messages.push(c),k(`[MessageRepository] Added message with ID: ${a}`),a}editMessage(e,n){let r=this.messages.find(o=>o.id===e);return r?r.displayText===n?(k(`[MessageRepository] No changes needed for message: ${e}`),!0):(r.displayText=n,r.sender==="user"||r.sender==="USER"?k(`[MessageRepository] Edited user message ${e}, needs context reprocessing`):(r.processedText=n,k(`[MessageRepository] Edited AI message ${e}`)),!0):(k(`[MessageRepository] Message not found for edit: ${e}`),!1)}updateProcessedText(e,n,r){let o=this.messages.find(i=>i.id===e);return o?(o.processedText=n,o.contextEnvelope=r,k(`[MessageRepository] Updated processed text for message ${e}`),!0):(k(`[MessageRepository] Message not found for processed text update: ${e}`),!1)}deleteMessage(e){let n=this.messages.findIndex(r=>r.id===e);return n===-1?(k(`[MessageRepository] Message not found for deletion: ${e}`),!1):(this.messages.splice(n,1),k(`[MessageRepository] Deleted message ${e}`),!0)}clear(){this.messages=[],k("[MessageRepository] Cleared all messages")}truncateAfter(e){this.messages=this.messages.slice(0,e+1),k(`[MessageRepository] Truncated messages after index ${e}`)}truncateAfterMessageId(e){let n=this.messages.findIndex(r=>r.id===e);n!==-1&&(this.messages=this.messages.slice(0,n+1),k(`[MessageRepository] Truncated messages after message ${e}`))}getDisplayMessages(){return this.messages.filter(e=>e.isVisible).map(e=>({id:e.id,message:e.displayText,originalMessage:e.displayText,sender:e.sender,timestamp:e.timestamp,isVisible:!0,context:e.context,contextEnvelope:e.contextEnvelope,isErrorMessage:e.isErrorMessage,sources:e.sources,content:e.content,responseMetadata:e.responseMetadata}))}getLLMMessage(e){let n=this.messages.find(r=>r.id===e);if(n)return{id:n.id,message:n.processedText,originalMessage:n.displayText,sender:n.sender,timestamp:n.timestamp,isVisible:!1,context:n.context,contextEnvelope:n.contextEnvelope,isErrorMessage:n.isErrorMessage,sources:n.sources,content:n.content,responseMetadata:n.responseMetadata}}getLLMMessages(){return this.messages.map(e=>({id:e.id,message:e.displayText,originalMessage:e.displayText,sender:e.sender,timestamp:e.timestamp,isVisible:!1,context:e.context,contextEnvelope:e.contextEnvelope,isErrorMessage:e.isErrorMessage,sources:e.sources,content:e.content}))}getMessage(e){let n=this.messages.find(r=>r.id===e);if(n)return{id:n.id,message:n.displayText,originalMessage:n.displayText,sender:n.sender,timestamp:n.timestamp,isVisible:n.isVisible,context:n.context,contextEnvelope:n.contextEnvelope,isErrorMessage:n.isErrorMessage,sources:n.sources,content:n.content}}loadMessages(e){this.clear(),e.forEach(n=>{this.messages.push({id:n.id||this.generateId(),displayText:n.message,processedText:n.originalMessage||n.message,sender:n.sender,timestamp:n.timestamp||ll(new Date),context:n.context,contextEnvelope:n.contextEnvelope,isVisible:n.isVisible!==!1,isErrorMessage:n.isErrorMessage,sources:n.sources,content:n.content})}),k(`[MessageRepository] Loaded ${e.length} messages`)}getDebugInfo(){return{totalMessages:this.messages.length,visibleMessages:this.messages.filter(e=>e.isVisible).length,userMessages:this.messages.filter(e=>e.sender==="user"||e.sender==="USER").length,aiMessages:this.messages.filter(e=>e.sender==="AI"||e.sender==="assistant").length}}};Ir();It();ye();Se();qe();av();var ol=require("obsidian"),b0e=100;function qX(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}var bV=class{constructor(e,n,r){this.app=e;this.messageRepo=n;this.chainManager=r}async saveChat(e){try{let n=this.messageRepo.getDisplayMessages();if(n.length===0){new ol.Notice("No messages to save.");return}let r=q(),o=this.formatChatContent(n),i=n[0].timestamp?.epoch||Date.now();await Fr(r.defaultSaveFolder);let s=await this.findFileByEpoch(i),a=s?this.app.metadataCache.getFileCache(s)?.frontmatter:void 0,l=a?.topic,c=a?.lastAccessedAt;if(s&&!a)try{let h=await oy(this.app,s.path);h&&(h.topic&&(l=h.topic),h.lastAccessedAt&&(c=Number(h.lastAccessedAt)))}catch{}let u=br(),d=s?s.path:this.generateFileName(u,n,i,l),f=this.generateNoteContent(o,i,e,l,c),p=s,m=s!=null&&P0(this.app,s.path);if(s&&m)await this.app.vault.modify(s,f),k(`[ChatPersistenceManager] Updated existing chat file: ${s.path}`);else if(!P0(this.app,d)&&await this.app.vault.adapter.exists(d)){let h=await this.resolveChatSavePath(d,u);await this.app.vault.adapter.write(h,f),h!==d?(new ol.Notice(`Chat saved as note: ${h}`),ee(`[ChatPersistenceManager] Avoided cross-project overwrite in hidden folder. Created: ${h}`)):(new ol.Notice("Existing chat note found - updating it now."),k(`[ChatPersistenceManager] Updated existing chat file via adapter: ${d}`))}else try{p=await this.app.vault.create(d,f),new ol.Notice(`Chat saved as note: ${d}`),k(`[ChatPersistenceManager] Created new chat file: ${d}`)}catch(h){if(this.isFileAlreadyExistsError(h)){let g=this.app.vault.getAbstractFileByPath(d);if(g&&g instanceof ol.TFile){let y=this.app.metadataCache.getFileCache(g)?.frontmatter,w=y?.projectId,v=u?.id;if(v&&w!==v){let x=`${r.defaultSaveFolder}/${Xc(v)}__chat-${i}.md`,b=await this.resolveChatSavePath(x,u);p=await this.app.vault.create(b,f),new ol.Notice(`Chat saved as note: ${b}`),ee(`[ChatPersistenceManager] Avoided cross-project overwrite. Created: ${b}`)}else{l=y?.topic??l;let x=y?.lastAccessedAt,b=this.generateNoteContent(o,i,e,l,x);await this.app.vault.modify(g,b),p=g,new ol.Notice("Existing chat note found - updating it now."),k(`[ChatPersistenceManager] Resolved save conflict by updating existing chat file: ${g.path}`)}}else{let y=await this.resolveChatSavePath(d,u);await this.app.vault.adapter.write(y,f),y!==d?(new ol.Notice(`Chat saved as note: ${y}`),ee(`[ChatPersistenceManager] Avoided cross-project overwrite via adapter. Created: ${y}`)):(new ol.Notice("Existing chat note found - updating it now."),k(`[ChatPersistenceManager] Resolved save conflict via adapter: ${d}`))}}else if(this.isNameTooLongError(h)){let g=br(),y=g?`${Xc(g.id)}__`:"",w=`${r.defaultSaveFolder}/${y}chat-${i}.md`,v=await this.resolveChatSavePath(w,u);try{p=await this.app.vault.create(v,f),new ol.Notice(`Chat saved as note: ${v}`),ee(`[ChatPersistenceManager] Used minimal filename due to length constraints: ${v}`)}catch(x){if(this.isFileAlreadyExistsError(x)){let b=this.app.vault.getAbstractFileByPath(v);if(b&&b instanceof ol.TFile){let _=this.app.metadataCache.getFileCache(b)?.frontmatter,T=_?.lastAccessedAt,S=_?.topic,P=this.generateNoteContent(o,i,e,S,T);await this.app.vault.modify(b,P),p=b,new ol.Notice("Existing chat note found - updating it now."),k(`[ChatPersistenceManager] Resolved fallback save conflict by updating existing chat file: ${b.path}`)}else await this.app.vault.adapter.write(v,f),new ol.Notice("Existing chat note found - updating it now."),k(`[ChatPersistenceManager] Resolved fallback save conflict via adapter: ${v}`)}else throw x}}else throw h}this.generateTopicAsyncIfNeeded(u,p,n,l)}catch(n){z("[ChatPersistenceManager] Error saving chat:",n),new ol.Notice("Failed to save chat as note. Check console for details.")}}async loadChat(e){try{let n;try{n=await this.app.vault.read(e)}catch{n=await this.app.vault.adapter.read(e.path)}let r=this.parseChatContent(n);return k(`[ChatPersistenceManager] Loaded ${r.length} messages from ${e.path}`),r}catch(n){return z("[ChatPersistenceManager] Error loading chat:",n),new ol.Notice("Failed to load chat history. Check console for details."),[]}}async resolveChatSavePath(e,n){if(!await this.app.vault.adapter.exists(e))return e;let r=n?.id;if(!r||await fht(this.app,e)===r)return e;let i=e.replace(/\.md$/i,""),s=2,a=`${i}-${s}.md`;for(;await this.app.vault.adapter.exists(a);)s++,a=`${i}-${s}.md`;return a}async getChatHistoryFiles(){let e=q(),n=await dB(this.app,e.defaultSaveFolder);if(n.length===0)return[];let r=br();return BX(this.app,n,r?.id)}formatChatContent(e){return e.map(n=>{let r=n.timestamp?n.timestamp.display:"Unknown time",o=n.message;if(n.sender===Sd){let s=tj(o);s&&(o=s.contentAfter)}let i=`**${n.sender}**: ${o}`;if(n.context){let s=[];n.context.notes?.length&&s.push(`Notes: ${n.context.notes.map(a=>a.path).join(", ")}`),n.context.urls?.length&&s.push(`URLs: ${n.context.urls.join(", ")}`),n.context.webTabs?.length&&s.push(`Web Tabs: ${n.context.webTabs.map(a=>a.url).join(", ")}`),n.context.tags?.length&&s.push(`Tags: ${n.context.tags.join(", ")}`),n.context.folders?.length&&s.push(`Folders: ${n.context.folders.join(", ")}`),s.length>0&&(i+=`
[Context: ${s.join(" | ")}]`)}return i+=`
[Timestamp: ${r}]`,i}).join(`

`)}parseChatContent(e){let n=[],r=e.match(/^---\n([\s\S]*?)\n---/),o=e;r&&(o=e.slice(r[0].length).trim());let i=/\*\*(user|ai)\*\*: ([\s\S]*?)(?=(?:\n\*\*(?:user|ai)\*\*: )|$)/g,s;for(;(s=i.exec(o))!==null;){let a=s[1]==="user"?uo:Sd,l=s[2].trim(),c=l.split(`
`),u=l,d="Unknown time",f,p=c.length;if(c[p-1]?.startsWith("[Timestamp: ")){let h=c[p-1].match(/\[Timestamp: (.*?)\]/);h&&(d=h[1],p--)}if(p>0&&c[p-1]?.startsWith("[Context: ")){let h=c[p-1].match(/\[Context: (.*?)\]/);if(h){let g=h[1];f=this.parseContextString(g),p--}}if(u=c.slice(0,p).join(`
`).trim(),a===Sd){u=u.replace(/<!--TOOL_CALL_START:[^:]+:[^:]+:[^:]+:[^:]+:[^:]*:[^:]+-->[\s\S]*?<!--TOOL_CALL_END:[^:]+:[\s\S]*?-->/g,"");let h=tj(u);h&&(u=h.contentAfter),u=u.replace(/\n{3,}/g,`

`).trim()}let m;if(d!=="Unknown time"){let h=new Date(d);isNaN(h.getTime())||(m=h.getTime())}n.push({message:u,sender:a,isVisible:!0,timestamp:m?{epoch:m,display:d,fileName:""}:null,context:f})}return n}parseContextString(e){let n={notes:[],urls:[],tags:[],folders:[],webTabs:[]},r=e.split(" | ");for(let o of r){let i=o.trim();if(i.startsWith("Notes: ")){let s=i.substring(7);s&&(n.notes=s.split(", ").map(a=>{let l=a.trim(),c=this.app.vault.getAbstractFileByPath(l);if(c instanceof ol.TFile)return c;let u=l.includes("/")?l.split("/").pop():l,d=this.app.vault.getMarkdownFiles().filter(f=>f.basename===u);return d.length===1?(k(`[ChatPersistenceManager] Resolved legacy basename "${u}" to ${d[0].path}`),d[0]):(d.length>1?ee(`[ChatPersistenceManager] Ambiguous basename "${u}", skipping. Matches: ${d.map(f=>f.path).join(", ")}`):ee(`[ChatPersistenceManager] Note not found: ${l}`),null)}).filter(a=>a!==null))}else if(i.startsWith("URLs: ")){let s=i.substring(6);s&&(n.urls=s.split(", ").map(a=>a.trim()))}else if(i.startsWith("Web Tabs: ")||i.startsWith("WebTabs: ")){let s=i.startsWith("Web Tabs: ")?i.substring(10):i.substring(9);s&&(n.webTabs=s.split(", ").map(a=>a.trim()).filter(a=>a.length>0).map(a=>({url:a})))}else if(i.startsWith("Tags: ")){let s=i.substring(6);s&&(n.tags=s.split(", ").map(a=>a.trim()))}else if(i.startsWith("Folders: ")){let s=i.substring(9);s&&(n.folders=s.split(", ").map(a=>a.trim()))}}if(n.notes.length>0||n.urls.length>0||(n.tags?.length??0)>0||(n.folders?.length??0)>0||(n.webTabs?.length??0)>0)return n}async findFileByEpoch(e){let n=await this.getChatHistoryFiles();for(let r of n){let o=this.app.metadataCache.getFileCache(r)?.frontmatter?.epoch;if(o===void 0)try{let s=await oy(this.app,r.path);s?.epoch&&(o=Number(s.epoch))}catch{continue}let i=typeof o=="number"?o:typeof o=="string"?Number(o):void 0;if(typeof i=="number"&&!Number.isNaN(i)&&i===e)return r}return null}async generateAITopic(e){if(this.chainManager)try{let n=this.chainManager.chatModelManager.getChatModel();if(!n)return;let r=6,o=200,s=`Generate a concise title (max 5 words) for this conversation based on its content. Return only the title without any explanation or quotes.

Conversation:
${e.reduce((u,d,f)=>f>=r?u:u+(u?`
`:"")+`${d.sender}: ${d.message.slice(0,o)}`,"")}`,a=await n.invoke(s),l=typeof a=="string"?a:a.content??a.text??a;return Kx(l).trim().replace(/^["']|["']$/g,"").replace(/[\\/:*?"<>|]/g,"").slice(0,50)||void 0}catch(n){z("[ChatPersistenceManager] Error generating AI topic:",n);return}}generateFileName(e,n,r,o){let i=q(),a=ll(new Date(r)).fileName,l;if(o)l=o;else{let b=n.find(_=>_.sender===uo);l=b&&b.message.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"").split(/\s+/).slice(0,10).join(" ").replace(/[\\/:*?"<>|\x00-\x1F]/g,"").trim()||"Untitled Chat"}let c=i.defaultConversationNoteName||"{$date}_{$time}__{$topic}",u=e===void 0?br():e,d=u?`${Xc(u.id)}__`:"",f=WS(".md"),p=WS(d),m=c.replace("{$topic}","").replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]),h=WS(m),g=Math.max(20,b0e-f-p-h),y=l.replace(/\s+/g,"_"),w=ZD(y,g);c=c.replace("{$topic}",w).replace("{$date}",a.split("_")[0]).replace("{$time}",a.split("_")[1]);let v=c.replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/[{}[\]]/g,"_").replace(/[\\/:*?"<>|\x00-\x1F]/g,"_"),x=`${d}${v}.md`;if(WS(x)>b0e){let b=b0e-f-p,_=ZD(v,b);return`${i.defaultSaveFolder}/${d}${_}.md`}return`${i.defaultSaveFolder}/${x}`}generateNoteContent(e,n,r,o,i){let s=q(),a=br();return`---
epoch: ${n}
modelKey: "${qX(r)}"
${o?`topic: "${qX(o)}"`:""}
${i?`lastAccessedAt: ${i}`:""}
${a?`projectId: "${qX(a.id)}"`:""}
${a?`projectName: "${qX(a.name)}"`:""}
tags:
  - ${s.defaultConversationTag}
---

${e}`}generateTopicAsyncIfNeeded(e,n,r,o){!q().generateAIChatTitleOnSave||!n||o||(async()=>{try{let s=await this.generateAITopic(r);if(!s)return;await this.applyTopicToFrontmatter(n,s),await this.renameFileToMatchTopic(e,n,s)}catch(s){z("[ChatPersistenceManager] Error during async topic generation:",s)}})()}async applyTopicToFrontmatter(e,n){try{await LC(this.app,e.path,{topic:n.trim()}),k(`[ChatPersistenceManager] Applied AI topic to chat file: ${e.path}`)}catch(r){z("[ChatPersistenceManager] Error applying AI topic to file:",r)}}errorToMessage(e){return e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e)}isNameTooLongError(e){if(!e)return!1;let n=this.errorToMessage(e).toLowerCase();return n.includes("enametoolong")||n.includes("name too long")}isFileAlreadyExistsError(e){return e?this.errorToMessage(e).toLowerCase().includes("already exists"):!1}async renameFileToMatchTopic(e,n,r){if(!n||!r)return;let o,i=this.app.metadataCache.getFileCache(n);if(i?.frontmatter?.epoch)o=i.frontmatter.epoch;else try{let l=await oy(this.app,n.path);l?.epoch&&(o=Number(l.epoch))}catch{}if(!o)return;let s=this.messageRepo.getDisplayMessages(),a=this.generateFileName(e,s,o,r);n.path!==a&&await this.app.fileManager.renameFile(n,a)}};It();FP();fL();var GX=class{constructor(e,n,r,o){this.messageRepo=e;this.chainManager=n;this.fileParserManager=r;this.plugin=o;this.projectMessageRepos=new Map;this.defaultProjectKey="defaultProjectKey";this.lastKnownProjectId=null;this.contextManager=KX.getInstance(),this.projectMessageRepos.set(this.defaultProjectKey,e),this.persistenceManager=new bV(o.app,e,n)}getCurrentMessageRepo(){let e=this.plugin.projectManager.getCurrentProjectId(),n=e??this.defaultProjectKey;if(this.lastKnownProjectId!==e&&(k(`[ChatManager] Project changed from ${this.lastKnownProjectId} to ${e}`),this.lastKnownProjectId=e),!this.projectMessageRepos.has(n)){k(`[ChatManager] Creating new message repository for project: ${n}`);let o=new R1;this.projectMessageRepos.set(n,o)}let r=this.projectMessageRepos.get(n);return this.persistenceManager=new bV(this.plugin.app,r,this.chainManager),r}setOnMessageCreatedCallback(e){this.onMessageCreatedCallback=e}async processSystemPromptTemplates(e,n,r){if(!e.includes("{")||!e.includes("}"))return{processedPrompt:e,includedFiles:[]};if(!q().enableCustomPromptTemplating)return{processedPrompt:e,includedFiles:[]};try{let i=await Ij(e,"",n,r,!0);return{processedPrompt:i.processedPrompt.trimEnd(),includedFiles:i.includedFiles}}catch(i){return ee("[ChatManager] Error processing system prompt templates:",i),{processedPrompt:e,includedFiles:[]}}}injectProcessedUserCustomPromptIntoSystemPrompt(e){let{systemPromptWithoutMemory:n,userCustomPrompt:r,processedUserCustomPrompt:o}=e,i=/<user_custom_instructions>\n[\s\S]*?\n<\/user_custom_instructions>/;return i.test(n)?n.replace(i,()=>`<user_custom_instructions>
${o}
</user_custom_instructions>`):n===r?o:(k("[ChatManager] Could not locate <user_custom_instructions> block for injection; returning original system prompt."),n)}replaceSystemPromptWithoutMemoryInBasePrompt(e){let{basePromptWithMemory:n,systemPromptWithoutMemory:r,processedSystemPromptWithoutMemory:o}=e;return n.endsWith(r)?`${n.slice(0,n.length-r.length)}${o}`:(k("[ChatManager] basePromptWithMemory does not end with systemPromptWithoutMemory; returning original base prompt."),n)}async getSystemPromptForMessage(e,n,r){let o=K8(),i=[],s=await xv(this.chainManager.userMemoryManager),a=r_(),l=s;if(o){let c=await this.processSystemPromptTemplates(o,n,r),u=this.injectProcessedUserCustomPromptIntoSystemPrompt({systemPromptWithoutMemory:a,userCustomPrompt:o,processedUserCustomPrompt:c.processedPrompt}),d=this.replaceSystemPromptWithoutMemoryInBasePrompt({basePromptWithMemory:s,systemPromptWithoutMemory:a,processedSystemPromptWithoutMemory:u});d!==s&&i.push(...c.includedFiles),l=d}if(e==="project"){let c=br();if(c){let u=await Sl.instance.getProjectContext(c.id),d=await this.processSystemPromptTemplates(c.systemPrompt,n,r);i.push(...d.includedFiles);let f=`${l}

<project_system_prompt>
${d.processedPrompt}
</project_system_prompt>`;if(u){let m=u;u.length>24e5&&(m=u.substring(0,24e5),ee(`Project context truncated from ${Math.round(u.length/4e3)}k to ${Math.round(24e5/4e3)}k estimated tokens to stay within token budget`)),f+=`

<project_context>
${m}
</project_context>`}return{processedPrompt:f,includedFiles:i}}}return{processedPrompt:l,includedFiles:i}}buildWebTabsWithActiveSnapshot(e,n){let r=Grt(e);if(!n)return r;try{let s=ls(this.plugin.app).getActiveWebTabState().activeWebTabForMentions,a=dL(s?.url);if(!a)return r;let l=r.map(u=>{if(u.isActive){let{isActive:d,...f}=u;return f}return u}),c=l.findIndex(u=>dL(u.url)===a);if(c>=0){let u=l[c];return l[c]={...u,url:wc(s?.url)??u.url,title:s?.title??u.title,faviconUrl:s?.faviconUrl??u.faviconUrl,isActive:!0},l}return[...l,{url:wc(s?.url)??a,title:s?.title,faviconUrl:s?.faviconUrl,isActive:!0}]}catch(o){return ee("[ChatManager] Failed to resolve active web tab:",o),r}}async sendMessage(e,n,r,o=!1,i=!1,s,a){try{k(`[ChatManager] Sending message: "${e}"`);let l=this.plugin.app.workspace.getActiveFile(),c={...n};if(o&&l){let v=n.notes||[],x=v.some(b=>b.path===l.path);c.notes=x?v:[...v,l]}let d=!((c.selectedTextContexts||[]).length>0)&&(i||e.includes(lD));c.webTabs=this.buildWebTabsWithActiveSnapshot(c.webTabs||[],d);let f=this.getCurrentMessageRepo(),p=f.addMessage(e,e,uo,c,s);this.onMessageCreatedCallback&&this.onMessageCreatedCallback(p);let m=f.getMessage(p);if(!m)throw new Error(`Failed to retrieve message ${p}`);let{processedPrompt:h,includedFiles:g}=await this.getSystemPromptForMessage(r,this.plugin.app.vault,l),{processedContent:y,contextEnvelope:w}=await this.contextManager.processMessageContext(m,this.fileParserManager,this.plugin.app.vault,r,o,l,f,h,g,a);return f.updateProcessedText(p,y,w),k(`[ChatManager] Successfully sent message ${p}`),p}catch(l){throw k("[ChatManager] Error sending message:",l),l}}async editMessage(e,n,r,o=!1){try{k(`[ChatManager] Editing message ${e}: "${n}"`);let i=this.getCurrentMessageRepo();if(!i.editMessage(e,n))return!1;let a=this.plugin.app.workspace.getActiveFile(),{processedPrompt:l,includedFiles:c}=await this.getSystemPromptForMessage(r,this.plugin.app.vault,a);return await this.contextManager.reprocessMessageContext(e,i,this.fileParserManager,this.plugin.app.vault,r,o,a,l,c),await this.updateChainMemory(),k(`[ChatManager] Successfully edited message ${e}`),!0}catch(i){return k(`[ChatManager] Error editing message ${e}:`,i),!1}}async regenerateMessage(e,n,r,o){try{k(`[ChatManager] Regenerating message ${e}`);let i=this.getCurrentMessageRepo();if(!i.getMessage(e))return k(`[ChatManager] Message not found: ${e}`),!1;let a=i.getDisplayMessages(),l=a.findIndex(f=>f.id===e);if(l<=0)return k("[ChatManager] Cannot regenerate first message or no user message found"),!1;let c=a[l-1];if(c.sender!==uo)return k("[ChatManager] Previous message is not from user"),!1;if(i.truncateAfter(l-1),o&&o(),await this.updateChainMemory(),!c.id)return k("[ChatManager] User message has no ID for regeneration"),!1;let u=i.getLLMMessage(c.id);if(!u)return k("[ChatManager] LLM message not found for regeneration"),!1;if(!u.contextEnvelope){k("[ChatManager] Context envelope missing, reprocessing context for regeneration");let f=ym(),p=this.plugin.app.workspace.getActiveFile(),{processedPrompt:m,includedFiles:h}=await this.getSystemPromptForMessage(f,this.plugin.app.vault,p);await this.contextManager.reprocessMessageContext(c.id,i,this.fileParserManager,this.plugin.app.vault,f,!1,p,m,h),u=i.getLLMMessage(c.id)}let d=new AbortController;return await this.chainManager.runChain(u,d,n,r,{debug:q().debug}),k(`[ChatManager] Successfully regenerated message ${e}`),!0}catch(i){return k(`[ChatManager] Error regenerating message ${e}:`,i),!1}}async deleteMessage(e){try{return k(`[ChatManager] Deleting message ${e}`),this.getCurrentMessageRepo().deleteMessage(e)?(await this.updateChainMemory(),k(`[ChatManager] Successfully deleted message ${e}`),!0):!1}catch(n){return k(`[ChatManager] Error deleting message ${e}:`,n),!1}}addMessage(e){return this.getCurrentMessageRepo().addMessage(e)}clearMessages(){this.getCurrentMessageRepo().clear(),this.chainManager.memoryManager.clearChatMemory().catch(n=>z("clearChatMemory failed",n)),k("[ChatManager] Cleared all messages")}async truncateAfterMessageId(e){this.getCurrentMessageRepo().truncateAfterMessageId(e),await this.updateChainMemory(),k(`[ChatManager] Truncated messages after ${e}`)}getDisplayMessages(){return this.getCurrentMessageRepo().getDisplayMessages()}getLLMMessages(){return this.getCurrentMessageRepo().getLLMMessages()}getMessage(e){return this.getCurrentMessageRepo().getMessage(e)}getLLMMessage(e){return this.getCurrentMessageRepo().getLLMMessage(e)}async updateChainMemory(){try{let n=this.getCurrentMessageRepo().getLLMMessages();await wht(n,this.chainManager.memoryManager),k(`[ChatManager] Updated chain memory with ${n.length} messages`)}catch(e){k("[ChatManager] Error updating chain memory:",e)}}async loadMessages(e){let n=this.getCurrentMessageRepo();n.clear(),e.forEach(r=>{n.addMessage(r)}),await this.updateChainMemory(),k(`[ChatManager] Loaded ${e.length} messages`)}async saveChat(e){await this.persistenceManager.saveChat(e)}getDebugInfo(){return{...this.getCurrentMessageRepo().getDebugInfo(),currentProject:this.plugin.projectManager.getCurrentProjectId(),totalProjects:this.projectMessageRepos.size}}async handleProjectSwitch(){let e=this.plugin.projectManager.getCurrentProjectId();k(`[ChatManager] Handling project switch to: ${e}`),this.lastKnownProjectId=null;let n=this.getCurrentMessageRepo();await this.updateChainMemory(),k(`[ChatManager] Project switch complete. Messages: ${n.getDisplayMessages().length}`)}async loadChatHistory(e){this.clearMessages();let n=await this.persistenceManager.loadChat(e),r=this.getCurrentMessageRepo();for(let o of n)r.addMessage(o);await this.updateChainMemory(),k(`[ChatManager] Loaded ${n.length} messages from chat history`)}};ye();HS();var Eht=require("obsidian");Se();Su();It();Su();var Uy=["apiKey"],Pht=Object.freeze(Object.keys(Hn).filter(Mx));function CS(t){for(let e of Object.keys(t)){if(!Mx(e))continue;let n=t[e];if(typeof n=="string"&&n.length>0)return!0}for(let e of["activeModels","activeEmbeddingModels"]){let n=t[e];if(Array.isArray(n))for(let r of n){if(!r||typeof r!="object")continue;let o=r;for(let i of Uy){let s=o[i];if(typeof s=="string"&&s.length>0)return!0}}}return!1}function EE(t){let e={...t};for(let n of Object.keys(e))Mx(n)&&(e[n]="");return e.activeModels=Iht(t.activeModels??[]),e.activeEmbeddingModels=Iht(t.activeEmbeddingModels??[]),e}function Iht(t){return t?.length?t.map(e=>{let n={...e};for(let r of Uy)n[r]="";return n}):t}function AE(t){let e={...t};return delete e.enableEncryption,delete e._keychainMigrated,delete e._keychainMigratedAt,delete e._migrationModalDismissed,e._diskSecretsCleared!==void 0&&e._keychainOnly===void 0&&(e._keychainOnly=e._diskSecretsCleared),delete e._diskSecretsCleared,e}function By(t){return t._keychainOnly===!0}var ZX=require("obsidian");TC();var _tn=[];function L1(t){return Mx(t)||_tn.includes(t)}function Stn(t){let e=Ttn(t);if(e)return Jc(e).slice(0,8);let n=window.crypto;if(typeof n?.getRandomValues=="function"){let r=new Uint8Array(4);return n.getRandomValues(r),Array.from(r,o=>o.toString(16).padStart(2,"0")).join("")}return Jc(`${Date.now()}-${Math.random()}`).slice(0,8)}function Ttn(t){let e=t.vault.adapter;if(e instanceof Eht.FileSystemAdapter)return e.getBasePath();let n=e;if(typeof n.getBasePath=="function")return n.getBasePath();if(typeof n.basePath=="string")return n.basePath}var JX=64;function Itn(t,e=JX){let n=t.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,""),r=Jc(t).slice(0,8),o=Math.max(0,e-9);return n.slice(0,o)+"-"+r}function C0e(t,e){let n=`copilot-v${t}-`,r=e.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),o=n+r;if(o.length<=JX)return o;let i=Jc(e).slice(0,8);return o.slice(0,JX-9)+"-"+i}function YX(t,e,n,r){let i=`model-${r.replace(/([A-Z])/g,"-$1").toLowerCase()}`,s=`copilot-v${t}-${i}-${e}-`,a=JX-s.length,l=Itn(n,a);return s+l}var _S=class _S{constructor(e){this.app=e,this.vaultId=Stn(e)}static getInstance(e){if(!_S.instance){if(!e)throw new Error("KeychainService must be initialized with app on first call");_S.instance=new _S(e)}return _S.instance}static resetInstance(){_S.instance=null}isAvailable(){return!!this.app.secretStorage}getVaultId(){return this.vaultId}setVaultId(e){this.vaultId=e}get storage(){if(!this.app.secretStorage)throw new Error("OS keychain (SecretStorage) is not available.");return this.app.secretStorage}removeSecret(e){typeof this.storage.deleteSecret=="function"?this.storage.deleteSecret(e):this.storage.setSecret(e,"")}setSecretById(e,n){this.storage.setSecret(e,n)}deleteSecretById(e){this.removeSecret(e)}setSecret(e,n){let r=C0e(this.vaultId,e);this.storage.setSecret(r,n)}getSecret(e){let n=C0e(this.vaultId,e);return this.storage.getSecret(n)}setModelSecret(e,n,r,o){let i=YX(this.vaultId,e,n,r);this.storage.setSecret(i,o)}getModelSecret(e,n,r){let o=YX(this.vaultId,e,n,r);return this.storage.getSecret(o)}async hydrateFromKeychain(e){let n={...e},r=!1,o=new Set([...Pht,...Object.keys(n).filter(a=>L1(a))]);for(let a of o){let l;try{l=this.getSecret(a)}catch(c){console.warn(`Keychain read failed for "${a}".`,c),r=!0;continue}l===""?n[a]="":l!==null&&(n[a]=l)}let i=await this.hydrateModelSecrets("chat",n.activeModels??[]);n.activeModels=i.models,r=r||i.hadFailures;let s=await this.hydrateModelSecrets("embedding",n.activeEmbeddingModels??[]);return n.activeEmbeddingModels=s.models,r=r||s.hadFailures,r&&console.warn("Keychain hydrate: some keychain reads failed \u2014 values left as-is."),{settings:n,hadFailures:r}}persistSecrets(e,n){let r=[],o=[];for(let s of Object.keys(e)){if(!L1(s))continue;let a=e[s],l=C0e(this.vaultId,s);if(typeof a=="string"&&a.length>0)r.push([l,a]);else if(n){let c=n[s];typeof c=="string"&&c.length>0&&o.push(l)}}this.collectModelSecrets("chat",e.activeModels,r,n?.activeModels,o),this.collectModelSecrets("embedding",e.activeEmbeddingModels,r,n?.activeEmbeddingModels,o);let i=[...this.getDeletedModelKeysForScope("chat",n?.activeModels,e.activeModels),...this.getDeletedModelKeysForScope("embedding",n?.activeEmbeddingModels,e.activeEmbeddingModels),...o];return{secretEntries:r,keychainIdsToDelete:i}}clearAllVaultSecrets(){let e=`copilot-v${this.vaultId}-`;if(typeof this.storage.listSecrets!="function")throw new Error("Obsidian Keychain on this build does not support listing entries; cannot guarantee a complete clear.");let n=this.storage.listSecrets(),r=[];for(let o of n)if(o.startsWith(e))try{this.removeSecret(o)}catch{r.push(o)}if(r.length>0)throw new Error(`Failed to clear ${r.length} keychain entr${r.length===1?"y":"ies"}. Please retry.`)}async forgetAllSecrets(e,n,r,o){let i=q();if(By(i)&&!this.isAvailable())throw new Error("Cannot delete API keys from the Obsidian Keychain because Secure Storage is unavailable in this Obsidian build. Update Obsidian to 1.11.4 or later, or open this vault on a device with Keychain access, then try again.");if(this.isAvailable()&&typeof this.app.secretStorage?.listSecrets!="function")throw new Error("Cannot delete all API keys because this Obsidian build does not support enumerating Keychain entries. Update Obsidian to a newer version and retry.");let s=EE(i);this.isAvailable()&&(s._keychainOnly=!0);let a=AE(s);try{await e(a),n(a)}catch(c){console.error("forgetAllSecrets: saveData failed \u2014 aborting keychain clear",c),o&&o(),new ZX.Notice("Failed to remove API keys from data.json. Obsidian Keychain was NOT cleared. Please try again.");return}let l;if(this.isAvailable())try{this.clearAllVaultSecrets()}catch(c){l=c instanceof Error?c:new Error(String(c))}if(r(s),l)throw new ZX.Notice("Some Obsidian Keychain entries could not be removed. Your keys have been cleared from data.json and memory. Please restart and retry."),l;new ZX.Notice("All API keys for this vault removed. Please re-enter them.")}async hydrateModelSecrets(e,n){if(!n?.length)return{models:n,hadFailures:!1};let r=!1,o=[];for(let i of n){let s=ln(i),a={...i};for(let l of Uy){let c;try{c=this.getModelSecret(e,s,l)}catch(u){console.warn(`Keychain read failed for model "${s}" field "${l}".`,u),r=!0;continue}c===""?a[l]="":c!==null&&(a[l]=c)}o.push(a)}return{models:o,hadFailures:r}}collectModelSecrets(e,n,r,o,i){if(!n?.length)return;let s=new Map;if(o)for(let a of o)s.set(ln(a),a);for(let a of n){let l=ln(a),c=s.get(l);for(let u of Uy){let d=a[u],f=YX(this.vaultId,e,l,u);if(typeof d=="string"&&d.length>0)r.push([f,d]);else if(c&&i){let p=c[u];typeof p=="string"&&p.length>0&&i.push(f)}}}}getDeletedModelKeysForScope(e,n,r){if(!n?.length)return[];let o=new Set((r??[]).map(ln));return n.filter(i=>!o.has(ln(i))).flatMap(i=>{let s=ln(i);return Uy.flatMap(a=>{let l=i[a];return typeof l!="string"||l.length===0?[]:[YX(this.vaultId,e,s,a)]})})}};_S.instance=null;var vd=_S;Se();Su();ye();var S0e=require("obsidian"),$1=Promise.resolve(),kE=!1,Bh,XX=!1,QX=0,CV=new Set,D1=!1,Ptn=/^[a-f0-9]{8}$/;function Etn(t){return typeof t=="string"&&Ptn.test(t)}function _V(t){kE=CS(t)}function Nht(){$1=Promise.resolve(),kE=!1,Bh=void 0,XX=!1,QX=0,CV.clear(),D1=!1}function Oht(t){Bh=structuredClone(t)}function eQ(){XX=!0}function Rht(){return kE}function T0e(t){return!vd.getInstance().isAvailable()||D1||By(t)?!1:kE||CS(t)}async function I0e(t){let e=$1.then(async()=>{try{await t()}finally{QX++}});return $1=e.catch(()=>{}),e}async function Lht(){await $1}async function Aht(t){let e=structuredClone(t),n=e;for(let r of Object.keys(n)){if(!L1(r))continue;let o=n[r];if(typeof o!="string"||o.length===0)continue;let i=await pn(o);i&&(n[r]=i)}for(let r of["activeModels","activeEmbeddingModels"]){let o=e[r]??[];for(let i of o){let s=i;for(let a of Uy){let l=s[a];if(typeof l!="string"||l.length===0)continue;let c=await pn(l);c&&(s[a]=c)}}}return e}async function Atn(t){let e=EE(t),{settings:n,hadFailures:r}=await vd.getInstance().hydrateFromKeychain(e);return r&&new S0e.Notice("Some API keys could not be loaded from the Obsidian Keychain. They may be unavailable this session. Restart Obsidian if the issue persists."),n}async function Dht(t,e){let n=t==null,r=Vee(t),o=structuredClone(t??{});kE=CS(o),r=AE(r);let i=vd.getInstance();if(!i.isAvailable()){if(By(r)){let l=EE(r);return Bh=structuredClone(l),l}let a=await Aht(r);return Bh=structuredClone(a),a}if(n&&(r._keychainOnly=!0),Etn(o._keychainVaultId))i.setVaultId(o._keychainVaultId);else{let a=i.getVaultId();r={...r,_keychainVaultId:a};try{let l={...o,_keychainVaultId:a};n&&(l._keychainOnly=!0),await e(l),o=l,kE=CS(o)}catch(l){z("Failed to persist initial keychain settings on first run",l),new S0e.Notice("Could not save initial settings. Please save once to confirm Keychain mode.")}}if(By(r)){kE&&console.warn("disk secrets ignored because keychain-only mode is enabled");let a=await Atn(r);return Bh=structuredClone(a),a}let s=await Aht(r);return Bh=structuredClone(s),s}async function kht(t,e){let n=AE(t);await e(n),_V(n),D1=!1,Bh=structuredClone(t)}async function _0e(t,e,n){let r=vd.getInstance(),o=AE(t),i=Bh??n,{secretEntries:s,keychainIdsToDelete:a}=r.persistSecrets(t,i),l=Bh??n,c=[],u=s.filter(([,d])=>kx(d)).map(([d])=>d);if(u.length>0)throw new Error(`Refusing to persist: undecryptable secrets in keychain-only mode (${u.join(", ")}). Re-enter these keys in Settings before saving.`);D1=!0;try{for(let f of CV)r.setSecretById(f,""),c.push(f);for(let[f,p]of s)r.setSecretById(f,p);for(let f of a)try{r.setSecretById(f,"")}catch(p){throw CV.add(f),p}let d=EE(o);d._keychainOnly=!0,await e(d),_V(d),Bh=structuredClone(t);for(let f of c)CV.delete(f)}catch(d){let f=!1;try{f=await Ntn(r,l,t)}catch(p){ee("Failed to roll back keychain after persist failure.",p)}throw f&&(D1=!1),d}D1=!1}function ktn(t){let e=[],n=t;for(let r of Object.keys(n)){if(!L1(r))continue;let o=n[r];typeof o=="string"&&o.length>0&&kx(o)&&e.push(r)}for(let r of["activeModels","activeEmbeddingModels"])for(let o of t[r]??[]){let i=o;for(let s of Uy){let a=i[s];if(typeof a=="string"&&a.length>0&&kx(a)){let l=i.name??"(unnamed)",c=i.provider??"?";e.push(`${l} (${c}) ${s}`)}}}return e}function Mht(t){let e=structuredClone(t),n=e;for(let r of Object.keys(n)){if(!L1(r))continue;let o=n[r];typeof o=="string"&&o.length>0&&kx(o)&&(n[r]="")}for(let r of["activeModels","activeEmbeddingModels"]){let o=e[r]??[];for(let i of o){let s=i;for(let a of Uy){let l=s[a];typeof l=="string"&&l.length>0&&kx(l)&&(s[a]="")}}}return e}async function $ht(t){let e={fieldsRequiringReentry:[]};return await I0e(async()=>{let n=q();if(!T0e(n))throw new Error("Cannot migrate to Obsidian Keychain: it is unavailable, the last save did not complete safely, or there are no secrets left to migrate. Retry saving settings, then try again.");e.fieldsRequiringReentry=ktn(n);let o={...Mht(n),_keychainOnly:!0};await _0e(o,t,n);let i=q(),a={...Mht(i),_keychainOnly:!0};if(JSON.stringify(a)!==JSON.stringify(o))try{await _0e(a,t,o)}catch(l){throw eQ(),Ls(o),l}eQ(),Ls(a)}),e}async function Fht(t,e,n){if(XX){XX=!1;return}let r=QX,o=$1.then(()=>{if(r===QX)return Mtn(t,e,n)});return $1=o.catch(()=>{}),o}async function Mtn(t,e,n){if(!vd.getInstance().isAvailable()){if(By(t)){let o=EE(AE(t));o._keychainOnly=!0,await e(o),_V(o),Bh=structuredClone(t);return}await kht(t,e);return}if(By(t)){await _0e(t,e,n);return}await kht(t,e)}async function Ntn(t,e,n){if(!e)return!1;let{secretEntries:r,keychainIdsToDelete:o}=t.persistSecrets(e,n),i=!0;for(let[s,a]of r)try{t.setSecretById(s,a)}catch(l){ee(`Failed to restore keychain entry "${s}" during rollback.`,l),i=!1}for(let s of o)try{t.setSecretById(s,""),CV.delete(s)}catch(a){ee(`Failed to write keychain tombstone "${s}" during rollback.`,a),i=!1}return i}ns();FP();QCe();qh();var tQ=class{constructor(e){this.timeoutId=null;this.isRunning=!1;this.leafState=new WeakMap;this.suppressedSelectionsByUrl=new Map;this.intervalMs=e.intervalMs??500;let n=e.emptySelectionDebounceCount??2;this.emptySelectionDebounceCount=Number.isFinite(n)&&n>0?Math.floor(n):2,this.isEnabled=e.isEnabled,this.getLeaf=e.getLeaf,this.getActiveLeaf=e.getActiveLeaf,this.onSelectionChange=e.onSelectionChange,this.onSelectionClear=e.onSelectionClear}start(){this.isRunning||(this.isRunning=!0,this.scheduleNext())}stop(){this.isRunning=!1,this.timeoutId!==null&&(window.clearTimeout(this.timeoutId),this.timeoutId=null),this.leafState=new WeakMap,this.suppressedSelectionsByUrl=new Map}scheduleNext(){this.isRunning&&(this.timeoutId=window.setTimeout(()=>{(async()=>(await this.checkSelection(),this.scheduleNext()))()},this.intervalMs))}async checkSelection(){if(this.isEnabled())try{let e=this.getLeaf();if(!e)return;let n=this.getOrCreateLeafState(e),r=uL(e),o=r.url;if(this.isValidUrl(o))n.consecutiveInvalidUrlChecks=0;else{n.consecutiveEmptyChecks=0,this.maybeClearSelectionForInvalidUrl(e,n);return}let i=await wZ(e);if(!i.trim()){this.handleEmptySelection(e,n);return}if(n.consecutiveEmptyChecks=0,this.shouldSuppressSelectionForUrl(o,i)||n.lastSelection&&n.lastSelection.url===o&&n.lastSelection.text===i)return;let s=await vZ(e);if(!s.trim()||this.shouldSuppressSelectionForUrl(o,i))return;n.lastSelection={url:o,text:i};let a={id:si(),content:s,sourceType:"web",title:r.title||"Untitled",url:o,faviconUrl:r.faviconUrl||void 0};this.onSelectionChange(a)}catch{}}getOrCreateLeafState(e){let n=this.leafState.get(e);if(n)return n;let r={lastSelection:null,consecutiveEmptyChecks:0,consecutiveInvalidUrlChecks:0};return this.leafState.set(e,r),r}isValidUrl(e){let n=e.trim();if(!n)return!1;try{return new URL(n),!0}catch{return!1}}isActiveWebViewerLeaf(e){let n=this.getActiveLeaf();return!!(n&&n===e)}handleEmptySelection(e,n){if(!n.lastSelection||!this.isActiveWebViewerLeaf(e)||(n.consecutiveEmptyChecks+=1,n.consecutiveEmptyChecks<this.emptySelectionDebounceCount))return;let r=n.lastSelection.url;n.lastSelection=null,n.consecutiveEmptyChecks=0,this.clearSuppressionForUrl(r),this.onSelectionClear({url:r,reason:"selection-cleared"})}maybeClearSelectionForInvalidUrl(e,n){if(!n.lastSelection||!this.isActiveWebViewerLeaf(e)||(n.consecutiveInvalidUrlChecks+=1,n.consecutiveInvalidUrlChecks<this.emptySelectionDebounceCount))return;let r=n.lastSelection.url;n.lastSelection=null,n.consecutiveEmptyChecks=0,n.consecutiveInvalidUrlChecks=0,this.clearSuppressionForUrl(r),this.onSelectionClear({url:r,reason:"invalid-url"})}clearSuppressionForUrl(e){this.suppressedSelectionsByUrl.delete(e.trim())}shouldSuppressSelectionForUrl(e,n){let r=e.trim(),o=this.suppressedSelectionsByUrl.get(r);return o===void 0?!1:o===null?(this.suppressedSelectionsByUrl.set(r,n),!0):o===n?!0:(this.suppressedSelectionsByUrl.delete(r),!1)}suppressSelectionForUrl(e){let n=e.trim();this.isValidUrl(n)&&this.suppressedSelectionsByUrl.set(n,null)}suppressCurrentSelection(){let e=this.getLeaf();if(!e)return;let n=uL(e);this.suppressSelectionForUrl(n.url)}};ei();It();Se();ye();var HV=require("obsidian"),Dyt=N(U());var nQ=class extends Cr{constructor(e,n){super(e,n,'Resetting settings will clear all settings and restore the default values. API keys are not cleared by this action \u2014 use "Delete All Keys" in Advanced Settings \u2192 API Key Storage if you also want to remove them. Are you sure you want to continue?',"Reset Settings")}};rn();var SV=N(U());Kt();var Uht=({tab:t,isSelected:e,onClick:n,isFirst:r,isLast:o})=>SV.default.createElement("div",{role:"tab",id:`tab-${t.id}`,"aria-controls":`tabpanel-${t.id}`,"aria-selected":e,onClick:n,className:oe("tw-flex tw-flex-row tw-items-center","tw-h-8","tw-px-2 tw-py-1","tw-gap-1.5","tw-cursor-pointer","tw-overflow-hidden","tw-whitespace-nowrap","tw-text-sm","tw-border tw-border-solid tw-border-border","tw-rounded-b-[2px] tw-rounded-t-sm","tw-bg-primary","tw-transition-all tw-duration-300 tw-ease-in-out","hover:tw-border-interactive-accent",e&&["!tw-bg-interactive-accent","tw-text-on-accent","!tw-max-w-full","tw-transition-all tw-duration-300 tw-ease-in-out","tw-delay-100"],"lg:tw-max-w-32","md:tw-max-w-32")},SV.default.createElement("div",{className:oe("tw-flex tw-items-center tw-justify-center","tw-size-4","tw-transition-transform tw-duration-200 tw-ease-in-out",e?"tw-max-w-[16px] tw-translate-x-0 tw-opacity-100":"tw-max-w-0 tw--translate-x-4 tw-opacity-0")},t.icon),SV.default.createElement("span",{className:oe("tw-text-sm","tw-font-medium","tw-transition-all tw-duration-200 tw-ease-in-out","tw-overflow-hidden tw-whitespace-nowrap","tw-max-w-[100px] tw-translate-x-0 tw-opacity-100")},t.label)),Bht=({id:t,children:e,isSelected:n})=>n?SV.default.createElement("div",{role:"tabpanel",id:`tabpanel-${t}`,"aria-labelledby":`tab-${t}`,className:oe("tw-pt-4","tw-transition-all tw-duration-200 tw-ease-in-out",n?"tw-translate-y-0 tw-opacity-100":"tw-translate-y-2 tw-opacity-0")},e):null;var zh=N(U()),zht=(0,zh.createContext)(void 0),jht=({children:t})=>{let[e,n]=(0,zh.useState)("basic"),[r]=(0,zh.useState)(()=>activeDocument.querySelector(".modal-container")),o=(0,zh.useMemo)(()=>({selectedTab:e,setSelectedTab:n,modalContainer:r}),[e,r]);return zh.default.createElement(zht.Provider,{value:o},t)},SS=()=>{let t=(0,zh.useContext)(zht);if(t===void 0)throw new Error("useTab must be used within a TabProvider");return t};Se();var Ke=N(U());rn();var lo=N(U());rn();Kt();var ps=N(U());var Pe=N(U()),$E=N(yo());var fs=N(U());function Wht(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return(0,fs.useMemo)(()=>r=>{e.forEach(o=>o(r))},e)}var TV=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ME(t){let e=Object.prototype.toString.call(t);return e==="[object Window]"||e==="[object global]"}function rQ(t){return"nodeType"in t}function yu(t){var e,n;return t?ME(t)?t:rQ(t)&&(e=(n=t.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function oQ(t){let{Document:e}=yu(t);return t instanceof e}function F1(t){return ME(t)?!1:t instanceof yu(t).HTMLElement}function E0e(t){return t instanceof yu(t).SVGElement}function NE(t){return t?ME(t)?t.document:rQ(t)?oQ(t)?t:F1(t)||E0e(t)?t.ownerDocument:document:document:document}var im=TV?fs.useLayoutEffect:fs.useEffect;function iQ(t){let e=(0,fs.useRef)(t);return im(()=>{e.current=t}),(0,fs.useCallback)(function(){for(var n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return e.current==null?void 0:e.current(...r)},[])}function Hht(){let t=(0,fs.useRef)(null),e=(0,fs.useCallback)((r,o)=>{t.current=setInterval(r,o)},[]),n=(0,fs.useCallback)(()=>{t.current!==null&&(clearInterval(t.current),t.current=null)},[]);return[e,n]}function U1(t,e){e===void 0&&(e=[t]);let n=(0,fs.useRef)(t);return im(()=>{n.current!==t&&(n.current=t)},e),n}function B1(t,e){let n=(0,fs.useRef)();return(0,fs.useMemo)(()=>{let r=t(n.current);return n.current=r,r},[...e])}function IV(t){let e=iQ(t),n=(0,fs.useRef)(null),r=(0,fs.useCallback)(o=>{o!==n.current&&e?.(o,n.current),n.current=o},[]);return[n,r]}function sQ(t){let e=(0,fs.useRef)();return(0,fs.useEffect)(()=>{e.current=t},[t]),e.current}var P0e={};function OE(t,e){return(0,fs.useMemo)(()=>{if(e)return e;let n=P0e[t]==null?0:P0e[t]+1;return P0e[t]=n,t+"-"+n},[t,e])}function Kht(t){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return r.reduce((i,s)=>{let a=Object.entries(s);for(let[l,c]of a){let u=i[l];u!=null&&(i[l]=u+t*c)}return i},{...e})}}var RE=Kht(1),LE=Kht(-1);function Otn(t){return"clientX"in t&&"clientY"in t}function PV(t){if(!t)return!1;let{KeyboardEvent:e}=yu(t.target);return e&&t instanceof e}function Rtn(t){if(!t)return!1;let{TouchEvent:e}=yu(t.target);return e&&t instanceof e}function aQ(t){if(Rtn(t)){if(t.touches&&t.touches.length){let{clientX:e,clientY:n}=t.touches[0];return{x:e,y:n}}else if(t.changedTouches&&t.changedTouches.length){let{clientX:e,clientY:n}=t.changedTouches[0];return{x:e,y:n}}}return Otn(t)?{x:t.clientX,y:t.clientY}:null}var om=Object.freeze({Translate:{toString(t){if(!t)return;let{x:e,y:n}=t;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(t){if(!t)return;let{scaleX:e,scaleY:n}=t;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(t){if(t)return[om.Translate.toString(t),om.Scale.toString(t)].join(" ")}},Transition:{toString(t){let{property:e,duration:n,easing:r}=t;return e+" "+n+"ms "+r}}}),Vht="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function qht(t){return t.matches(Vht)?t:t.querySelector(Vht)}var DE=N(U()),Ltn={display:"none"};function Ght(t){let{id:e,value:n}=t;return DE.default.createElement("div",{id:e,style:Ltn},n)}function Yht(t){let{id:e,announcement:n,ariaLiveType:r="assertive"}=t,o={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return DE.default.createElement("div",{id:e,style:o,role:"status","aria-live":r,"aria-atomic":!0},n)}function Zht(){let[t,e]=(0,DE.useState)("");return{announce:(0,DE.useCallback)(r=>{r!=null&&e(r)},[]),announcement:t}}var cgt=(0,Pe.createContext)(null);function Dtn(t){let e=(0,Pe.useContext)(cgt);(0,Pe.useEffect)(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of <DndContext>");return e(t)},[t,e])}function $tn(){let[t]=(0,Pe.useState)(()=>new Set),e=(0,Pe.useCallback)(r=>(t.add(r),()=>t.delete(r)),[t]);return[(0,Pe.useCallback)(r=>{let{type:o,event:i}=r;t.forEach(s=>{var a;return(a=s[o])==null?void 0:a.call(s,i)})},[t]),e]}var Ftn={draggable:`
    To pick up a draggable item, press the space bar.
    While dragging, use the arrow keys to move the item.
    Press space again to drop the item in its new position, or press escape to cancel.
  `},Utn={onDragStart(t){let{active:e}=t;return"Picked up draggable item "+e.id+"."},onDragOver(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(t){let{active:e,over:n}=t;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(t){let{active:e}=t;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function Btn(t){let{announcements:e=Utn,container:n,hiddenTextDescribedById:r,screenReaderInstructions:o=Ftn}=t,{announce:i,announcement:s}=Zht(),a=OE("DndLiveRegion"),[l,c]=(0,Pe.useState)(!1);if((0,Pe.useEffect)(()=>{c(!0)},[]),Dtn((0,Pe.useMemo)(()=>({onDragStart(d){let{active:f}=d;i(e.onDragStart({active:f}))},onDragMove(d){let{active:f,over:p}=d;e.onDragMove&&i(e.onDragMove({active:f,over:p}))},onDragOver(d){let{active:f,over:p}=d;i(e.onDragOver({active:f,over:p}))},onDragEnd(d){let{active:f,over:p}=d;i(e.onDragEnd({active:f,over:p}))},onDragCancel(d){let{active:f,over:p}=d;i(e.onDragCancel({active:f,over:p}))}}),[i,e])),!l)return null;let u=Pe.default.createElement(Pe.default.Fragment,null,Pe.default.createElement(Ght,{id:r,value:o.draggable}),Pe.default.createElement(Yht,{id:a,announcement:s}));return n?(0,$E.createPortal)(u,n):u}var Ca;(function(t){t.DragStart="dragStart",t.DragMove="dragMove",t.DragEnd="dragEnd",t.DragCancel="dragCancel",t.DragOver="dragOver",t.RegisterDroppable="registerDroppable",t.SetDroppableDisabled="setDroppableDisabled",t.UnregisterDroppable="unregisterDroppable"})(Ca||(Ca={}));function cQ(){}function z1(t,e){return(0,Pe.useMemo)(()=>({sensor:t,options:e??{}}),[t,e])}function dQ(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return(0,Pe.useMemo)(()=>[...e].filter(r=>r!=null),[...e])}var jh=Object.freeze({x:0,y:0});function ugt(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}function dgt(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return n-r}function ztn(t,e){let{data:{value:n}}=t,{data:{value:r}}=e;return r-n}function Jht(t){let{left:e,top:n,height:r,width:o}=t;return[{x:e,y:n},{x:e+o,y:n},{x:e,y:n+r},{x:e+o,y:n+r}]}function $0e(t,e){if(!t||t.length===0)return null;let[n]=t;return e?n[e]:n}function Xht(t,e,n){return e===void 0&&(e=t.left),n===void 0&&(n=t.top),{x:e+t.width*.5,y:n+t.height*.5}}var j1=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t,o=Xht(e,e.left,e.top),i=[];for(let s of r){let{id:a}=s,l=n.get(a);if(l){let c=ugt(Xht(l),o);i.push({id:a,data:{droppableContainer:s,value:c}})}}return i.sort(dgt)},fgt=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t,o=Jht(e),i=[];for(let s of r){let{id:a}=s,l=n.get(a);if(l){let c=Jht(l),u=o.reduce((f,p,m)=>f+ugt(c[m],p),0),d=Number((u/4).toFixed(4));i.push({id:a,data:{droppableContainer:s,value:d}})}}return i.sort(dgt)};function jtn(t,e){let n=Math.max(e.top,t.top),r=Math.max(e.left,t.left),o=Math.min(e.left+e.width,t.left+t.width),i=Math.min(e.top+e.height,t.top+t.height),s=o-r,a=i-n;if(r<o&&n<i){let l=e.width*e.height,c=t.width*t.height,u=s*a,d=u/(l+c-u);return Number(d.toFixed(4))}return 0}var Vtn=t=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=t,o=[];for(let i of r){let{id:s}=i,a=n.get(s);if(a){let l=jtn(a,e);l>0&&o.push({id:s,data:{droppableContainer:i,value:l}})}}return o.sort(ztn)};function Wtn(t,e,n){return{...t,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function pgt(t,e){return t&&e?{x:t.left-e.left,y:t.top-e.top}:jh}function Htn(t){return function(n){for(var r=arguments.length,o=new Array(r>1?r-1:0),i=1;i<r;i++)o[i-1]=arguments[i];return o.reduce((s,a)=>({...s,top:s.top+t*a.y,bottom:s.bottom+t*a.y,left:s.left+t*a.x,right:s.right+t*a.x}),{...n})}}var Ktn=Htn(1);function qtn(t){if(t.startsWith("matrix3d(")){let e=t.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(t.startsWith("matrix(")){let e=t.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function Gtn(t,e,n){let r=qtn(e);if(!r)return t;let{scaleX:o,scaleY:i,x:s,y:a}=r,l=t.left-s-(1-o)*parseFloat(n),c=t.top-a-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),u=o?t.width/o:t.width,d=i?t.height/i:t.height;return{width:u,height:d,top:c,right:l+u,bottom:c+d,left:l}}var Ytn={ignoreTransform:!1};function BE(t,e){e===void 0&&(e=Ytn);let n=t.getBoundingClientRect();if(e.ignoreTransform){let{transform:c,transformOrigin:u}=yu(t).getComputedStyle(t);c&&(n=Gtn(n,c,u))}let{top:r,left:o,width:i,height:s,bottom:a,right:l}=n;return{top:r,left:o,width:i,height:s,bottom:a,right:l}}function Qht(t){return BE(t,{ignoreTransform:!0})}function Ztn(t){let e=t.innerWidth,n=t.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function Jtn(t,e){return e===void 0&&(e=yu(t).getComputedStyle(t)),e.position==="fixed"}function Xtn(t,e){e===void 0&&(e=yu(t).getComputedStyle(t));let n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{let i=e[o];return typeof i=="string"?n.test(i):!1})}function NV(t,e){let n=[];function r(o){if(e!=null&&n.length>=e||!o)return n;if(oQ(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!F1(o)||E0e(o)||n.includes(o))return n;let i=yu(t).getComputedStyle(o);return o!==t&&Xtn(o,i)&&n.push(o),Jtn(o,i)?n:r(o.parentNode)}return t?r(t):n}function mgt(t){let[e]=NV(t,1);return e??null}function A0e(t){return!TV||!t?null:ME(t)?t:rQ(t)?oQ(t)||t===NE(t).scrollingElement?window:F1(t)?t:null:null}function hgt(t){return ME(t)?t.scrollX:t.scrollLeft}function ggt(t){return ME(t)?t.scrollY:t.scrollTop}function N0e(t){return{x:hgt(t),y:ggt(t)}}var il;(function(t){t[t.Forward=1]="Forward",t[t.Backward=-1]="Backward"})(il||(il={}));function ygt(t){return!TV||!t?!1:t===document.scrollingElement}function wgt(t){let e={x:0,y:0},n=ygt(t)?{height:window.innerHeight,width:window.innerWidth}:{height:t.clientHeight,width:t.clientWidth},r={x:t.scrollWidth-n.width,y:t.scrollHeight-n.height},o=t.scrollTop<=e.y,i=t.scrollLeft<=e.x,s=t.scrollTop>=r.y,a=t.scrollLeft>=r.x;return{isTop:o,isLeft:i,isBottom:s,isRight:a,maxScroll:r,minScroll:e}}var Qtn={x:.2,y:.2};function enn(t,e,n,r,o){let{top:i,left:s,right:a,bottom:l}=n;r===void 0&&(r=10),o===void 0&&(o=Qtn);let{isTop:c,isBottom:u,isLeft:d,isRight:f}=wgt(t),p={x:0,y:0},m={x:0,y:0},h={height:e.height*o.y,width:e.width*o.x};return!c&&i<=e.top+h.height?(p.y=il.Backward,m.y=r*Math.abs((e.top+h.height-i)/h.height)):!u&&l>=e.bottom-h.height&&(p.y=il.Forward,m.y=r*Math.abs((e.bottom-h.height-l)/h.height)),!f&&a>=e.right-h.width?(p.x=il.Forward,m.x=r*Math.abs((e.right-h.width-a)/h.width)):!d&&s<=e.left+h.width&&(p.x=il.Backward,m.x=r*Math.abs((e.left+h.width-s)/h.width)),{direction:p,speed:m}}function tnn(t){if(t===document.scrollingElement){let{innerWidth:i,innerHeight:s}=window;return{top:0,left:0,right:i,bottom:s,width:i,height:s}}let{top:e,left:n,right:r,bottom:o}=t.getBoundingClientRect();return{top:e,left:n,right:r,bottom:o,width:t.clientWidth,height:t.clientHeight}}function vgt(t){return t.reduce((e,n)=>RE(e,N0e(n)),jh)}function nnn(t){return t.reduce((e,n)=>e+hgt(n),0)}function rnn(t){return t.reduce((e,n)=>e+ggt(n),0)}function onn(t,e){if(e===void 0&&(e=BE),!t)return;let{top:n,left:r,bottom:o,right:i}=e(t);mgt(t)&&(o<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&t.scrollIntoView({block:"center",inline:"center"})}var inn=[["x",["left","right"],nnn],["y",["top","bottom"],rnn]],AV=class{constructor(e,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;let r=NV(n),o=vgt(r);this.rect={...e},this.width=e.width,this.height=e.height;for(let[i,s,a]of inn)for(let l of s)Object.defineProperty(this,l,{get:()=>{let c=a(r),u=o[i]-c;return this.rect[l]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}},FE=class{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var o;(o=this.target)==null||o.addEventListener(e,n,r),this.listeners.push([e,n,r])}};function snn(t){let{EventTarget:e}=yu(t);return t instanceof e?t:NE(t)}function k0e(t,e){let n=Math.abs(t.x),r=Math.abs(t.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var sm;(function(t){t.Click="click",t.DragStart="dragstart",t.Keydown="keydown",t.ContextMenu="contextmenu",t.Resize="resize",t.SelectionChange="selectionchange",t.VisibilityChange="visibilitychange"})(sm||(sm={}));function egt(t){t.preventDefault()}function ann(t){t.stopPropagation()}var _r;(function(t){t.Space="Space",t.Down="ArrowDown",t.Right="ArrowRight",t.Left="ArrowLeft",t.Up="ArrowUp",t.Esc="Escape",t.Enter="Enter",t.Tab="Tab"})(_r||(_r={}));var xgt={start:[_r.Space,_r.Enter],cancel:[_r.Esc],end:[_r.Space,_r.Enter,_r.Tab]},lnn=(t,e)=>{let{currentCoordinates:n}=e;switch(t.code){case _r.Right:return{...n,x:n.x+25};case _r.Left:return{...n,x:n.x-25};case _r.Down:return{...n,y:n.y+25};case _r.Up:return{...n,y:n.y-25}}},IS=class{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;let{event:{target:n}}=e;this.props=e,this.listeners=new FE(NE(n)),this.windowListeners=new FE(yu(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(sm.Resize,this.handleCancel),this.windowListeners.add(sm.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(sm.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&onn(r),n(jh)}handleKeyDown(e){if(PV(e)){let{active:n,context:r,options:o}=this.props,{keyboardCodes:i=xgt,coordinateGetter:s=lnn,scrollBehavior:a="smooth"}=o,{code:l}=e;if(i.end.includes(l)){this.handleEnd(e);return}if(i.cancel.includes(l)){this.handleCancel(e);return}let{collisionRect:c}=r.current,u=c?{x:c.left,y:c.top}:jh;this.referenceCoordinates||(this.referenceCoordinates=u);let d=s(e,{active:n,context:r.current,currentCoordinates:u});if(d){let f=LE(d,u),p={x:0,y:0},{scrollableAncestors:m}=r.current;for(let h of m){let g=e.code,{isTop:y,isRight:w,isLeft:v,isBottom:x,maxScroll:b,minScroll:_}=wgt(h),T=tnn(h),S={x:Math.min(g===_r.Right?T.right-T.width/2:T.right,Math.max(g===_r.Right?T.left:T.left+T.width/2,d.x)),y:Math.min(g===_r.Down?T.bottom-T.height/2:T.bottom,Math.max(g===_r.Down?T.top:T.top+T.height/2,d.y))},P=g===_r.Right&&!w||g===_r.Left&&!v,A=g===_r.Down&&!x||g===_r.Up&&!y;if(P&&S.x!==d.x){let O=h.scrollLeft+f.x,D=g===_r.Right&&O<=b.x||g===_r.Left&&O>=_.x;if(D&&!f.y){h.scrollTo({left:O,behavior:a});return}D?p.x=h.scrollLeft-O:p.x=g===_r.Right?h.scrollLeft-b.x:h.scrollLeft-_.x,p.x&&h.scrollBy({left:-p.x,behavior:a});break}else if(A&&S.y!==d.y){let O=h.scrollTop+f.y,D=g===_r.Down&&O<=b.y||g===_r.Up&&O>=_.y;if(D&&!f.x){h.scrollTo({top:O,behavior:a});return}D?p.y=h.scrollTop-O:p.y=g===_r.Down?h.scrollTop-b.y:h.scrollTop-_.y,p.y&&h.scrollBy({top:-p.y,behavior:a});break}}this.handleMove(e,RE(LE(d,this.referenceCoordinates),p))}}}handleMove(e,n){let{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){let{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){let{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}};IS.activators=[{eventName:"onKeyDown",handler:(t,e,n)=>{let{keyboardCodes:r=xgt,onActivation:o}=e,{active:i}=n,{code:s}=t.nativeEvent;if(r.start.includes(s)){let a=i.activatorNode.current;return a&&t.target!==a?!1:(t.preventDefault(),o?.({event:t.nativeEvent}),!0)}return!1}}];function tgt(t){return!!(t&&"distance"in t)}function ngt(t){return!!(t&&"delay"in t)}var kV=class{constructor(e,n,r){var o;r===void 0&&(r=snn(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=n;let{event:i}=e,{target:s}=i;this.props=e,this.events=n,this.document=NE(s),this.documentListeners=new FE(this.document),this.listeners=new FE(r),this.windowListeners=new FE(yu(s)),this.initialCoordinates=(o=aQ(i))!=null?o:jh,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(sm.Resize,this.handleCancel),this.windowListeners.add(sm.DragStart,egt),this.windowListeners.add(sm.VisibilityChange,this.handleCancel),this.windowListeners.add(sm.ContextMenu,egt),this.documentListeners.add(sm.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(ngt(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(tgt(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,n){let{active:r,onPending:o}=this.props;o(r,e,this.initialCoordinates,n)}handleStart(){let{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(sm.Click,ann,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(sm.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;let{activated:r,initialCoordinates:o,props:i}=this,{onMove:s,options:{activationConstraint:a}}=i;if(!o)return;let l=(n=aQ(e))!=null?n:jh,c=LE(o,l);if(!r&&a){if(tgt(a)){if(a.tolerance!=null&&k0e(c,a.tolerance))return this.handleCancel();if(k0e(c,a.distance))return this.handleStart()}if(ngt(a)&&k0e(c,a.tolerance))return this.handleCancel();this.handlePending(a,c);return}e.cancelable&&e.preventDefault(),s(l)}handleEnd(){let{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){let{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===_r.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}},cnn={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}},PS=class extends kV{constructor(e){let{event:n}=e,r=NE(n.target);super(e,cnn,r)}};PS.activators=[{eventName:"onPointerDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];var unn={move:{name:"mousemove"},end:{name:"mouseup"}},O0e;(function(t){t[t.RightClick=2]="RightClick"})(O0e||(O0e={}));var R0e=class extends kV{constructor(e){super(e,unn,NE(e.event.target))}};R0e.activators=[{eventName:"onMouseDown",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e;return n.button===O0e.RightClick?!1:(r?.({event:n}),!0)}}];var M0e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}},L0e=class extends kV{constructor(e){super(e,M0e)}static setup(){return window.addEventListener(M0e.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(M0e.move.name,e)};function e(){}}};L0e.activators=[{eventName:"onTouchStart",handler:(t,e)=>{let{nativeEvent:n}=t,{onActivation:r}=e,{touches:o}=n;return o.length>1?!1:(r?.({event:n}),!0)}}];var EV;(function(t){t[t.Pointer=0]="Pointer",t[t.DraggableRect=1]="DraggableRect"})(EV||(EV={}));var uQ;(function(t){t[t.TreeOrder=0]="TreeOrder",t[t.ReversedTreeOrder=1]="ReversedTreeOrder"})(uQ||(uQ={}));function dnn(t){let{acceleration:e,activator:n=EV.Pointer,canScroll:r,draggingRect:o,enabled:i,interval:s=5,order:a=uQ.TreeOrder,pointerCoordinates:l,scrollableAncestors:c,scrollableAncestorRects:u,delta:d,threshold:f}=t,p=pnn({delta:d,disabled:!i}),[m,h]=Hht(),g=(0,Pe.useRef)({x:0,y:0}),y=(0,Pe.useRef)({x:0,y:0}),w=(0,Pe.useMemo)(()=>{switch(n){case EV.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case EV.DraggableRect:return o}},[n,o,l]),v=(0,Pe.useRef)(null),x=(0,Pe.useCallback)(()=>{let _=v.current;if(!_)return;let T=g.current.x*y.current.x,S=g.current.y*y.current.y;_.scrollBy(T,S)},[]),b=(0,Pe.useMemo)(()=>a===uQ.TreeOrder?[...c].reverse():c,[a,c]);(0,Pe.useEffect)(()=>{if(!i||!c.length||!w){h();return}for(let _ of b){if(r?.(_)===!1)continue;let T=c.indexOf(_),S=u[T];if(!S)continue;let{direction:P,speed:A}=enn(_,S,w,e,f);for(let O of["x","y"])p[O][P[O]]||(A[O]=0,P[O]=0);if(A.x>0||A.y>0){h(),v.current=_,m(x,s),g.current=A,y.current=P;return}}g.current={x:0,y:0},y.current={x:0,y:0},h()},[e,x,r,h,i,s,JSON.stringify(w),JSON.stringify(p),m,c,b,u,JSON.stringify(f)])}var fnn={x:{[il.Backward]:!1,[il.Forward]:!1},y:{[il.Backward]:!1,[il.Forward]:!1}};function pnn(t){let{delta:e,disabled:n}=t,r=sQ(e);return B1(o=>{if(n||!r||!o)return fnn;let i={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[il.Backward]:o.x[il.Backward]||i.x===-1,[il.Forward]:o.x[il.Forward]||i.x===1},y:{[il.Backward]:o.y[il.Backward]||i.y===-1,[il.Forward]:o.y[il.Forward]||i.y===1}}},[n,e,r])}function mnn(t,e){let n=e!=null?t.get(e):void 0,r=n?n.node.current:null;return B1(o=>{var i;return e==null?null:(i=r??o)!=null?i:null},[r,e])}function hnn(t,e){return(0,Pe.useMemo)(()=>t.reduce((n,r)=>{let{sensor:o}=r,i=o.activators.map(s=>({eventName:s.eventName,handler:e(s.handler,r)}));return[...n,...i]},[]),[t,e])}var MV;(function(t){t[t.Always=0]="Always",t[t.BeforeDragging=1]="BeforeDragging",t[t.WhileDragging=2]="WhileDragging"})(MV||(MV={}));var D0e;(function(t){t.Optimized="optimized"})(D0e||(D0e={}));var rgt=new Map;function gnn(t,e){let{dragging:n,dependencies:r,config:o}=e,[i,s]=(0,Pe.useState)(null),{frequency:a,measure:l,strategy:c}=o,u=(0,Pe.useRef)(t),d=g(),f=U1(d),p=(0,Pe.useCallback)(function(y){y===void 0&&(y=[]),!f.current&&s(w=>w===null?y:w.concat(y.filter(v=>!w.includes(v))))},[f]),m=(0,Pe.useRef)(null),h=B1(y=>{if(d&&!n)return rgt;if(!y||y===rgt||u.current!==t||i!=null){let w=new Map;for(let v of t){if(!v)continue;if(i&&i.length>0&&!i.includes(v.id)&&v.rect.current){w.set(v.id,v.rect.current);continue}let x=v.node.current,b=x?new AV(l(x),x):null;v.rect.current=b,b&&w.set(v.id,b)}return w}return y},[t,i,n,d,l]);return(0,Pe.useEffect)(()=>{u.current=t},[t]),(0,Pe.useEffect)(()=>{d||p()},[n,d]),(0,Pe.useEffect)(()=>{i&&i.length>0&&s(null)},[JSON.stringify(i)]),(0,Pe.useEffect)(()=>{d||typeof a!="number"||m.current!==null||(m.current=setTimeout(()=>{p(),m.current=null},a))},[a,d,p,...r]),{droppableRects:h,measureDroppableContainers:p,measuringScheduled:i!=null};function g(){switch(c){case MV.Always:return!1;case MV.BeforeDragging:return n;default:return!n}}}function bgt(t,e){return B1(n=>t?n||(typeof e=="function"?e(t):t):null,[e,t])}function ynn(t,e){return bgt(t,e)}function wnn(t){let{callback:e,disabled:n}=t,r=iQ(e),o=(0,Pe.useMemo)(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;let{MutationObserver:i}=window;return new i(r)},[r,n]);return(0,Pe.useEffect)(()=>()=>o?.disconnect(),[o]),o}function fQ(t){let{callback:e,disabled:n}=t,r=iQ(e),o=(0,Pe.useMemo)(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;let{ResizeObserver:i}=window;return new i(r)},[n]);return(0,Pe.useEffect)(()=>()=>o?.disconnect(),[o]),o}function vnn(t){return new AV(BE(t),t)}function ogt(t,e,n){e===void 0&&(e=vnn);let[r,o]=(0,Pe.useState)(null);function i(){o(l=>{if(!t)return null;if(t.isConnected===!1){var c;return(c=l??n)!=null?c:null}let u=e(t);return JSON.stringify(l)===JSON.stringify(u)?l:u})}let s=wnn({callback(l){if(t)for(let c of l){let{type:u,target:d}=c;if(u==="childList"&&d instanceof HTMLElement&&d.contains(t)){i();break}}}}),a=fQ({callback:i});return im(()=>{i(),t?(a?.observe(t),s?.observe(document.body,{childList:!0,subtree:!0})):(a?.disconnect(),s?.disconnect())},[t]),r}function xnn(t){let e=bgt(t);return pgt(t,e)}var igt=[];function bnn(t){let e=(0,Pe.useRef)(t),n=B1(r=>t?r&&r!==igt&&t&&e.current&&t.parentNode===e.current.parentNode?r:NV(t):igt,[t]);return(0,Pe.useEffect)(()=>{e.current=t},[t]),n}function Cnn(t){let[e,n]=(0,Pe.useState)(null),r=(0,Pe.useRef)(t),o=(0,Pe.useCallback)(i=>{let s=A0e(i.target);s&&n(a=>a?(a.set(s,N0e(s)),new Map(a)):null)},[]);return(0,Pe.useEffect)(()=>{let i=r.current;if(t!==i){s(i);let a=t.map(l=>{let c=A0e(l);return c?(c.addEventListener("scroll",o,{passive:!0}),[c,N0e(c)]):null}).filter(l=>l!=null);n(a.length?new Map(a):null),r.current=t}return()=>{s(t),s(i)};function s(a){a.forEach(l=>{let c=A0e(l);c?.removeEventListener("scroll",o)})}},[o,t]),(0,Pe.useMemo)(()=>t.length?e?Array.from(e.values()).reduce((i,s)=>RE(i,s),jh):vgt(t):jh,[t,e])}function sgt(t,e){e===void 0&&(e=[]);let n=(0,Pe.useRef)(null);return(0,Pe.useEffect)(()=>{n.current=null},e),(0,Pe.useEffect)(()=>{let r=t!==jh;r&&!n.current&&(n.current=t),!r&&n.current&&(n.current=null)},[t]),n.current?LE(t,n.current):jh}function _nn(t){(0,Pe.useEffect)(()=>{if(!TV)return;let e=t.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(let n of e)n?.()}},t.map(e=>{let{sensor:n}=e;return n}))}function Snn(t,e){return(0,Pe.useMemo)(()=>t.reduce((n,r)=>{let{eventName:o,handler:i}=r;return n[o]=s=>{i(s,e)},n},{}),[t,e])}function Cgt(t){return(0,Pe.useMemo)(()=>t?Ztn(t):null,[t])}var agt=[];function Tnn(t,e){e===void 0&&(e=BE);let[n]=t,r=Cgt(n?yu(n):null),[o,i]=(0,Pe.useState)(agt);function s(){i(()=>t.length?t.map(l=>ygt(l)?r:new AV(e(l),l)):agt)}let a=fQ({callback:s});return im(()=>{a?.disconnect(),s(),t.forEach(l=>a?.observe(l))},[t]),o}function Inn(t){if(!t)return null;if(t.children.length>1)return t;let e=t.children[0];return F1(e)?e:t}function Pnn(t){let{measure:e}=t,[n,r]=(0,Pe.useState)(null),o=(0,Pe.useCallback)(c=>{for(let{target:u}of c)if(F1(u)){r(d=>{let f=e(u);return d?{...d,width:f.width,height:f.height}:f});break}},[e]),i=fQ({callback:o}),s=(0,Pe.useCallback)(c=>{let u=Inn(c);i?.disconnect(),u&&i?.observe(u),r(u?e(u):null)},[e,i]),[a,l]=IV(s);return(0,Pe.useMemo)(()=>({nodeRef:a,rect:n,setRef:l}),[n,a,l])}var Enn=[{sensor:PS,options:{}},{sensor:IS,options:{}}],Ann={current:{}},lQ={draggable:{measure:Qht},droppable:{measure:Qht,strategy:MV.WhileDragging,frequency:D0e.Optimized},dragOverlay:{measure:BE}},UE=class extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}},knn={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new UE,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:cQ},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:lQ,measureDroppableContainers:cQ,windowRect:null,measuringScheduled:!1},Mnn={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:cQ,draggableNodes:new Map,over:null,measureDroppableContainers:cQ},pQ=(0,Pe.createContext)(Mnn),_gt=(0,Pe.createContext)(knn);function Nnn(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new UE}}}function Onn(t,e){switch(e.type){case Ca.DragStart:return{...t,draggable:{...t.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case Ca.DragMove:return t.draggable.active==null?t:{...t,draggable:{...t.draggable,translate:{x:e.coordinates.x-t.draggable.initialCoordinates.x,y:e.coordinates.y-t.draggable.initialCoordinates.y}}};case Ca.DragEnd:case Ca.DragCancel:return{...t,draggable:{...t.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Ca.RegisterDroppable:{let{element:n}=e,{id:r}=n,o=new UE(t.droppable.containers);return o.set(r,n),{...t,droppable:{...t.droppable,containers:o}}}case Ca.SetDroppableDisabled:{let{id:n,key:r,disabled:o}=e,i=t.droppable.containers.get(n);if(!i||r!==i.key)return t;let s=new UE(t.droppable.containers);return s.set(n,{...i,disabled:o}),{...t,droppable:{...t.droppable,containers:s}}}case Ca.UnregisterDroppable:{let{id:n,key:r}=e,o=t.droppable.containers.get(n);if(!o||r!==o.key)return t;let i=new UE(t.droppable.containers);return i.delete(n),{...t,droppable:{...t.droppable,containers:i}}}default:return t}}function Rnn(t){let{disabled:e}=t,{active:n,activatorEvent:r,draggableNodes:o}=(0,Pe.useContext)(pQ),i=sQ(r),s=sQ(n?.id);return(0,Pe.useEffect)(()=>{if(!e&&!r&&i&&s!=null){if(!PV(i)||document.activeElement===i.target)return;let a=o.get(s);if(!a)return;let{activatorNode:l,node:c}=a;if(!l.current&&!c.current)return;requestAnimationFrame(()=>{for(let u of[l.current,c.current]){if(!u)continue;let d=qht(u);if(d){d.focus();break}}})}},[r,e,o,s,i]),null}function Lnn(t,e){let{transform:n,...r}=e;return t!=null&&t.length?t.reduce((o,i)=>i({transform:o,...r}),n):n}function Dnn(t){return(0,Pe.useMemo)(()=>({draggable:{...lQ.draggable,...t?.draggable},droppable:{...lQ.droppable,...t?.droppable},dragOverlay:{...lQ.dragOverlay,...t?.dragOverlay}}),[t?.draggable,t?.droppable,t?.dragOverlay])}function $nn(t){let{activeNode:e,measure:n,initialRect:r,config:o=!0}=t,i=(0,Pe.useRef)(!1),{x:s,y:a}=typeof o=="boolean"?{x:o,y:o}:o;im(()=>{if(!s&&!a||!e){i.current=!1;return}if(i.current||!r)return;let c=e?.node.current;if(!c||c.isConnected===!1)return;let u=n(c),d=pgt(u,r);if(s||(d.x=0),a||(d.y=0),i.current=!0,Math.abs(d.x)>0||Math.abs(d.y)>0){let f=mgt(c);f&&f.scrollBy({top:d.y,left:d.x})}},[e,s,a,r,n])}var Sgt=(0,Pe.createContext)({...jh,scaleX:1,scaleY:1}),TS;(function(t){t[t.Uninitialized=0]="Uninitialized",t[t.Initializing=1]="Initializing",t[t.Initialized=2]="Initialized"})(TS||(TS={}));var V1=(0,Pe.memo)(function(e){var n,r,o,i;let{id:s,accessibility:a,autoScroll:l=!0,children:c,sensors:u=Enn,collisionDetection:d=Vtn,measuring:f,modifiers:p,...m}=e,h=(0,Pe.useReducer)(Onn,void 0,Nnn),[g,y]=h,[w,v]=$tn(),[x,b]=(0,Pe.useState)(TS.Uninitialized),_=x===TS.Initialized,{draggable:{active:T,nodes:S,translate:P},droppable:{containers:A}}=g,O=T!=null?S.get(T):null,D=(0,Pe.useRef)({initial:null,translated:null}),$=(0,Pe.useMemo)(()=>{var hs;return T!=null?{id:T,data:(hs=O?.data)!=null?hs:Ann,rect:D}:null},[T,O]),B=(0,Pe.useRef)(null),[W,F]=(0,Pe.useState)(null),[Z,V]=(0,Pe.useState)(null),H=U1(m,Object.values(m)),te=OE("DndDescribedBy",s),fe=(0,Pe.useMemo)(()=>A.getEnabled(),[A]),me=Dnn(f),{droppableRects:j,measureDroppableContainers:G,measuringScheduled:J}=gnn(fe,{dragging:_,dependencies:[P.x,P.y],config:me.droppable}),M=mnn(S,T),E=(0,Pe.useMemo)(()=>Z?aQ(Z):null,[Z]),R=tD(),L=ynn(M,me.draggable.measure);$nn({activeNode:T!=null?S.get(T):null,config:R.layoutShiftCompensation,initialRect:L,measure:me.draggable.measure});let K=ogt(M,me.draggable.measure,L),Y=ogt(M?M.parentElement:null),re=(0,Pe.useRef)({activatorEvent:null,active:null,activeNode:M,collisionRect:null,collisions:null,droppableRects:j,draggableNodes:S,draggingNode:null,draggingNodeRect:null,droppableContainers:A,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ae=A.getNodeFor((n=re.current.over)==null?void 0:n.id),ve=Pnn({measure:me.dragOverlay.measure}),Te=(r=ve.nodeRef.current)!=null?r:M,Ee=_?(o=ve.rect)!=null?o:K:null,nt=!!(ve.nodeRef.current&&ve.rect),rt=xnn(nt?null:K),Jt=Cgt(Te?yu(Te):null),ke=bnn(_?ae??M:null),Ln=Tnn(ke),He=Lnn(p,{transform:{x:P.x-rt.x,y:P.y-rt.y,scaleX:1,scaleY:1},activatorEvent:Z,active:$,activeNodeRect:K,containerNodeRect:Y,draggingNodeRect:Ee,over:re.current.over,overlayNodeRect:ve.rect,scrollableAncestors:ke,scrollableAncestorRects:Ln,windowRect:Jt}),Ie=E?RE(E,P):null,dt=Cnn(ke),Me=sgt(dt),Ue=sgt(dt,[K]),it=RE(He,Me),St=Ee?Ktn(Ee,He):null,$r=$&&St?d({active:$,collisionRect:St,droppableRects:j,droppableContainers:fe,pointerCoordinates:Ie}):null,oo=$0e($r,"id"),[Bn,Tr]=(0,Pe.useState)(null),Px=nt?He:RE(He,Ue),Zi=Wtn(Px,(i=Bn?.rect)!=null?i:null,K),Hh=(0,Pe.useRef)(null),_d=(0,Pe.useCallback)((hs,Ta)=>{let{sensor:sl,options:If}=Ta;if(B.current==null)return;let jl=S.get(B.current);if(!jl)return;let Ji=hs.nativeEvent,xu=new sl({active:B.current,activeNode:jl,event:Ji,options:If,context:re,onAbort(Xi){if(!S.get(Xi))return;let{onDragAbort:gt}=H.current,Je={id:Xi};gt?.(Je),w({type:"onDragAbort",event:Je})},onPending(Xi,Pf,gt,Je){if(!S.get(Xi))return;let{onDragPending:ge}=H.current,ht={id:Xi,constraint:Pf,initialCoordinates:gt,offset:Je};ge?.(ht),w({type:"onDragPending",event:ht})},onStart(Xi){let Pf=B.current;if(Pf==null)return;let gt=S.get(Pf);if(!gt)return;let{onDragStart:Je}=H.current,xt={activatorEvent:Ji,active:{id:Pf,data:gt.data,rect:D}};(0,$E.unstable_batchedUpdates)(()=>{Je?.(xt),b(TS.Initializing),y({type:Ca.DragStart,initialCoordinates:Xi,active:Pf}),w({type:"onDragStart",event:xt}),F(Hh.current),V(Ji)})},onMove(Xi){y({type:Ca.DragMove,coordinates:Xi})},onEnd:Kh(Ca.DragEnd),onCancel:Kh(Ca.DragCancel)});Hh.current=xu;function Kh(Xi){return async function(){let{active:gt,collisions:Je,over:xt,scrollAdjustedTranslate:ge}=re.current,ht=null;if(gt&&ge){let{cancelDrop:ir}=H.current;ht={activatorEvent:Ji,active:gt,collisions:Je,delta:ge,over:xt},Xi===Ca.DragEnd&&typeof ir=="function"&&await Promise.resolve(ir(ht))&&(Xi=Ca.DragCancel)}B.current=null,(0,$E.unstable_batchedUpdates)(()=>{y({type:Xi}),b(TS.Uninitialized),Tr(null),F(null),V(null),Hh.current=null;let ir=Xi===Ca.DragEnd?"onDragEnd":"onDragCancel";if(ht){let Ef=H.current[ir];Ef?.(ht),w({type:ir,event:ht})}})}}},[S]),Q1=(0,Pe.useCallback)((hs,Ta)=>(sl,If)=>{let jl=sl.nativeEvent,Ji=S.get(If);if(B.current!==null||!Ji||jl.dndKit||jl.defaultPrevented)return;let xu={active:Ji};hs(sl,Ta.options,xu)===!0&&(jl.dndKit={capturedBy:Ta.sensor},B.current=If,_d(sl,Ta))},[S,_d]),zl=hnn(u,Q1);_nn(u),im(()=>{K&&x===TS.Initializing&&b(TS.Initialized)},[K,x]),(0,Pe.useEffect)(()=>{let{onDragMove:hs}=H.current,{active:Ta,activatorEvent:sl,collisions:If,over:jl}=re.current;if(!Ta||!sl)return;let Ji={active:Ta,activatorEvent:sl,collisions:If,delta:{x:it.x,y:it.y},over:jl};(0,$E.unstable_batchedUpdates)(()=>{hs?.(Ji),w({type:"onDragMove",event:Ji})})},[it.x,it.y]),(0,Pe.useEffect)(()=>{let{active:hs,activatorEvent:Ta,collisions:sl,droppableContainers:If,scrollAdjustedTranslate:jl}=re.current;if(!hs||B.current==null||!Ta||!jl)return;let{onDragOver:Ji}=H.current,xu=If.get(oo),Kh=xu&&xu.rect.current?{id:xu.id,rect:xu.rect.current,data:xu.data,disabled:xu.disabled}:null,Xi={active:hs,activatorEvent:Ta,collisions:sl,delta:{x:jl.x,y:jl.y},over:Kh};(0,$E.unstable_batchedUpdates)(()=>{Tr(Kh),Ji?.(Xi),w({type:"onDragOver",event:Xi})})},[oo]),im(()=>{re.current={activatorEvent:Z,active:$,activeNode:M,collisionRect:St,collisions:$r,droppableRects:j,draggableNodes:S,draggingNode:Te,draggingNodeRect:Ee,droppableContainers:A,over:Bn,scrollableAncestors:ke,scrollAdjustedTranslate:it},D.current={initial:Ee,translated:St}},[$,M,$r,St,S,Te,Ee,j,A,Bn,ke,it]),dnn({...R,delta:P,draggingRect:St,pointerCoordinates:Ie,scrollableAncestors:ke,scrollableAncestorRects:Ln});let zy=(0,Pe.useMemo)(()=>({active:$,activeNode:M,activeNodeRect:K,activatorEvent:Z,collisions:$r,containerNodeRect:Y,dragOverlay:ve,draggableNodes:S,droppableContainers:A,droppableRects:j,over:Bn,measureDroppableContainers:G,scrollableAncestors:ke,scrollableAncestorRects:Ln,measuringConfiguration:me,measuringScheduled:J,windowRect:Jt}),[$,M,K,Z,$r,Y,ve,S,A,j,Bn,G,ke,Ln,me,J,Jt]),eD=(0,Pe.useMemo)(()=>({activatorEvent:Z,activators:zl,active:$,activeNodeRect:K,ariaDescribedById:{draggable:te},dispatch:y,draggableNodes:S,over:Bn,measureDroppableContainers:G}),[Z,zl,$,K,y,te,S,Bn,G]);return Pe.default.createElement(cgt.Provider,{value:v},Pe.default.createElement(pQ.Provider,{value:eD},Pe.default.createElement(_gt.Provider,{value:zy},Pe.default.createElement(Sgt.Provider,{value:Zi},c)),Pe.default.createElement(Rnn,{disabled:a?.restoreFocus===!1})),Pe.default.createElement(Btn,{...a,hiddenTextDescribedById:te}));function tD(){let hs=W?.autoScrollEnabled===!1,Ta=typeof l=="object"?l.enabled===!1:l===!1,sl=_&&!hs&&!Ta;return typeof l=="object"?{...l,enabled:sl}:{enabled:sl}}}),Fnn=(0,Pe.createContext)(null),lgt="button",Unn="Draggable";function Tgt(t){let{id:e,data:n,disabled:r=!1,attributes:o}=t,i=OE(Unn),{activators:s,activatorEvent:a,active:l,activeNodeRect:c,ariaDescribedById:u,draggableNodes:d,over:f}=(0,Pe.useContext)(pQ),{role:p=lgt,roleDescription:m="draggable",tabIndex:h=0}=o??{},g=l?.id===e,y=(0,Pe.useContext)(g?Sgt:Fnn),[w,v]=IV(),[x,b]=IV(),_=Snn(s,e),T=U1(n);im(()=>(d.set(e,{id:e,key:i,node:w,activatorNode:x,data:T}),()=>{let P=d.get(e);P&&P.key===i&&d.delete(e)}),[d,e]);let S=(0,Pe.useMemo)(()=>({role:p,tabIndex:h,"aria-disabled":r,"aria-pressed":g&&p===lgt?!0:void 0,"aria-roledescription":m,"aria-describedby":u.draggable}),[r,p,h,g,m,u.draggable]);return{active:l,activatorEvent:a,activeNodeRect:c,attributes:S,isDragging:g,listeners:r?void 0:_,node:w,over:f,setNodeRef:v,setActivatorNodeRef:b,transform:y}}function Igt(){return(0,Pe.useContext)(_gt)}var Bnn="Droppable",znn={timeout:25};function Pgt(t){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:o}=t,i=OE(Bnn),{active:s,dispatch:a,over:l,measureDroppableContainers:c}=(0,Pe.useContext)(pQ),u=(0,Pe.useRef)({disabled:n}),d=(0,Pe.useRef)(!1),f=(0,Pe.useRef)(null),p=(0,Pe.useRef)(null),{disabled:m,updateMeasurementsFor:h,timeout:g}={...znn,...o},y=U1(h??r),w=(0,Pe.useCallback)(()=>{if(!d.current){d.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{c(Array.isArray(y.current)?y.current:[y.current]),p.current=null},g)},[g]),v=fQ({callback:w,disabled:m||!s}),x=(0,Pe.useCallback)((S,P)=>{v&&(P&&(v.unobserve(P),d.current=!1),S&&v.observe(S))},[v]),[b,_]=IV(x),T=U1(e);return(0,Pe.useEffect)(()=>{!v||!b.current||(v.disconnect(),d.current=!1,v.observe(b.current))},[b,v]),(0,Pe.useEffect)(()=>(a({type:Ca.RegisterDroppable,element:{id:r,key:i,disabled:n,node:b,rect:f,data:T}}),()=>a({type:Ca.UnregisterDroppable,key:i,id:r})),[r]),(0,Pe.useEffect)(()=>{n!==u.current.disabled&&(a({type:Ca.SetDroppableDisabled,id:r,key:i,disabled:n}),u.current.disabled=n)},[r,i,n,a]),{active:s,rect:f,isOver:l?.id===r,node:b,over:l,setNodeRef:_}}function yQ(t,e,n){let r=t.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function jnn(t,e){return t.reduce((n,r,o)=>{let i=e.get(r);return i&&(n[o]=i),n},Array(t.length))}function mQ(t){return t!==null&&t>=0}function Vnn(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Wnn(t){return typeof t=="boolean"?{draggable:t,droppable:t}:t}var Egt=t=>{let{rects:e,activeIndex:n,overIndex:r,index:o}=t,i=yQ(e,r,n),s=e[o],a=i[o];return!a||!s?null:{x:a.left-s.left,y:a.top-s.top,scaleX:a.width/s.width,scaleY:a.height/s.height}};var hQ={scaleX:1,scaleY:1},W1=t=>{var e;let{activeIndex:n,activeNodeRect:r,index:o,rects:i,overIndex:s}=t,a=(e=i[n])!=null?e:r;if(!a)return null;if(o===n){let c=i[s];return c?{x:0,y:n<s?c.top+c.height-(a.top+a.height):c.top-a.top,...hQ}:null}let l=Hnn(i,o,n);return o>n&&o<=s?{x:0,y:-a.height-l,...hQ}:o<n&&o>=s?{x:0,y:a.height+l,...hQ}:{x:0,y:0,...hQ}};function Hnn(t,e,n){let r=t[e],o=t[e-1],i=t[e+1];return r?n<e?o?r.top-(o.top+o.height):i?i.top-(r.top+r.height):0:i?i.top-(r.top+r.height):o?r.top-(o.top+o.height):0:0}var Agt="Sortable",kgt=ps.default.createContext({activeIndex:-1,containerId:Agt,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:Egt,disabled:{draggable:!1,droppable:!1}});function H1(t){let{children:e,id:n,items:r,strategy:o=Egt,disabled:i=!1}=t,{active:s,dragOverlay:a,droppableRects:l,over:c,measureDroppableContainers:u}=Igt(),d=OE(Agt,n),f=a.rect!==null,p=(0,ps.useMemo)(()=>r.map(_=>typeof _=="object"&&"id"in _?_.id:_),[r]),m=s!=null,h=s?p.indexOf(s.id):-1,g=c?p.indexOf(c.id):-1,y=(0,ps.useRef)(p),w=!Vnn(p,y.current),v=g!==-1&&h===-1||w,x=Wnn(i);im(()=>{w&&m&&u(p)},[w,p,m,u]),(0,ps.useEffect)(()=>{y.current=p},[p]);let b=(0,ps.useMemo)(()=>({activeIndex:h,containerId:d,disabled:x,disableTransforms:v,items:p,overIndex:g,useDragOverlay:f,sortedRects:jnn(p,l),strategy:o}),[h,d,x.draggable,x.droppable,v,p,g,l,f,o]);return ps.default.createElement(kgt.Provider,{value:b},e)}var Knn=t=>{let{id:e,items:n,activeIndex:r,overIndex:o}=t;return yQ(n,r,o).indexOf(e)},qnn=t=>{let{containerId:e,isSorting:n,wasDragging:r,index:o,items:i,newIndex:s,previousItems:a,previousContainerId:l,transition:c}=t;return!c||!r||a!==i&&o===s?!1:n?!0:s!==o&&e===l},Gnn={duration:200,easing:"ease"},Mgt="transform",Ynn=om.Transition.toString({property:Mgt,duration:0,easing:"linear"}),Znn={roleDescription:"sortable"};function Jnn(t){let{disabled:e,index:n,node:r,rect:o}=t,[i,s]=(0,ps.useState)(null),a=(0,ps.useRef)(n);return im(()=>{if(!e&&n!==a.current&&r.current){let l=o.current;if(l){let c=BE(r.current,{ignoreTransform:!0}),u={x:l.left-c.left,y:l.top-c.top,scaleX:l.width/c.width,scaleY:l.height/c.height};(u.x||u.y)&&s(u)}}n!==a.current&&(a.current=n)},[e,n,r,o]),(0,ps.useEffect)(()=>{i&&s(null)},[i]),i}function K1(t){let{animateLayoutChanges:e=qnn,attributes:n,disabled:r,data:o,getNewIndex:i=Knn,id:s,strategy:a,resizeObserverConfig:l,transition:c=Gnn}=t,{items:u,containerId:d,activeIndex:f,disabled:p,disableTransforms:m,sortedRects:h,overIndex:g,useDragOverlay:y,strategy:w}=(0,ps.useContext)(kgt),v=Xnn(r,p),x=u.indexOf(s),b=(0,ps.useMemo)(()=>({sortable:{containerId:d,index:x,items:u},...o}),[d,o,x,u]),_=(0,ps.useMemo)(()=>u.slice(u.indexOf(s)),[u,s]),{rect:T,node:S,isOver:P,setNodeRef:A}=Pgt({id:s,data:b,disabled:v.droppable,resizeObserverConfig:{updateMeasurementsFor:_,...l}}),{active:O,activatorEvent:D,activeNodeRect:$,attributes:B,setNodeRef:W,listeners:F,isDragging:Z,over:V,setActivatorNodeRef:H,transform:te}=Tgt({id:s,data:b,attributes:{...Znn,...n},disabled:v.draggable}),fe=Wht(A,W),me=!!O,j=me&&!m&&mQ(f)&&mQ(g),G=!y&&Z,J=G&&j?te:null,E=j?J??(a??w)({rects:h,activeNodeRect:$,activeIndex:f,overIndex:g,index:x}):null,R=mQ(f)&&mQ(g)?i({id:s,items:u,activeIndex:f,overIndex:g}):x,L=O?.id,K=(0,ps.useRef)({activeId:L,items:u,newIndex:R,containerId:d}),Y=u!==K.current.items,re=e({active:O,containerId:d,isDragging:Z,isSorting:me,id:s,index:x,items:u,newIndex:K.current.newIndex,previousItems:K.current.items,previousContainerId:K.current.containerId,transition:c,wasDragging:K.current.activeId!=null}),ae=Jnn({disabled:!re,index:x,node:S,rect:T});return(0,ps.useEffect)(()=>{me&&K.current.newIndex!==R&&(K.current.newIndex=R),d!==K.current.containerId&&(K.current.containerId=d),u!==K.current.items&&(K.current.items=u)},[me,R,d,u]),(0,ps.useEffect)(()=>{if(L===K.current.activeId)return;if(L!=null&&K.current.activeId==null){K.current.activeId=L;return}let Te=setTimeout(()=>{K.current.activeId=L},50);return()=>clearTimeout(Te)},[L]),{active:O,activeIndex:f,attributes:B,data:b,rect:T,index:x,newIndex:R,items:u,isOver:P,isSorting:me,isDragging:Z,listeners:F,node:S,overIndex:g,over:V,setNodeRef:fe,setActivatorNodeRef:H,setDroppableNodeRef:A,setDraggableNodeRef:W,transform:ae??E,transition:ve()};function ve(){if(ae||Y&&K.current.newIndex===x)return Ynn;if(!(G&&!PV(D)||!c)&&(me||re))return om.Transition.toString({...c,property:Mgt})}}function Xnn(t,e){var n,r;return typeof t=="boolean"?{draggable:t,droppable:!1}:{draggable:(n=t?.draggable)!=null?n:e.draggable,droppable:(r=t?.droppable)!=null?r:e.droppable}}function gQ(t){if(!t)return!1;let e=t.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}var Qnn=[_r.Down,_r.Right,_r.Up,_r.Left],wQ=(t,e)=>{let{context:{active:n,collisionRect:r,droppableRects:o,droppableContainers:i,over:s,scrollableAncestors:a}}=e;if(Qnn.includes(t.code)){if(t.preventDefault(),!n||!r)return;let l=[];i.getEnabled().forEach(d=>{if(!d||d!=null&&d.disabled)return;let f=o.get(d.id);if(f)switch(t.code){case _r.Down:r.top<f.top&&l.push(d);break;case _r.Up:r.top>f.top&&l.push(d);break;case _r.Left:r.left>f.left&&l.push(d);break;case _r.Right:r.left<f.left&&l.push(d);break}});let c=fgt({active:n,collisionRect:r,droppableRects:o,droppableContainers:l,pointerCoordinates:null}),u=$0e(c,"id");if(u===s?.id&&c.length>1&&(u=c[1].id),u!=null){let d=i.get(n.id),f=i.get(u),p=f?o.get(f.id):null,m=f?.node.current;if(m&&p&&d&&f){let g=NV(m).some((_,T)=>a[T]!==_),y=Ngt(d,f),w=ern(d,f),v=g||!y?{x:0,y:0}:{x:w?r.width-p.width:0,y:w?r.height-p.height:0},x={x:p.left,y:p.top};return v.x&&v.y?x:LE(x,v)}}}};function Ngt(t,e){return!gQ(t)||!gQ(e)?!1:t.data.current.sortable.containerId===e.data.current.sortable.containerId}function ern(t,e){return!gQ(t)||!gQ(e)||!Ngt(t,e)?!1:t.data.current.sortable.index<e.data.current.sortable.index}vt();var trn=[];function vQ({id:t,item:e,title:n,subtitle:r,badge:o,icon:i,isDraggable:s=!1,isExpandable:a=!1,defaultExpanded:l=!1,expandedContent:c,primaryAction:u,dropdownActions:d=trn,containerRef:f,className:p,onExpandToggle:m}){let[h,g]=(0,lo.useState)(l),{attributes:y,listeners:w,setNodeRef:v,transform:x,transition:b,isDragging:_}=K1({id:t,disabled:!s}),T={transform:om.Transform.toString(x),transition:b},S=()=>{if(a){let A=!h;g(A),m?.(A)}},P=d.length>0;return lo.default.createElement(wx,{ref:v,style:T,className:oe("tw-mb-2",_&&["tw-opacity-90","tw-shadow-lg","tw-border-accent/50","tw-relative","tw-z-[9999]","tw-bg-primary","tw-rounded-lg","tw-transform-gpu"],s&&"tw-touch-manipulation",p)},lo.default.createElement(vx,{className:"tw-p-3"},lo.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between"},s&&lo.default.createElement("div",{className:"tw-mr-2 tw-cursor-grab tw-touch-none active:tw-cursor-grabbing",...y,...w},lo.default.createElement(bm,{className:"tw-size-4"})),lo.default.createElement("div",{className:"tw-flex-1 tw-touch-auto",onClick:a?S:void 0,style:{cursor:a?"pointer":"default"}},lo.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},a&&lo.default.createElement("div",{className:"tw-flex tw-size-3 tw-items-center tw-justify-center"},h?lo.default.createElement(hr,{className:"tw-size-3 tw-stroke-[7]"}):lo.default.createElement(Di,{className:"tw-size-3 tw-stroke-[7]"})),i&&lo.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-center"},i),lo.default.createElement("div",{className:"tw-min-w-0 tw-flex-1"},lo.default.createElement("div",{className:"tw-break-words tw-font-medium tw-leading-relaxed"},n,o&&lo.default.createElement("span",{className:"tw-ml-1 tw-inline-flex tw-items-center"},o)),r&&lo.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},lo.default.createElement("span",{className:"tw-bg-secondary tw-text-sm tw-text-muted"},r))))),lo.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},u&&lo.default.createElement(X,{variant:"ghost",size:"icon",onClick:A=>{A.stopPropagation(),u.onClick(e)},title:u.tooltip},u.icon),P&&lo.default.createElement(xy,null,lo.default.createElement(by,{asChild:!0},lo.default.createElement(X,{variant:"ghost",size:"icon"},lo.default.createElement(lg,{className:"tw-size-4"}))),lo.default.createElement(sd,{align:"end",container:f?.current},d.map(A=>lo.default.createElement(wr,{key:A.label,onClick:O=>{O.stopPropagation(),A.onClick(e)},className:oe(A.variant==="destructive"&&"tw-text-error")},lo.default.createElement("span",{className:"tw-mr-2 tw-flex tw-size-4 tw-items-center tw-justify-center"},A.icon),A.label))))))),a&&lo.default.createElement("div",{className:oe("tw-transition-all tw-duration-300 tw-ease-in-out",h?"tw-max-h-96 tw-opacity-100":"tw-max-h-0 tw-overflow-hidden tw-opacity-0")},lo.default.createElement(xx,{className:"tw-p-3 tw-pt-0"},c)))}vt();var _a=N(U());Kt();var OV=_a.forwardRef(({className:t,...e},n)=>_a.createElement("div",{className:"tw-relative tw-w-full tw-overflow-auto"},_a.createElement("table",{ref:n,className:oe("tw-w-full tw-caption-bottom tw-border-collapse tw-text-sm",t),...e})));OV.displayName="Table";var RV=_a.forwardRef(({className:t,...e},n)=>_a.createElement("thead",{ref:n,className:oe("[&_tr]:tw-border-b",t),...e}));RV.displayName="TableHeader";var LV=_a.forwardRef(({className:t,...e},n)=>_a.createElement("tbody",{ref:n,className:t,...e}));LV.displayName="TableBody";var nrn=_a.forwardRef(({className:t,...e},n)=>_a.createElement("tfoot",{ref:n,className:oe("tw-border-t tw-font-medium tw-bg-primary-alt/50",t),...e}));nrn.displayName="TableFooter";var ES=_a.forwardRef(({className:t,...e},n)=>_a.createElement("tr",{ref:n,className:oe("tw-border-b tw-transition-colors hover:tw-bg-primary-alt/50 data-[state=selected]:tw-bg-primary-alt",t),...e}));ES.displayName="TableRow";var wu=_a.forwardRef(({className:t,...e},n)=>_a.createElement("th",{ref:n,className:oe("tw-h-10 tw-px-2 tw-text-left tw-align-middle tw-font-medium tw-text-muted [&:has([role=checkbox])]:tw-pr-0 [&>[role=checkbox]]:tw-translate-y-[2px]",t),...e}));wu.displayName="TableHead";var Ic=_a.forwardRef(({className:t,...e},n)=>_a.createElement("td",{ref:n,className:oe("tw-p-2 tw-align-middle [&:has([role=checkbox])]:tw-pr-0 [&>[role=checkbox]]:tw-translate-y-[2px]",t),...e}));Ic.displayName="TableCell";var rrn=_a.forwardRef(({className:t,...e},n)=>_a.createElement("caption",{ref:n,className:oe("tw-mt-4 tw-text-sm tw-text-muted",t),...e}));rrn.displayName="TableCaption";Kt();ye();Se();rD();bi();var ii=N(U());Kt();vt();var Ul=N(U());var Wo=N(U(),1);var $7r=!!(typeof window<"u"&&window.document&&window.document.createElement);function q1(t,e,{checkForDefaultPrevented:n=!0}={}){return function(o){if(t?.(o),n===!1||!o.defaultPrevented)return e?.(o)}}var Rgt=N(U(),1);function Ogt(t,e){if(typeof t=="function")return t(e);t!=null&&(t.current=e)}function F0e(...t){return e=>{let n=!1,r=t.map(o=>{let i=Ogt(o,e);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let o=0;o<r.length;o++){let i=r[o];typeof i=="function"?i():Ogt(t[o],null)}}}}function G1(...t){return Rgt.useCallback(F0e(...t),t)}var am=N(U(),1),U0e=N(Ve(),1);function Lgt(t,e){let n=am.createContext(e),r=i=>{let{children:s,...a}=i,l=am.useMemo(()=>a,Object.values(a));return(0,U0e.jsx)(n.Provider,{value:l,children:s})};r.displayName=t+"Provider";function o(i){let s=am.useContext(n);if(s)return s;if(e!==void 0)return e;throw new Error(`\`${i}\` must be used within \`${t}\``)}return[r,o]}function Dgt(t,e=[]){let n=[];function r(i,s){let a=am.createContext(s),l=n.length;n=[...n,s];let c=d=>{let{scope:f,children:p,...m}=d,h=f?.[t]?.[l]||a,g=am.useMemo(()=>m,Object.values(m));return(0,U0e.jsx)(h.Provider,{value:g,children:p})};c.displayName=i+"Provider";function u(d,f){let p=f?.[t]?.[l]||a,m=am.useContext(p);if(m)return m;if(s!==void 0)return s;throw new Error(`\`${d}\` must be used within \`${i}\``)}return[c,u]}let o=()=>{let i=n.map(s=>am.createContext(s));return function(a){let l=a?.[t]||i;return am.useMemo(()=>({[`__scope${t}`]:{...a,[t]:l}}),[a,l])}};return o.scopeName=t,[r,orn(o,...e)]}function orn(...t){let e=t[0];if(t.length===1)return e;let n=()=>{let r=t.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){let s=r.reduce((a,{useScope:l,scopeName:c})=>{let d=l(i)[`__scope${c}`];return{...a,...d}},{});return am.useMemo(()=>({[`__scope${e.scopeName}`]:s}),[s])}};return n.scopeName=e.scopeName,n}var B0e=N(U(),1);var $gt=N(U(),1),zE=globalThis?.document?$gt.useLayoutEffect:()=>{};var irn=B0e[" useId ".trim().toString()]||(()=>{}),srn=0;function xQ(t){let[e,n]=B0e.useState(irn());return zE(()=>{t||n(r=>r??String(srn++))},[t]),t||(e?`radix-${e}`:"")}var lm=N(U(),1);var bQ=N(U(),1);var arn=lm[" useInsertionEffect ".trim().toString()]||zE;function Fgt({prop:t,defaultProp:e,onChange:n=()=>{},caller:r}){let[o,i,s]=lrn({defaultProp:e,onChange:n}),a=t!==void 0,l=a?t:o;{let u=lm.useRef(t!==void 0);lm.useEffect(()=>{let d=u.current;d!==a&&console.warn(`${r} is changing from ${d?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=a},[a,r])}let c=lm.useCallback(u=>{if(a){let d=crn(u)?u(t):u;d!==t&&s.current?.(d)}else i(u)},[a,t,i,s]);return[l,c]}function lrn({defaultProp:t,onChange:e}){let[n,r]=lm.useState(t),o=lm.useRef(n),i=lm.useRef(e);return arn(()=>{i.current=e},[e]),lm.useEffect(()=>{o.current!==n&&(i.current?.(n),o.current=n)},[n,o]),[n,r,i]}function crn(t){return typeof t=="function"}var H7r=Symbol("RADIX:SYNC_STATE");var xd=N(U(),1);var Ugt=N(U(),1);function urn(t,e){return Ugt.useReducer((n,r)=>e[n][r]??n,t)}var DV=t=>{let{present:e,children:n}=t,r=drn(e),o=typeof n=="function"?n({present:r.isPresent}):xd.Children.only(n),i=G1(r.ref,frn(o));return typeof n=="function"||r.isPresent?xd.cloneElement(o,{ref:i}):null};DV.displayName="Presence";function drn(t){let[e,n]=xd.useState(),r=xd.useRef(null),o=xd.useRef(t),i=xd.useRef("none"),s=t?"mounted":"unmounted",[a,l]=urn(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return xd.useEffect(()=>{let c=CQ(r.current);i.current=a==="mounted"?c:"none"},[a]),zE(()=>{let c=r.current,u=o.current;if(u!==t){let f=i.current,p=CQ(c);t?l("MOUNT"):p==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&f!==p?"ANIMATION_OUT":"UNMOUNT"),o.current=t}},[t,l]),zE(()=>{if(e){let c,u=e.ownerDocument.defaultView??window,d=p=>{let h=CQ(r.current).includes(CSS.escape(p.animationName));if(p.target===e&&h&&(l("ANIMATION_END"),!o.current)){let g=e.style.animationFillMode;e.style.animationFillMode="forwards",c=u.setTimeout(()=>{e.style.animationFillMode==="forwards"&&(e.style.animationFillMode=g)})}},f=p=>{p.target===e&&(i.current=CQ(r.current))};return e.addEventListener("animationstart",f),e.addEventListener("animationcancel",d),e.addEventListener("animationend",d),()=>{u.clearTimeout(c),e.removeEventListener("animationstart",f),e.removeEventListener("animationcancel",d),e.removeEventListener("animationend",d)}}else l("ANIMATION_END")},[e,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:xd.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function CQ(t){return t?.animationName||"none"}function frn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var Bgt=N(U(),1),wrn=N(yo(),1);var Sa=N(U(),1);var _Q=N(Ve(),1);function SQ(t){let e=prn(t),n=Sa.forwardRef((r,o)=>{let{children:i,...s}=r,a=Sa.Children.toArray(i),l=a.find(hrn);if(l){let c=l.props.children,u=a.map(d=>d===l?Sa.Children.count(c)>1?Sa.Children.only(null):Sa.isValidElement(c)?c.props.children:null:d);return(0,_Q.jsx)(e,{...s,ref:o,children:Sa.isValidElement(c)?Sa.cloneElement(c,void 0,u):null})}return(0,_Q.jsx)(e,{...s,ref:o,children:i})});return n.displayName=`${t}.Slot`,n}function prn(t){let e=Sa.forwardRef((n,r)=>{let{children:o,...i}=n;if(Sa.isValidElement(o)){let s=yrn(o),a=grn(i,o.props);return o.type!==Sa.Fragment&&(a.ref=r?F0e(r,s):s),Sa.cloneElement(o,a)}return Sa.Children.count(o)>1?Sa.Children.only(null):null});return e.displayName=`${t}.SlotClone`,e}var mrn=Symbol("radix.slottable");function hrn(t){return Sa.isValidElement(t)&&typeof t.type=="function"&&"__radixId"in t.type&&t.type.__radixId===mrn}function grn(t,e){let n={...e};for(let r in e){let o=t[r],i=e[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...a)=>{let l=i(...a);return o(...a),l}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...t,...n}}function yrn(t){let e=Object.getOwnPropertyDescriptor(t.props,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning;return n?t.ref:(e=Object.getOwnPropertyDescriptor(t,"ref")?.get,n=e&&"isReactWarning"in e&&e.isReactWarning,n?t.props.ref:t.props.ref||t.ref)}var zgt=N(Ve(),1),vrn=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Y1=vrn.reduce((t,e)=>{let n=SQ(`Primitive.${e}`),r=Bgt.forwardRef((o,i)=>{let{asChild:s,...a}=o,l=s?n:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),(0,zgt.jsx)(l,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{});var Co=N(Ve(),1),IQ="Dialog",[jgt,mJr]=Dgt(IQ),[xrn,Vh]=jgt(IQ),Vgt=t=>{let{__scopeDialog:e,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=t,a=Wo.useRef(null),l=Wo.useRef(null),[c,u]=Fgt({prop:r,defaultProp:o??!1,onChange:i,caller:IQ});return(0,Co.jsx)(xrn,{scope:e,triggerRef:a,contentRef:l,contentId:xQ(),titleId:xQ(),descriptionId:xQ(),open:c,onOpenChange:u,onOpenToggle:Wo.useCallback(()=>u(d=>!d),[u]),modal:s,children:n})};Vgt.displayName=IQ;var Wgt="DialogTrigger",Hgt=Wo.forwardRef((t,e)=>{let{__scopeDialog:n,...r}=t,o=Vh(Wgt,n),i=G1(e,o.triggerRef);return(0,Co.jsx)(Y1.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":V0e(o.open),...r,ref:i,onClick:q1(t.onClick,o.onOpenToggle)})});Hgt.displayName=Wgt;var z0e="DialogPortal",[brn,Kgt]=jgt(z0e,{forceMount:void 0}),qgt=t=>{let{__scopeDialog:e,forceMount:n,children:r,container:o}=t,i=Vh(z0e,e);return(0,Co.jsx)(brn,{scope:e,forceMount:n,children:Wo.Children.map(r,s=>(0,Co.jsx)(DV,{present:n||i.open,children:(0,Co.jsx)(vh,{asChild:!0,container:o,children:s})}))})};qgt.displayName=z0e;var TQ="DialogOverlay",Ggt=Wo.forwardRef((t,e)=>{let n=Kgt(TQ,t.__scopeDialog),{forceMount:r=n.forceMount,...o}=t,i=Vh(TQ,t.__scopeDialog);return i.modal?(0,Co.jsx)(DV,{present:r||i.open,children:(0,Co.jsx)(_rn,{...o,ref:e})}):null});Ggt.displayName=TQ;var Crn=SQ("DialogOverlay.RemoveScroll"),_rn=Wo.forwardRef((t,e)=>{let{__scopeDialog:n,...r}=t,o=Vh(TQ,n);return(0,Co.jsx)(jv,{as:Crn,allowPinchZoom:!0,shards:[o.contentRef],children:(0,Co.jsx)(Y1.div,{"data-state":V0e(o.open),...r,ref:e,style:{pointerEvents:"auto",...r.style}})})}),jE="DialogContent",Ygt=Wo.forwardRef((t,e)=>{let n=Kgt(jE,t.__scopeDialog),{forceMount:r=n.forceMount,...o}=t,i=Vh(jE,t.__scopeDialog);return(0,Co.jsx)(DV,{present:r||i.open,children:i.modal?(0,Co.jsx)(Srn,{...o,ref:e}):(0,Co.jsx)(Trn,{...o,ref:e})})});Ygt.displayName=jE;var Srn=Wo.forwardRef((t,e)=>{let n=Vh(jE,t.__scopeDialog),r=Wo.useRef(null),o=G1(e,n.contentRef,r);return Wo.useEffect(()=>{let i=r.current;if(i)return I_(i)},[]),(0,Co.jsx)(Zgt,{...t,ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:q1(t.onCloseAutoFocus,i=>{i.preventDefault(),n.triggerRef.current?.focus()}),onPointerDownOutside:q1(t.onPointerDownOutside,i=>{let s=i.detail.originalEvent,a=s.button===0&&s.ctrlKey===!0;(s.button===2||a)&&i.preventDefault()}),onFocusOutside:q1(t.onFocusOutside,i=>i.preventDefault())})}),Trn=Wo.forwardRef((t,e)=>{let n=Vh(jE,t.__scopeDialog),r=Wo.useRef(!1),o=Wo.useRef(!1);return(0,Co.jsx)(Zgt,{...t,ref:e,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{t.onCloseAutoFocus?.(i),i.defaultPrevented||(r.current||n.triggerRef.current?.focus(),i.preventDefault()),r.current=!1,o.current=!1},onInteractOutside:i=>{t.onInteractOutside?.(i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));let s=i.target;n.triggerRef.current?.contains(s)&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}})}),Zgt=Wo.forwardRef((t,e)=>{let{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=t,a=Vh(jE,n),l=Wo.useRef(null),c=G1(e,l);return x_(),(0,Co.jsxs)(Co.Fragment,{children:[(0,Co.jsx)(Dv,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i,children:(0,Co.jsx)(mh,{role:"dialog",id:a.contentId,"aria-describedby":a.descriptionId,"aria-labelledby":a.titleId,"data-state":V0e(a.open),...s,ref:c,onDismiss:()=>a.onOpenChange(!1)})}),(0,Co.jsxs)(Co.Fragment,{children:[(0,Co.jsx)(Irn,{titleId:a.titleId}),(0,Co.jsx)(Ern,{contentRef:l,descriptionId:a.descriptionId})]})]})}),j0e="DialogTitle",Jgt=Wo.forwardRef((t,e)=>{let{__scopeDialog:n,...r}=t,o=Vh(j0e,n);return(0,Co.jsx)(Y1.h2,{id:o.titleId,...r,ref:e})});Jgt.displayName=j0e;var Xgt="DialogDescription",Qgt=Wo.forwardRef((t,e)=>{let{__scopeDialog:n,...r}=t,o=Vh(Xgt,n);return(0,Co.jsx)(Y1.p,{id:o.descriptionId,...r,ref:e})});Qgt.displayName=Xgt;var eyt="DialogClose",tyt=Wo.forwardRef((t,e)=>{let{__scopeDialog:n,...r}=t,o=Vh(eyt,n);return(0,Co.jsx)(Y1.button,{type:"button",...r,ref:e,onClick:q1(t.onClick,()=>o.onOpenChange(!1))})});tyt.displayName=eyt;function V0e(t){return t?"open":"closed"}var nyt="DialogTitleWarning",[hJr,ryt]=Lgt(nyt,{contentName:jE,titleName:j0e,docsSlug:"dialog"}),Irn=({titleId:t})=>{let e=ryt(nyt),n=`\`${e.contentName}\` requires a \`${e.titleName}\` for the component to be accessible for screen reader users.

If you want to hide the \`${e.titleName}\`, you can wrap it with our VisuallyHidden component.

For more information, see https://radix-ui.com/primitives/docs/components/${e.docsSlug}`;return Wo.useEffect(()=>{t&&(document.getElementById(t)||console.error(n))},[n,t]),null},Prn="DialogDescriptionWarning",Ern=({contentRef:t,descriptionId:e})=>{let r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${ryt(Prn).contentName}}.`;return Wo.useEffect(()=>{let o=t.current?.getAttribute("aria-describedby");e&&o&&(document.getElementById(e)||console.warn(r))},[r,t,e]),null},oyt=Vgt,iyt=Hgt,syt=qgt,W0e=Ggt,H0e=Ygt,K0e=Jgt,q0e=Qgt,ayt=tyt;vt();Kt();var PQ=oyt,lyt=iyt,krn=syt;var cyt=Ul.forwardRef(({className:t,...e},n)=>Ul.createElement(W0e,{ref:n,className:oe("tw-fixed tw-inset-0 tw-z-modal data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0","tw-bg-overlay/50",t),...e}));cyt.displayName=W0e.displayName;var $V=Ul.forwardRef(({className:t,children:e,container:n,...r},o)=>Ul.createElement(krn,{container:n},Ul.createElement(cyt,null),Ul.createElement(H0e,{ref:o,className:oe("tw-fixed tw-left-1/2 tw-top-1/2 tw-z-modal tw-grid tw-w-full tw-max-w-lg -tw-translate-x-1/2 -tw-translate-y-1/2 tw-gap-4 tw-border tw-bg-primary tw-p-6 tw-shadow-lg tw-duration-200 data-[state=open]:tw-animate-in data-[state=closed]:tw-animate-out data-[state=closed]:tw-fade-out-0 data-[state=open]:tw-fade-in-0 data-[state=closed]:tw-zoom-out-95 data-[state=open]:tw-zoom-in-95 data-[state=closed]:tw-slide-out-to-left-1/2 data-[state=closed]:tw-slide-out-to-top-[48%] data-[state=open]:tw-slide-in-from-left-1/2 data-[state=open]:tw-slide-in-from-top-[48%] sm:tw-rounded-lg",t),...r},e,Ul.createElement(ayt,{className:"clickable-icon tw-absolute tw-right-4 tw-top-4 tw-border-none tw-bg-transparent tw-text-faint tw-outline-none hover:tw-bg-transparent hover:tw-bg-opacity-100 hover:tw-text-normal focus-visible:tw-text-normal focus-visible:tw-outline-none focus-visible:tw-ring-0"},Ul.createElement(Sn,{className:"tw-size-4"}),Ul.createElement("span",{className:"tw-sr-only"},"Close")))));$V.displayName=H0e.displayName;var FV=({className:t,...e})=>Ul.createElement("div",{className:oe("tw-flex tw-flex-col tw-space-y-0.5 tw-text-center sm:tw-text-left",t),...e});FV.displayName="DialogHeader";var Mrn=({className:t,...e})=>Ul.createElement("div",{className:oe("tw-flex tw-flex-col-reverse sm:tw-flex-row sm:tw-justify-end sm:tw-space-x-2",t),...e});Mrn.displayName="DialogFooter";var UV=Ul.forwardRef(({className:t,...e},n)=>Ul.createElement(K0e,{ref:n,className:oe("tw-mt-0 tw-text-lg tw-font-semibold tw-leading-none tw-tracking-tight",t),...e}));UV.displayName=K0e.displayName;var BV=Ul.forwardRef(({className:t,...e},n)=>Ul.createElement(q0e,{ref:n,className:oe("tw-text-sm tw-text-muted",t),...e}));BV.displayName=q0e.displayName;qe();function $t(t){let{title:e,description:n,className:r,disabled:o}=t,{modalContainer:i}=SS(),s="onChange"in t?t.onChange:void 0,a=(0,ii.useMemo)(()=>{if(s)return Li(c=>{s(c)},1e3)},[s]),l=()=>{switch(t.type){case"text":case"number":return ii.default.createElement(Xn,{type:t.type,defaultValue:t.value,onChange:c=>{a?.(c.target.value)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"password":return ii.default.createElement(Fy,{value:t.value!==void 0?String(t.value):void 0,onChange:c=>{a?.(c)},placeholder:t.placeholder,disabled:o,className:"tw-w-full sm:tw-w-[200px]"});case"textarea":return ii.default.createElement(hf,{defaultValue:t.value,onChange:c=>{a?.(c.target.value)},placeholder:t.placeholder,rows:t.rows||3,disabled:o,className:"tw-min-h-[80px] tw-w-full sm:tw-w-[300px]"});case"switch":return ii.default.createElement(uh,{checked:t.checked,onCheckedChange:t.onCheckedChange,disabled:o});case"select":return ii.default.createElement("div",{className:"tw-group tw-relative tw-w-full sm:tw-w-[200px]"},ii.default.createElement("select",{value:t.value?.toString(),onChange:c=>t.onChange?.(c.target.value),disabled:o,className:oe("tw-w-full tw-appearance-none","tw-flex tw-h-9 tw-rounded-md tw-border tw-border-solid tw-border-border tw-bg-dropdown tw-px-3 tw-py-1 tw-pr-8","tw-text-sm !tw-shadow tw-transition-colors","focus:tw-outline-none focus:tw-ring-1 focus:tw-ring-ring","disabled:tw-cursor-not-allowed disabled:tw-opacity-50","hover:tw-bg-interactive-hover hover:tw-text-normal")},t.placeholder&&ii.default.createElement("option",{value:"",disabled:!0},t.placeholder),t.options.map(c=>ii.default.createElement("option",{key:c.value,value:c.value.toString()},c.label))),ii.default.createElement("div",{className:oe("tw-pointer-events-none tw-absolute tw-inset-y-0 tw-right-0 tw-flex tw-items-center tw-pr-2","tw-transition-colors group-hover:[&>svg]:tw-text-normal",o&&"tw-opacity-50")},ii.default.createElement(hr,{className:"tw-size-4"})));case"slider":return ii.default.createElement(fV,{value:t.value||0,onChange:t.onChange,min:t.min,max:t.max,step:t.step,suffix:t.suffix,disabled:o,className:"tw-w-full sm:tw-w-[300px]"});case"dialog":return ii.default.createElement(PQ,null,ii.default.createElement(lyt,{asChild:!0},t.trigger),ii.default.createElement($V,{container:i},(t.dialogTitle||t.dialogDescription)&&ii.default.createElement(FV,null,t.dialogTitle&&ii.default.createElement(UV,null,t.dialogTitle),t.dialogDescription&&ii.default.createElement(BV,null,t.dialogDescription)),t.children));case"custom":return t.children}};return ii.default.createElement("div",{className:oe("tw-flex tw-flex-col tw-items-start tw-justify-between tw-gap-4 tw-py-4 sm:tw-flex-row sm:tw-items-center","tw-w-full",r)},ii.default.createElement("div",{className:"tw-w-full tw-space-y-1.5 sm:tw-w-[300px]"},ii.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-leading-none"},e),n&&ii.default.createElement("div",{className:"tw-text-xs tw-text-muted"},n)),ii.default.createElement("div",{className:"tw-w-full tw-flex-1 sm:tw-flex sm:tw-justify-end"},l()))}var EQ=require("obsidian"),Nrn=({command:t,commands:e,onUpdate:n,onRemove:r,onCopy:o,containerRef:i})=>{let s=tr(),a=u=>{new g_(s,e,u,async f=>{await n(f,u.title)}).open()},l=[{icon:Ke.default.createElement(Bf,{className:"tw-size-4"}),label:"Edit",onClick:a},{icon:Ke.default.createElement(VA,{className:"tw-size-4"}),label:"Duplicate",onClick:o},{icon:Ke.default.createElement(ka,{className:"tw-size-4"}),label:"Delete",onClick:u=>{new Cr(s,()=>r(u),`Are you sure you want to delete the command "${u.title}"? This will permanently remove the command file and cannot be undone.`,"Delete Command","Delete","Cancel").open()},variant:"destructive"}],c=Ke.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-justify-around"},Ke.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-2"},Ke.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ke.default.createElement("span",{className:"tw-text-sm tw-font-medium"},"In Menu"),Ke.default.createElement(Nn,{content:Ke.default.createElement("div",{className:"tw-max-w-xs tw-text-xs"},"If enabled, the command will be available in the context menu when you right-click in the editor.")})),Ke.default.createElement(To,{checked:t.showInContextMenu,onCheckedChange:u=>{n({...t,showInContextMenu:u===!0},t.title)}})),Ke.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between  tw-gap-2"},Ke.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ke.default.createElement("span",{className:"tw-text-sm tw-font-medium"},"In Slash"),Ke.default.createElement(Nn,{content:Ke.default.createElement("div",{className:"tw-max-w-xs tw-text-xs"},"If enabled, the command will be available as a slash command in the chat.")})),Ke.default.createElement(To,{checked:t.showInSlashMenu,onCheckedChange:u=>n({...t,showInSlashMenu:u===!0},t.title)})));return Ke.default.createElement(vQ,{id:t.title,item:t,title:t.title,isDraggable:!0,isExpandable:!0,expandedContent:c,primaryAction:{icon:Ke.default.createElement(Bf,{className:"tw-size-4"}),onClick:a,tooltip:"Edit Command"},dropdownActions:l,containerRef:i})},Orn=({command:t,commands:e,onUpdate:n,onRemove:r,onCopy:o})=>{let i=tr(),{attributes:s,listeners:a,setNodeRef:l,transform:c,transition:u,isDragging:d}=K1({id:t.title}),f={transform:om.Transform.toString(c),transition:u},p=()=>{r(t)};return Ke.default.createElement(ES,{ref:l,style:f,className:oe("tw-transition-colors",d&&"tw-relative tw-z-[100] tw-cursor-grabbing tw-shadow-lg tw-backdrop-blur-sm tw-border-accent/50")},Ke.default.createElement(Ic,{className:"tw-w-10"},Ke.default.createElement("div",{...s,...a,className:"tw-flex tw-cursor-grab tw-items-center tw-justify-center"},Ke.default.createElement(bm,{className:"tw-size-4"}))),Ke.default.createElement(Ic,null,t.title),Ke.default.createElement(Ic,{className:"tw-text-center"},Ke.default.createElement(To,{checked:t.showInContextMenu,onCheckedChange:m=>{n({...t,showInContextMenu:m===!0},t.title)},className:"tw-mx-auto"})),Ke.default.createElement(Ic,{className:"tw-text-center"},Ke.default.createElement(To,{checked:t.showInSlashMenu,onCheckedChange:m=>n({...t,showInSlashMenu:m===!0},t.title),className:"tw-mx-auto"})),Ke.default.createElement(Ic,{className:"tw-text-center"},Ke.default.createElement("div",{className:"tw-flex tw-justify-center tw-space-x-1"},Ke.default.createElement(X,{variant:"ghost",size:"icon",onClick:()=>{new g_(i,e,t,async h=>{await n(h,t.title)}).open()}},Ke.default.createElement(Bf,{className:"tw-size-4"})),Ke.default.createElement(X,{variant:"ghost",size:"icon",onClick:()=>o(t),title:"Duplicate command"},Ke.default.createElement(VA,{className:"tw-size-4"})),Ke.default.createElement(X,{variant:"ghost",size:"icon",onClick:()=>{new Cr(i,p,`Are you sure you want to delete the command "${t.title}"? This will permanently remove the command file and cannot be undone.`,"Delete Command","Delete","Cancel").open()}},Ke.default.createElement(ka,{className:"tw-size-4"})))))},uyt=()=>{let t=tr(),e=G9(),n=(0,Ke.useMemo)(()=>Sj([...e]),[e]),r=Ht(),o=(0,Ke.useRef)(null),i=dQ(z1(PS,{activationConstraint:{distance:8}}),z1(IS,{coordinateGetter:wQ})),s=async(f,p)=>{await Xs.getInstance().updateCommand(f,p)},a=async f=>{await Xs.getInstance().createCommand(f)},l=async f=>{try{await Xs.getInstance().deleteCommand(f),new EQ.Notice(`Command "${f.title}" deleted successfully!`)}catch(p){throw z("Failed to delete command:",p),new EQ.Notice("Failed to delete command. Please try again."),p}},c=async f=>{try{let p=VJe(f.title,n),m={...f,title:p};await Xs.getInstance().createCommand(m,{autoOrder:!1})}catch(p){z("Failed to duplicate command:",p),new EQ.Notice("Failed to duplicate command. Please try again.")}},u=async f=>{let{active:p,over:m}=f;if(!m||p.id===m.id)return;let h=n.findIndex(v=>v.title===p.id),g=n.findIndex(v=>v.title===m.id);if(h===-1||g===-1)return;let y=[...n],[w]=y.splice(h,1);y.splice(g,0,w),await Xs.getInstance().reorderCommands(y)},d=()=>Ke.default.createElement("div",{className:"tw-relative md:tw-hidden"},Ke.default.createElement(V1,{sensors:i,collisionDetection:j1,onDragEnd:f=>void u(f)},Ke.default.createElement(H1,{items:n.map(f=>f.title),strategy:W1},Ke.default.createElement("div",{className:"tw-space-y-2"},n.length===0?Ke.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-bg-primary tw-p-8 tw-text-center tw-text-muted"},"No custom prompt files found."):n.map(f=>Ke.default.createElement(Nrn,{key:f.title,command:f,commands:n,onUpdate:s,onRemove:l,onCopy:c,containerRef:o}))))));return Ke.default.createElement("div",{className:"tw-space-y-4",ref:o},Ke.default.createElement("section",null,Ke.default.createElement("div",{className:"tw-mb-4 tw-flex tw-flex-col tw-gap-2"},Ke.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Custom Commands"),Ke.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Custom commands are preset prompts that you can trigger in the editor by right-clicking and selecting them from the context menu or by using a ",Ke.default.createElement("code",null,"/")," command in the chat to load them into your chat input.")),Ke.default.createElement($t,{type:"text",title:"Custom Prompts Folder Name",description:"Folder where custom prompts are stored",value:r.customPromptsFolder,onChange:f=>{pe("customPromptsFolder",f),Z9().catch(p=>z("loadAllCustomCommands failed",p))},placeholder:"copilot/copilot-custom-prompts"}),Ke.default.createElement($t,{type:"switch",title:"Custom Prompt Templating",description:"Process variables like {activenote}, {foldername}, or {#tag} in prompts. Disable for raw prompts.",checked:r.enableCustomPromptTemplating,onCheckedChange:f=>{pe("enableCustomPromptTemplating",f)}}),Ke.default.createElement($t,{type:"select",title:"Custom Prompts Sort Strategy",description:"Sort order for slash command menu prompts",value:r.promptSortStrategy,onChange:f=>pe("promptSortStrategy",f),options:[{label:"Recency",value:"timestamp"},{label:"Alphabetical",value:"alphabetical"},{label:"Manual",value:"manual"}]}),Ke.default.createElement("div",{className:"tw-mb-4 tw-flex tw-items-start tw-gap-2 tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-4 tw-text-muted"},Ke.default.createElement(Cm,{className:"tw-size-5"})," ",Ke.default.createElement("div",null,"Commands are automatically loaded from .md files in your custom prompts folder"," ",Ke.default.createElement("strong",null,r.customPromptsFolder),". Modifying the files will also update the command settings.")),Ke.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Ke.default.createElement("div",{className:"tw-flex tw-w-full tw-justify-between tw-gap-2 md:tw-justify-end"},Ke.default.createElement("div",null,Ke.default.createElement(X,{variant:"secondary",onClick:()=>new Cr(t,w0e,"This will add default commands to your custom prompts folder. Do you want to continue?","Generate Default Commands").open()},"Generate Default")),Ke.default.createElement(X,{variant:"default",className:"tw-gap-2",onClick:()=>{let f={...hy};new g_(t,n,f,async m=>{await a(m)}).open()}},Ke.default.createElement(Lc,{className:"tw-size-2 md:tw-size-4"}),"Add Cmd")),Ke.default.createElement("div",{className:"tw-hidden md:tw-block"},Ke.default.createElement(V1,{sensors:i,collisionDetection:j1,onDragEnd:f=>void u(f)},Ke.default.createElement(OV,null,Ke.default.createElement(RV,null,Ke.default.createElement(ES,null,Ke.default.createElement(wu,{className:"tw-w-10"}),Ke.default.createElement(wu,null,"Name"),Ke.default.createElement(wu,{className:"tw-w-24 tw-text-center"},Ke.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-center tw-gap-1"},"In Menu",Ke.default.createElement(Nn,{content:Ke.default.createElement("div",{className:"tw-max-w-xs tw-text-xs"},"If enabled, the command will be available in the context menu when you right-click in the editor.")}))),Ke.default.createElement(wu,{className:"tw-w-28 tw-text-center"},Ke.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-center tw-gap-1"},"Slash Cmd",Ke.default.createElement(Nn,{content:Ke.default.createElement("div",{className:"tw-max-w-xs tw-text-xs"},"If enabled, the command will be available as a slash command in the chat.")}))),Ke.default.createElement(wu,{className:"tw-w-32 tw-text-center"},"Actions"))),Ke.default.createElement(H1,{items:n.map(f=>f.title),strategy:W1},Ke.default.createElement(LV,null,n.length===0?Ke.default.createElement(ES,null,Ke.default.createElement(Ic,{colSpan:5,className:"tw-py-8 tw-text-center tw-text-muted"},"No custom prompt files found.")):n.map(f=>Ke.default.createElement(Orn,{key:f.title,command:f,commands:n,onUpdate:s,onRemove:l,onCopy:c}))))))),d())))};vt();var Sr=N(U());rn();bi();HS();ye();Se();vt();rn();ws();vt();var dyt=require("obsidian"),ko=N(U());function Rrn({onConfirm:t,onCancel:e}){let[n,r]=(0,ko.useState)(!1);return ko.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},ko.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-3 tw-text-normal"},ko.default.createElement(sw,{className:"tw-size-6 tw-shrink-0 tw-text-success"}),ko.default.createElement("h2",{className:"tw-m-0 tw-text-xl tw-font-bold"},"Migrate API Keys to Obsidian Keychain")),ko.default.createElement("p",{className:"tw-m-0 tw-text-muted"},"Move your API keys from ",ko.default.createElement("code",{className:"tw-text-muted tw-bg-muted/10"},"data.json")," to this device's"," ",ko.default.createElement("code",{className:"tw-text-accent tw-bg-muted/10"},"Obsidian Keychain"),"."," ",ko.default.createElement("code",null,"data.json")," will be stripped of API keys after migration."),ko.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-3 tw-rounded-md tw-border tw-border-border tw-bg-secondary tw-p-4"},ko.default.createElement(M$,{className:"tw-mt-0.5 tw-size-5 tw-shrink-0 tw-text-accent"}),ko.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-1 tw-text-small"},ko.default.createElement("div",{className:"tw-font-semibold tw-text-normal"},"Using Copilot on multiple devices?"),ko.default.createElement("div",{className:"tw-text-muted"},"Each device has its own Obsidian Keychain. Other devices syncing this vault will need to re-enter their API keys after migration."))),ko.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-2 tw-px-1 tw-text-small tw-text-muted"},ko.default.createElement(ug,{className:"tw-mt-0.5 tw-size-4 tw-shrink-0 tw-text-accent"}),ko.default.createElement("span",null,"Tip: keep an offline backup of your API keys.")),ko.default.createElement("label",{className:"tw-flex tw-cursor-pointer tw-items-center tw-gap-2"},ko.default.createElement("input",{type:"checkbox",checked:n,onChange:o=>r(o.target.checked),"aria-label":"I understand keys may need to be re-entered on other devices"}),ko.default.createElement("span",null,"I understand keys may need to be re-entered on other devices")),ko.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},ko.default.createElement(X,{variant:"secondary",onClick:e},"Cancel"),ko.default.createElement(X,{variant:"default",onClick:t,disabled:!n,className:"tw-gap-1.5"},ko.default.createElement(sw,{className:"tw-size-4"}),"Migrate")))}var AQ=class extends dyt.Modal{constructor(n,r,o){super(n);this.onConfirm=r;this.onCancel=o;this.root=null;this.confirmed=!1}onOpen(){let{contentEl:n}=this;this.root=sr(n,this.app);let r=()=>{this.confirmed=!0,this.onConfirm(),this.close()},o=()=>{this.close()};this.root.render(ko.default.createElement(Rrn,{onConfirm:r,onCancel:o}))}onClose(){this.confirmed||this.onCancel?.(),this.root?.unmount(),this.root=null}};var zV=require("obsidian"),nn=N(U());function fyt(t){return async e=>{let{plugins:n}=t,r=n.getPlugin("copilot");if(!r)throw new Error("Copilot plugin not found");await r.saveData(e)}}var pyt=()=>{let t=tr(),e=Ht(),n=V8(),[r,o]=(0,nn.useState)(!1),[i,s]=(0,nn.useState)(!1),a=vd.getInstance().isAvailable(),l=By(e),c=Rht()||!l&&CS(e),u=T0e(e),d=a?l?"active":c&&!u?"blocked":"standard":l?"stranded":"unavailable",f=d==="active"&&!CS(e),m=n.some(x=>x.title===e.defaultSystemPromptTitle)?e.defaultSystemPromptTitle:"",h=x=>{pe("defaultSystemPromptTitle",x)},g=()=>{if(!m)return;let x=Gp(m);t.setting.close(),t.workspace.openLinkText(x,"",!0)},y=()=>{new i4(t,n).open()},w=(0,nn.useCallback)(async()=>{if(!(r||!await new Promise(b=>{new Cr(t,()=>b(!0),"This will remove all API keys for this vault from the Obsidian Keychain, data.json, and memory. You will need to re-enter them.","\u26A0\uFE0F Forget All Secrets","Remove","Cancel",()=>b(!1)).open()}))){o(!0);try{let b=vd.getInstance(),_=fyt(t),T=!1;await I0e(()=>b.forgetAllSecrets(_,_V,S=>{Oht(S),T||eQ(),Ls(S)},()=>{T=!0}))}catch(b){z("Failed to forget secrets.",b),new zV.Notice("Failed to remove API keys. Please try again.")}finally{o(!1)}}},[t,r]),v=(0,nn.useCallback)(async()=>{if(!(i||!await new Promise(b=>{new AQ(t,()=>b(!0),()=>b(!1)).open()}))){s(!0);try{let b=fyt(t),_=await $ht(b);if(_.fieldsRequiringReentry.length>0){let T=_.fieldsRequiringReentry.map(S=>`  \u2022 ${S}`).join(`
`);new zV.Notice(`API keys moved to Obsidian Keychain.

${_.fieldsRequiringReentry.length} key(s) could not be decrypted and need to be re-entered:
${T}`,0)}else new zV.Notice("API keys moved to Obsidian Keychain.")}catch(b){z("Failed to migrate secrets to Obsidian Keychain.",b),new zV.Notice("Failed to migrate to Obsidian Keychain. Please try again.")}finally{s(!1)}}},[t,i]);return nn.default.createElement("div",{className:"tw-space-y-4"},nn.default.createElement("section",{className:"tw-space-y-4 tw-rounded-lg tw-border tw-p-4"},nn.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"User System Prompt"),nn.default.createElement($t,{type:"custom",title:"Default System Prompt",description:"Customize the system prompt for all messages, may result in unexpected behavior!"},nn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},nn.default.createElement(Ty,{value:m,onChange:x=>h(x.target.value),options:[{label:"None (use built-in prompt)",value:""},...n.map(x=>({label:x.title===e.defaultSystemPromptTitle?`${x.title} (Default)`:x.title,value:x.title}))],containerClassName:"tw-flex-1"}),nn.default.createElement(X,{variant:"ghost",size:"icon",onClick:g,className:"tw-size-5 tw-shrink-0 tw-p-0",title:"Open the source file",disabled:!m},nn.default.createElement(Oc,{className:"tw-size-5"})),nn.default.createElement(X,{variant:"default",size:"icon",onClick:y,title:"Add new prompt"},nn.default.createElement(Lc,{className:"tw-size-4"})))),nn.default.createElement($t,{type:"text",title:"System Prompts Folder Name",description:"Folder where system prompts are stored.",value:e.userSystemPromptsFolder,onChange:x=>pe("userSystemPromptsFolder",x),placeholder:"copilot/system-prompts"})),nn.default.createElement("section",{className:"tw-space-y-4 tw-rounded-lg tw-border tw-p-4"},nn.default.createElement("div",{className:"tw-text-xl tw-font-bold"},"Others"),nn.default.createElement($t,{type:"custom",title:"API Key Storage",description:d==="unavailable"?nn.default.createElement(nn.default.Fragment,null,"Update Obsidian to ",nn.default.createElement("code",null,"1.11.4+")," to enable the"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),". Keys are stored in ",nn.default.createElement("code",null,"data.json"),"."):d==="stranded"?nn.default.createElement(nn.default.Fragment,null,"This vault uses the"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),", but this Obsidian build cannot access it. Keys you enter here won't persist. Update Obsidian to ",nn.default.createElement("code",null,"1.11.4+"),", or re-enter keys on a supported device."):d==="active"?f?nn.default.createElement("span",{className:"tw-text-warning"},"No API keys found in this device's"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),". Re-enter your API keys in the relevant settings sections \u2014 this device's keychain is separate from other devices."):nn.default.createElement(nn.default.Fragment,null,"API keys are stored in this device's"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain"),"."):nn.default.createElement(nn.default.Fragment,null,"Your API keys are stored in ",nn.default.createElement("code",null,"data.json"),". Move them to the"," ",nn.default.createElement("strong",{className:"tw-font-semibold tw-text-normal"},"Obsidian Keychain")," for stronger protection.")},nn.default.createElement("div",{className:"tw-flex tw-flex-col tw-items-start tw-gap-2 sm:tw-items-end"},d==="active"&&nn.default.createElement("div",{className:"tw-inline-flex tw-items-center tw-gap-1.5 tw-rounded-md tw-bg-success tw-px-3 tw-py-1 tw-text-smallest tw-font-semibold tw-text-success"},nn.default.createElement(sw,{className:"tw-size-4"}),"Obsidian Keychain"),(d==="standard"||d==="blocked")&&nn.default.createElement("div",{className:"tw-inline-flex tw-items-center tw-gap-1.5 tw-rounded-md tw-border tw-border-border tw-bg-callout-warning/20 tw-px-3 tw-py-1 tw-text-smallest tw-font-semibold tw-text-warning"},nn.default.createElement(tb,{className:"tw-size-4"}),"Standard Storage"),d==="unavailable"&&nn.default.createElement("div",{className:"tw-inline-flex tw-items-center tw-gap-1.5 tw-rounded-md tw-border tw-border-border tw-bg-secondary tw-px-3 tw-py-1 tw-text-smallest tw-font-semibold tw-text-muted"},nn.default.createElement(ug,{className:"tw-size-4"}),"Unavailable"),d==="stranded"&&nn.default.createElement("div",{className:"tw-inline-flex tw-items-center tw-gap-1.5 tw-rounded-md tw-border tw-border-border tw-bg-callout-warning/20 tw-px-3 tw-py-1 tw-text-smallest tw-font-semibold tw-text-warning"},nn.default.createElement(ug,{className:"tw-size-4"}),"Obsidian Keychain unavailable"),d==="blocked"&&nn.default.createElement("div",{className:"tw-text-smallest tw-text-muted sm:tw-text-right"},"Save your settings once, then try again."),(d==="standard"||d==="blocked")&&c&&nn.default.createElement(X,{variant:"default",size:"sm",onClick:v,disabled:i||r||d!=="standard",className:"tw-gap-1.5"},nn.default.createElement(sw,{className:"tw-size-4"}),i?"Migrating...":"Migrate to Obsidian Keychain"),(l||c)&&nn.default.createElement(X,{variant:"destructive",size:"sm",onClick:w,disabled:r||i||d==="stranded",title:d==="stranded"?"Update Obsidian to 1.11.4+ (or open this vault on a device with Keychain access) to delete the Keychain entries.":void 0,className:"tw-gap-1.5"},nn.default.createElement(ka,{className:"tw-size-4"}),r?"Removing...":"Delete All Keys"))),nn.default.createElement($t,{type:"switch",title:"Debug Mode",description:"Debug mode will log some debug message to the console.",checked:e.debug,onCheckedChange:x=>pe("debug",x)}),nn.default.createElement($t,{type:"custom",title:"Create Log File",description:`Open the Copilot log file (${Ds.getLogPath()}) for easy sharing when reporting issues.`},nn.default.createElement(X,{variant:"secondary",size:"sm",onClick:()=>{(async()=>(await TG(),await Ds.flush(),await Ds.openLogFile()))()}},"Create Log File"))))};Qi();rn();It();bi();Kt();ns();Se();var Ms=N(U()),myt=require("obsidian");rn();ws();ns();Se();vt();function Lrn({onConfirm:t,onCancel:e}){let n=q();return Ms.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Ms.default.createElement("div",null,Ms.default.createElement("p",null,"Thanks for purchasing ",Ms.default.createElement("b",null,"Copilot Plus"),"! You have unlocked the full power of Copilot, featuring chat context, PDF and image support, exclusive chat and embedding models, and much more!"),Ms.default.createElement("p",null,"Would you like to apply the Copilot Plus settings now? You can always change this later in Settings."),Ms.default.createElement("ul",{className:"tw-pl-4"},Ms.default.createElement("li",null,"Default mode: ",Ms.default.createElement("b",{className:"tw-text-accent"},"Copilot Plus")),Ms.default.createElement("li",null,"Chat model: ",Ms.default.createElement("b",{className:"tw-text-accent"},rye)),Ms.default.createElement("li",null,Ms.default.createElement("div",null,"Embedding model:"," ",Ms.default.createElement("b",{className:"tw-text-accent"},oye)),n.embeddingModelKey!==iye&&Ms.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-text-sm tw-text-warning"},Ms.default.createElement(dl,{className:"tw-size-4"})," It will rebuild your embeddings for the entire vault")))),Ms.default.createElement("div",{className:"tw-flex tw-w-full tw-justify-end tw-gap-2"},Ms.default.createElement(X,{variant:"ghost",onClick:e},"Apply Later"),Ms.default.createElement(X,{variant:"default",onClick:t},"Apply Now")))}var kQ=class extends myt.Modal{constructor(e){super(e),this.setTitle("Welcome to Copilot Plus \u{1F680}")}onOpen(){let{contentEl:e}=this;this.root=sr(e,this.app);let n=()=>{M5e(),this.close()},r=()=>{this.close()};this.root.render(Ms.default.createElement(Lrn,{onConfirm:n,onCancel:r}))}onClose(){this.root.unmount()}};bi();rn();It();ns();Se();vt();var Ns=N(U());function hyt(){let t=tr(),e=Ht(),[n,r]=(0,Ns.useState)(null),[o,i]=(0,Ns.useState)(!1),s=ZN(),[a,l]=(0,Ns.useState)(e.plusLicenseKey);return Ns.default.createElement("section",{className:"tw-flex tw-flex-col tw-gap-4 tw-rounded-lg tw-bg-secondary tw-p-4"},Ns.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-between tw-gap-2 tw-text-xl tw-font-bold"},Ns.default.createElement("span",null,"Copilot Plus"),s&&Ns.default.createElement(ro,{variant:"outline",className:"tw-text-success"},"Active")),Ns.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 tw-text-sm tw-text-muted"},Ns.default.createElement("div",null,"Copilot Plus takes your Obsidian experience to the next level with cutting-edge AI capabilities. This premium tier unlocks advanced features:"," ",Ns.default.createElement("strong",null," ","including chat context, PDF and image support, web search integration, exclusive chat and embedding models, and much more.")),Ns.default.createElement("div",null,"Copilot Plus is evolving fast, with new features and improvements rolling out regularly. Join now to secure the lowest price and get early access!")),Ns.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ns.default.createElement(Fy,{className:"tw-w-full",placeholder:"Enter your license key",value:a,onChange:c=>{l(c)}}),Ns.default.createElement(X,{disabled:o,onClick:async()=>{pe("plusLicenseKey",a),i(!0);let c=await _p();i(!1),c?(r(null),new kQ(t).open()):r("Invalid license key")},className:"tw-min-w-10 tw-text-xs md:tw-text-sm"},o?Ns.default.createElement(Pr,{className:"tw-size-2 tw-animate-spin md:tw-size-4"}):"Apply"),Ns.default.createElement(X,{className:"tw-text-xs md:tw-text-sm",variant:"secondary",onClick:()=>hT(Vy.SETTINGS)},"Join Now ",Ns.default.createElement(rw,{className:"tw-size-2 md:tw-size-4"}))),Ns.default.createElement("div",{className:"tw-text-error"},n))}qe();Ky();vt();var jV=require("obsidian"),ze=N(U());rn();It();Se();rn();It();uz();Bve();Se();rn();ye();Se();It();Su();uz();ye();It();ye();var Drn={openai:t=>t.data?.map(e=>({id:e.id,name:e.id,provider:"openai"}))||[],google:t=>t.models?.map(e=>{let n=e.name.split("models/")?.[1];return{id:n,name:n,provider:"google"}})||[],anthropic:t=>t.data?.map(e=>({id:e.id,name:e.id,provider:"anthropic"}))||[],mistralai:t=>t.data?.map(e=>({id:e.id,name:e.id,provider:"mistralai"}))||[],cohereai:t=>t.models?.map(e=>({id:e.name,name:e.name,provider:"cohereai"}))||[],deepseek:t=>t.data?.map(e=>({id:e.id,name:e.id,provider:"deepseek"}))||[],groq:t=>t.data?.map(e=>({id:e.id,name:e.id,provider:"groq"}))||[],xai:t=>t.data?.map(e=>({id:e.id,name:e.id,provider:"xai"}))||[],"amazon-bedrock":t=>[],openrouterai:t=>t.data?.map(e=>({id:e.id,name:e.id,provider:"openrouterai"}))||[],siliconflow:t=>t.data?.map(e=>({id:e.id,name:e.id,provider:"siliconflow"}))||[],"github-copilot":t=>t.data?.map(e=>({id:e.id,name:e.id,provider:"github-copilot"}))||[]},bd=(t,e)=>typeof t=="string"&&t.length>0?t:typeof t=="number"?String(t):e,$rn=t=>e=>e.data&&Array.isArray(e.data)?e.data.map(n=>({id:bd(n.id,"")||bd(n.name,String(Math.random())),name:bd(n.name,"")||bd(n.id,"")||bd(n.display_name,"Unknown Model"),provider:t})):e.models&&Array.isArray(e.models)?e.models.map(n=>({id:bd(n.id,"")||bd(n.name,String(Math.random())),name:bd(n.name,"")||bd(n.displayName,"")||bd(n.id,"Unknown Model"),provider:t})):Array.isArray(e)?e.map(n=>({id:bd(n.id,"")||bd(n.name,String(Math.random())),name:bd(n.name,"")||bd(n.id,"Unknown Model"),provider:t})):[],Frn=t=>Drn[t]||$rn(t),G0e=(t,e)=>{let n=Frn(t);try{return n(e)}catch(r){return z(`Error parsing ${t} model data:`,r),[]}};qe();VS();async function gyt(t){try{if(t==="github-copilot"){let l=await sh.getInstance().listModels();return{success:!0,models:G0e(t,l)}}let e=Ad(t);if(!e)return{success:!1,models:[],error:"API key not configured"};if(e=await pn(e),!e)return{success:!1,models:[],error:"Failed to decrypt API key"};let n=ew(t).listModelURL;if(!n)return{success:!1,models:[],error:"Provider does not support model listing"};let r={Authorization:`Bearer ${e}`};t==="google"?(n+=`?key=${e}`,r={}):t==="anthropic"&&(r={"x-api-key":e,"anthropic-version":"2023-06-01"});let o=await Promise.race([fo(n,{headers:r,method:"GET"}),new Promise((a,l)=>window.setTimeout(()=>l(new Error("Request timed out after 10s")),1e4))]);if(!o.ok){let a=Xt(await o.json());throw z(a),new Error(`Failed to fetch models: ${o.statusText} 
 detail: `+a)}let i=await o.json();return{success:!0,models:G0e(t,i)}}catch(e){return z(`Error fetching models for ${t}:`,e),{success:!1,models:[],error:Xt(e)}}}async function yyt(t,e,n){let r=n?.skipVerification??!1,i=!!e.find(u=>u.name===t.name&&u.provider===t.provider),s=t.provider==="github-copilot"?void 0:Ad(t.provider),a={name:t.name,provider:t.provider,apiKey:s,enabled:!0},l=!1,c;if(!r)try{await Sl.instance.getCurrentChainManager().chatModelManager.ping(a)}catch(u){if(l=!0,c=Xt(u),a.provider==="github-copilot"&&c.toLowerCase().includes("not supported")){let d=sh.getInstance().getPolicyTerms(t.id);d&&(c+=`

${d}`)}z("Model verification failed:",u)}return{success:!0,alreadyExists:i,verificationFailed:l,verificationError:c}}function wyt(t){return{name:t.name,provider:t.provider,enabled:!0}}qe();vt();var Tx=require("obsidian"),co=N(U());function Urn(t){return t.split(/\n\n+/).map((n,r)=>{let i=n.split(/(\[[^\]]+\]\([^)]+\))/g).map((s,a)=>{let l=s.match(/^\[([^\]]+)\]\(([^)]+)\)$/);return l?co.default.createElement("a",{key:a,href:l[2],target:"_blank",rel:"noopener noreferrer",className:"tw-underline"},l[1]):s});return co.default.createElement("p",{key:r,className:r>0?"tw-mt-1":""},i)})}function MQ({provider:t,isReady:e,expanded:n=!1,skipVerification:r=!1,credentialVersion:o}){let i=Ht(),[s,a]=(0,co.useState)(null),[l,c]=(0,co.useState)(!1),[u,d]=(0,co.useState)(null),[f,p]=(0,co.useState)(null),[m,h]=(0,co.useState)(!1),[g,y]=(0,co.useState)(null),w=(0,co.useRef)(!1),v=(0,co.useCallback)(async()=>{if(!(w.current||!e)){w.current=!0,c(!0),d(null);try{let _=await gyt(t);_.success?a(_.models):(d(_.error||"Failed to load models"),new Tx.Notice(`Failed to load models for ${cl(t)}: ${_.error}`,5e3))}catch(_){let T=Xt(_);d(T),new Tx.Notice(`Failed to load models for ${cl(t)}: ${T}`,5e3)}finally{c(!1),w.current=!1}}},[t,e]);(0,co.useEffect)(()=>{n&&e&&s===null&&!l&&!u&&v()},[n,e,s,l,u,v]);let x=async()=>{if(!f){new Tx.Notice("Please select a model first");return}h(!0),y(null);try{let _=await yyt({id:f.id,name:f.name,provider:t},i.activeModels,{skipVerification:r});if(_.alreadyExists)_.verificationFailed?(y(_.verificationError??null),new Tx.Notice(`Model ${f.name} already exists (verification failed: ${_.verificationError})`,1e4)):new Tx.Notice(`Model ${f.name} verified successfully! It already exists in your models list.`);else{let T=wyt({id:f.id,name:f.name,provider:t}),S=[...i.activeModels,T];pe("activeModels",S),_.verificationFailed?(y(_.verificationError??null),new Tx.Notice(`Model ${f.name} added (verification failed: ${_.verificationError})`,1e4)):new Tx.Notice(`Model ${f.name} verified and added to your models list!`)}}catch(_){z("Error adding model:",_),new Tx.Notice(`Failed to add model: ${Xt(_)}`)}finally{h(!1)}},b=s?.filter((_,T,S)=>S.findIndex(P=>P.id===_.id)===T).sort((_,T)=>_.name.localeCompare(T.name));return co.default.createElement(Zn,{label:"Model",description:"Add the selected model to your models list. After adding, check the Model Tab."},co.default.createElement("div",null,co.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},co.default.createElement("div",{className:"tw-flex-1"},co.default.createElement(Ty,{options:b?.map(_=>({label:_.name,value:_.id}))||[],onChange:_=>{let T=_.target.value,S=s?.find(P=>P.id===T);S&&(p(S),y(null))},onClick:()=>{s===null&&!l&&v()},value:f?.id||"",placeholder:"Select Model",disabled:!e||l})),co.default.createElement("div",{className:"tw-w-[72px]"},co.default.createElement(X,{onClick:x,disabled:!f||m,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},m?co.default.createElement(Pr,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}):"Add"))),co.default.createElement("div",{className:"tw-mt-1 tw-text-xs"},l&&co.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Loading models..."),u&&co.default.createElement("div",{className:"tw-p-1 tw-text-error"},"Failed to load models. ",u),s&&s.length===0&&co.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"No models available."),s===null&&!l&&!u&&co.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Click to load available models."),g&&co.default.createElement("div",{className:"tw-mt-2 tw-rounded-md tw-border tw-border-border tw-p-2 tw-text-error tw-bg-modifier-error/10"},Urn(g)))))}vt();var VE=require("obsidian"),Nt=N(U());function vyt(){let t=Ht(),[e]=(0,Nt.useState)(()=>sh.getInstance()),[n,r]=(0,Nt.useState)(()=>e.getAuthState().status==="authenticated"?"done":"idle"),[o,i]=(0,Nt.useState)(null),[s,a]=(0,Nt.useState)(0),[l,c]=(0,Nt.useState)(null),[u,d]=(0,Nt.useState)(!1),f=(0,Nt.useRef)(0),p=(0,Nt.useRef)(!0),[m,h]=(0,Nt.useState)({token:t.githubCopilotToken,accessToken:t.githubCopilotAccessToken,expiresAt:t.githubCopilotTokenExpiresAt});(m.token!==t.githubCopilotToken||m.accessToken!==t.githubCopilotAccessToken||m.expiresAt!==t.githubCopilotTokenExpiresAt)&&(h({token:t.githubCopilotToken,accessToken:t.githubCopilotAccessToken,expiresAt:t.githubCopilotTokenExpiresAt}),e.getAuthState().status==="authenticated"?n!=="pending"&&n!=="polling"&&r("done"):n==="done"&&r("idle")),(0,Nt.useEffect)(()=>(p.current=!0,()=>{p.current=!1,f.current+=1,e.abortPolling()}),[e]);let g=async(S,P)=>{await e.pollForAccessToken(S.deviceCode,S.interval,S.expiresIn,A=>{p.current&&P===f.current&&a(A)}),await e.fetchCopilotToken(),!(!p.current||P!==f.current)&&(r("done"),i(null),new VE.Notice("GitHub Copilot connected successfully!"))},y=async()=>{let S=++f.current;r("pending"),c(null),a(0);try{let P=await e.startDeviceCodeFlow();if(!p.current||S!==f.current)return;i(P),r("polling"),d(!0);try{await g(P,S)}catch(A){if(!p.current||S!==f.current||Uve(A))return;throw A}}catch(P){if(!p.current||S!==f.current)return;let A=P instanceof Error?P.message:String(P);c(A),r("error"),new VE.Notice(`Authentication failed: ${A}`)}},w=()=>{let S=n==="pending"||n==="polling"||n==="error"&&o;f.current+=1,e.resetAuth(),r("idle"),i(null),c(null),a(0),d(!1),new VE.Notice(S?"Authentication cancelled":"GitHub Copilot disconnected")},v=async S=>{try{await navigator.clipboard.writeText(S),new VE.Notice("Copied to clipboard!")}catch{new VE.Notice("Failed to copy to clipboard")}},x=n==="done",b=n==="pending"||n==="polling",_=(n==="polling"||n==="error")&&o!==null,T=async()=>{if(!o)return;let S=++f.current;r("polling"),c(null),a(0);try{await g(o,S)}catch(P){if(!p.current||S!==f.current||Uve(P))return;let A=P instanceof Error?P.message:String(P);c(A),r("error"),new VE.Notice(`Authentication failed: ${A}`)}};return Nt.default.createElement(Nt.default.Fragment,null,Nt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},Nt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1 tw-font-medium"},Nt.default.createElement("div",{className:"tw-truncate"},"GitHub Copilot"),Nt.default.createElement(Nn,{content:Nt.default.createElement("div",{className:"tw-max-w-[250px]"},Nt.default.createElement("div",{className:"tw-font-semibold"},"Unofficial Integration"),Nt.default.createElement("p",{className:"tw-mt-1"},"This uses GitHub Copilot's internal API, which is not officially supported for third-party apps. It may stop working at any time.")),side:"bottom"},Nt.default.createElement("span",{className:"tw-cursor-help tw-text-warning"},"\u26A0\uFE0F"))),Nt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 sm:tw-flex-row sm:tw-items-center"},Nt.default.createElement("div",{className:`tw-flex tw-h-9 tw-flex-1 tw-items-center tw-rounded-md tw-border tw-border-border tw-px-3 tw-text-sm ${x?"tw-text-success":b?"tw-text-warning":n==="error"?"tw-text-error":"tw-text-muted"}`},x?"\u2713 Connected":b?"Authenticating...":n==="error"?"Error - Click Setup to retry":"Not connected"),Nt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},x&&Nt.default.createElement(X,{onClick:w,variant:"ghost",className:"tw-flex tw-flex-1 tw-items-center tw-justify-center tw-whitespace-nowrap tw-px-4 tw-py-2 tw-text-warning hover:tw-text-warning sm:tw-flex-none"},"Disconnect"),Nt.default.createElement(X,{onClick:()=>{!x&&!b?y():d(!u)},disabled:b,variant:"secondary",className:"tw-flex tw-flex-1 tw-items-center tw-justify-center tw-gap-2 tw-whitespace-nowrap tw-px-4 tw-py-2 sm:tw-flex-none"},b?Nt.default.createElement(Pr,{className:"tw-size-4 tw-animate-spin"}):x?Nt.default.createElement(Nt.default.Fragment,null,"Add Model",u?Nt.default.createElement($s,{className:"tw-ml-1 tw-size-4"}):Nt.default.createElement(hr,{className:"tw-ml-1 tw-size-4"})):"Setup"))),Nt.default.createElement("div",null,Nt.default.createElement("a",{href:"https://github.com/settings/apps/authorizations",target:"_blank",rel:"noopener noreferrer",className:"tw-text-[10px] tw-text-accent hover:tw-text-accent-hover sm:tw-text-xs"},"Manage GitHub Authorizations"))),Nt.default.createElement(cs,{open:u},Nt.default.createElement(us,{className:"tw-rounded-md tw-p-3"},Nt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},_&&o&&Nt.default.createElement("div",{className:"tw-space-y-2.5 tw-rounded-lg tw-border tw-border-border tw-p-3.5 tw-bg-muted/10"},Nt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-text-xs"},Nt.default.createElement("span",{className:"tw-font-semibold"},"1."),Nt.default.createElement("span",{className:"tw-text-muted"},"Go to:"),Nt.default.createElement("a",{href:o.verificationUri,target:"_blank",rel:"noopener noreferrer",className:"tw-break-all tw-text-accent tw-underline hover:tw-text-accent-hover"},o.verificationUri),Nt.default.createElement(X,{variant:"ghost",size:"sm",onClick:()=>v(o.verificationUri),className:"tw-size-5 tw-shrink-0 tw-p-0",title:"Copy URL"},Nt.default.createElement(Eu,{className:"tw-size-3.5"}))),Nt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2 tw-text-xs"},Nt.default.createElement("span",{className:"tw-font-semibold"},"2."),Nt.default.createElement("span",{className:"tw-text-muted"},"Enter code:"),Nt.default.createElement("code",{className:"tw-rounded-md tw-border-border tw-px-3 tw-py-1.5 tw-font-mono tw-text-base tw-font-bold tw-tracking-widest tw-bg-accent/10 tw-border-accent/30"},o.userCode),Nt.default.createElement(X,{variant:"ghost",size:"sm",onClick:()=>v(o.userCode),className:"tw-size-5 tw-shrink-0 tw-p-0",title:"Copy code"},Nt.default.createElement(Eu,{className:"tw-size-3.5"}))),Nt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 tw-border-t tw-pt-2 tw-border-border/50"},n==="polling"?Nt.default.createElement(Nt.default.Fragment,null,Nt.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-center tw-gap-2 tw-py-1 tw-text-xs tw-text-muted"},Nt.default.createElement(Pr,{className:"tw-size-3.5 tw-animate-spin"}),Nt.default.createElement("span",null,"Waiting for authorization...",s>0&&` (Attempt ${s})`)),Nt.default.createElement(X,{onClick:w,variant:"ghost",size:"sm",className:"tw-w-full"},"Cancel")):Nt.default.createElement(Nt.default.Fragment,null,Nt.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-center tw-gap-2 tw-py-1 tw-text-xs tw-text-error"},Nt.default.createElement("span",null,"Polling failed - you can retry with the same code")),Nt.default.createElement("div",{className:"tw-flex tw-gap-2"},Nt.default.createElement(X,{onClick:T,variant:"secondary",size:"sm",className:"tw-flex-1"},"Retry"),Nt.default.createElement(X,{onClick:w,variant:"ghost",size:"sm",className:"tw-flex-1"},"Start Over"))))),x&&Nt.default.createElement(MQ,{provider:"github-copilot",isReady:x,expanded:u,credentialVersion:t.githubCopilotToken}),l&&Nt.default.createElement("div",{className:"tw-rounded-lg tw-border tw-border-border tw-p-3.5 tw-text-xs tw-text-error tw-bg-muted/10"},l)))))}rn();It();ye();Se();qe();vt();var Ix=require("obsidian"),dr=N(U());function xyt(t){return t.trim().replace(/\/+$/,"").replace(/\/v1$/i,"")}async function Brn(t,e){let n=xyt(t);return e==="ollama"?((await(0,Ix.requestUrl)({url:`${n}/api/tags`,method:"GET"})).json?.models||[]).map(a=>({id:a.name,name:a.name})):((await(0,Ix.requestUrl)({url:`${n}/v1/models`,method:"GET"})).json?.data||[]).map(i=>({id:i.id,name:i.id}))}function zrn({service:t,expanded:e,onToggleExpand:n}){let r=Ht(),[o,i]=(0,dr.useState)(t.url),[s,a]=(0,dr.useState)(null),[l,c]=(0,dr.useState)(!1),[u,d]=(0,dr.useState)(null),[f,p]=(0,dr.useState)(""),[m,h]=(0,dr.useState)(!1),g=async()=>{c(!0),d(null);try{let v=await Brn(o,t.kind);a(v)}catch(v){z(`Error fetching models for ${t.name}:`,v),d(Xt(v)),a(null)}finally{c(!1)}},y=()=>{n(),!e&&!s&&!l&&g()},w=async()=>{if(!f||!s)return;let v=s.find(_=>_.id===f);if(!v)return;h(!0);let x=!1,b="";try{let _=t.kind,T=xyt(o),S=t.kind==="ollama"?T:`${T}/v1`,P={name:v.name,provider:_,baseUrl:S,enabled:!0};try{await Sl.instance.getCurrentChainManager().chatModelManager.ping(P)}catch(O){x=!0,b=Xt(O),z("Model verification failed:",O)}r.activeModels.find(O=>O.name===P.name&&O.provider===P.provider)?x?new Ix.Notice(`Model ${v.name} already exists (verification failed: ${b})`,5e3):new Ix.Notice(`Model ${v.name} already exists.`):(pe("activeModels",[...r.activeModels,P]),x?new Ix.Notice(`Model ${v.name} added (verification failed: ${b})`,5e3):new Ix.Notice(`Model ${v.name} added!`))}catch(_){new Ix.Notice(`Failed to add model: ${Xt(_)}`)}finally{h(!1)}};return dr.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},dr.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},dr.default.createElement("div",{className:"tw-truncate"},t.name)),dr.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},dr.default.createElement("div",{className:"tw-flex-1"},dr.default.createElement(Xn,{className:"tw-max-w-full",value:o,onChange:v=>{i(v.target.value),a(null),p(""),d(null)}})),dr.default.createElement("div",null,dr.default.createElement(X,{onClick:y,variant:"secondary",className:"tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-2 tw-whitespace-nowrap tw-px-4 tw-py-2"},"Add Model",e?dr.default.createElement($s,{className:"tw-ml-1 tw-size-4"}):dr.default.createElement(hr,{className:"tw-ml-1 tw-size-4"})))),dr.default.createElement(cs,{open:e,className:"tw-mt-2"},dr.default.createElement(us,{className:"tw-rounded-md tw-p-3"},dr.default.createElement(Zn,{label:"Model",description:"Add the currently selected model to model List."},dr.default.createElement("div",null,dr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},dr.default.createElement("div",{className:"tw-flex-1"},dr.default.createElement(Ty,{options:s?[...s].sort((v,x)=>v.name.localeCompare(x.name)).map(v=>({label:v.name,value:v.id})):[],onChange:v=>p(v.target.value),value:f,placeholder:"Select Model",disabled:l||!!u})),dr.default.createElement("div",{className:"tw-w-[72px]"},dr.default.createElement(X,{onClick:w,disabled:!f||m,variant:"secondary",size:"sm",className:"tw-w-full tw-whitespace-nowrap"},m?dr.default.createElement(Pr,{className:"tw-size-4 tw-animate-spin"}):"Add"))),dr.default.createElement("div",{className:"tw-mt-1 tw-text-xs"},l&&dr.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"Loading models..."),u&&dr.default.createElement("div",{className:"tw-p-1 tw-text-error"},"Failed: ",u),s&&s.length===0&&dr.default.createElement("div",{className:"tw-p-1 tw-text-muted"},"No models found.")))))))}function byt(){let[t,e]=(0,dr.useState)(null),n=[{id:"ollama",name:"Ollama",url:"http://localhost:11434",kind:"ollama"},{id:"lm-studio",name:"LM Studio",url:"http://localhost:1234",kind:"lm-studio"}];return dr.default.createElement("div",{className:"tw-mt-6 tw-border-t tw-border-border tw-pt-4"},dr.default.createElement("div",{className:"tw-mb-3"},dr.default.createElement("h3",{className:"tw-m-0 tw-text-base tw-font-bold"},"Local Services"),dr.default.createElement("div",{className:"tw-mt-1 tw-text-xs tw-text-muted"},"Need help?"," ",dr.default.createElement("a",{href:"https://github.com/logancyang/obsidian-copilot/blob/master/local_copilot.md",target:"_blank",rel:"noopener noreferrer",className:"tw-text-accent hover:tw-text-accent-hover"},"Setup guide"))),dr.default.createElement("div",{className:"tw-space-y-4"},n.map(r=>dr.default.createElement(zrn,{key:r.id,service:r,expanded:t===r.id,onToggleExpand:()=>e(o=>o===r.id?null:r.id)}))))}qe();vt();VS();var Cyt=require("obsidian"),or=N(U());ws();function jrn({onClose:t,onGoToModelTab:e}){Ht();let[n,r]=(0,or.useState)(null),o=zte().map(s=>{let a=s,l=Ad(a);return{provider:a,apiKey:l}}),i=(s,a)=>{Ad(s)!==a&&pe(tW[s],a)};return or.default.createElement("div",{className:"tw-p-4 sm:tw-max-w-[500px]"},or.default.createElement("div",{className:"tw-mb-4"},or.default.createElement("h2",{className:"tw-text-xl tw-font-bold"},"AI Provider Settings"),or.default.createElement("p",{className:"tw-text-sm tw-text-muted"},"Configure your AI providers by adding their API keys.")),or.default.createElement("div",{className:"tw-space-y-6 tw-py-4"},or.default.createElement("div",{className:"tw-space-y-4"},o.map(s=>{let a=ew(s.provider),l=!!a.listModelURL,c=n===s.provider;return or.default.createElement(or.default.Fragment,{key:s.provider},or.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},or.default.createElement("div",{className:"tw-flex tw-items-end tw-gap-2 tw-font-medium"},or.default.createElement("div",{className:"tw-truncate"},cl(s.provider))),or.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-gap-2"},or.default.createElement("div",{className:"tw-flex-1"},or.default.createElement(Fy,{className:"tw-max-w-full",value:s.apiKey,onChange:u=>i(s.provider,u)})),l&&or.default.createElement("div",null,or.default.createElement(X,{onClick:()=>{r(c?null:s.provider)},disabled:!s.apiKey,variant:"secondary",className:"tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-2 tw-whitespace-nowrap tw-px-4 tw-py-2"},"Add Model",c?or.default.createElement($s,{className:"tw-ml-1 tw-size-4"}):or.default.createElement(hr,{className:"tw-ml-1 tw-size-4"})))),or.default.createElement("div",null,a.keyManagementURL&&or.default.createElement("a",{href:a.keyManagementURL,target:"_blank",rel:"noopener noreferrer",className:"tw-text-[10px] tw-text-accent hover:tw-text-accent-hover sm:tw-text-xs"},"Get ",cl(s.provider)," Key"))),l&&or.default.createElement(cs,{open:c,className:"tw-mt-2"},or.default.createElement(us,{className:"tw-rounded-md tw-p-3"},or.default.createElement(MQ,{key:`${s.provider}:${s.apiKey}`,provider:s.provider,isReady:!!s.apiKey,expanded:c,credentialVersion:s.apiKey}))))})),or.default.createElement(vyt,null),or.default.createElement(byt,null),e&&or.default.createElement("div",{className:"tw-mt-4 tw-border-t tw-border-border tw-pt-4"},or.default.createElement("div",{className:"tw-rounded-lg tw-border tw-p-4 tw-bg-secondary/30 tw-border-border/60"},or.default.createElement("div",{className:"tw-flex tw-gap-3"},or.default.createElement("div",{className:"tw-mt-0.5 tw-shrink-0"},or.default.createElement(ug,{className:"tw-size-5 tw-text-accent"})),or.default.createElement("div",{className:"tw-flex-1"},or.default.createElement("h4",{className:"tw-mb-1 tw-text-sm tw-font-semibold"},"Looking for Azure OpenAI or Custom Providers?"),or.default.createElement("p",{className:"tw-mb-3 tw-text-xs tw-leading-relaxed tw-text-muted"},"Providers like Azure OpenAI, OpenAI Format, or Local LLMs require additional configuration (Base URL, Deployment Name, etc.)."),or.default.createElement("button",{type:"button",onClick:()=>{e(),t()},className:"tw-group tw-flex tw-items-center tw-gap-1 tw-text-sm tw-font-medium tw-text-accent hover:tw-text-accent-hover"},"Go to Model Settings",or.default.createElement(Di,{className:"tw-size-4 tw-transition-transform group-hover:tw-translate-x-0.5"}))))))),or.default.createElement("div",{className:"tw-mt-4 tw-flex tw-justify-end"},or.default.createElement(X,{onClick:t},"Close")))}var NQ=class extends Cyt.Modal{constructor(e,n){super(e),this.onGoToModelTab=n}onOpen(){let{contentEl:e}=this;this.root=sr(e,this.app),this.root.render(or.default.createElement(jrn,{onClose:()=>this.close(),onGoToModelTab:this.onGoToModelTab}))}onClose(){this.root.unmount()}};var Wrn={llm_chain:"Chat",vault_qa:"Vault QA (Basic)",copilot_plus:"Copilot Plus",project:"Projects (alpha)"},_yt=()=>{let t=tr(),e=Ht(),{setSelectedTab:n}=SS(),[r,o]=(0,ze.useState)(!1),[i,s]=(0,ze.useState)(e.defaultConversationNoteName||"{$date}_{$time}__{$topic}"),a=()=>{o(!0);try{let u=i||"{$date}_{$time}__{$topic}",f=["{$date}","{$time}","{$topic}"].filter(w=>!u.includes(w));if(f.length>0){new jV.Notice(`Error: Missing required variables: ${f.join(", ")}`,4e3);return}let p=/[\\/:*?"<>|]/,m=u.replace(/\{\$date}/g,"").replace(/\{\$time}/g,"").replace(/\{\$topic}/g,"");if(p.test(m)){new jV.Notice('Error: Format contains illegal characters (\\/:*?"<>|)',4e3);return}let{fileName:h}=ll(new Date),y=u.replace("{$topic}","test topic name".slice(0,100).replace(/\s+/g,"_")).replace("{$date}",h.split("_")[0]).replace("{$time}",h.split("_")[1]);pe("defaultConversationNoteName",u),s(u),new jV.Notice(`Format applied successfully! Example: ${y}`,4e3)}catch(u){new jV.Notice(`Error applying format: ${u instanceof Error?u.message:String(u)}`,4e3)}finally{o(!1)}},l=!!e.activeModels.find(u=>u.enabled&&ln(u)===e.defaultModelKey),c=e.activeModels.filter(u=>u.enabled).map(u=>({label:OR(u),value:ln(u)}));return ze.default.createElement("div",{className:"tw-space-y-4"},ze.default.createElement(hyt,null),ze.default.createElement("section",null,ze.default.createElement("div",{className:"tw-mb-3 tw-text-xl tw-font-bold"},"General"),ze.default.createElement("div",{className:"tw-space-y-4"},ze.default.createElement("div",{className:"tw-space-y-4"},ze.default.createElement($t,{type:"custom",title:"API Keys",description:ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},ze.default.createElement("span",{className:"tw-leading-none"},"Configure API keys for different AI providers"),ze.default.createElement(Nn,{content:ze.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2 tw-py-4"},ze.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-text-accent"},"API key required for chat and QA features"),ze.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"To enable chat and QA functionality, please provide an API key from your selected provider."))}))},ze.default.createElement(X,{onClick:()=>{new NQ(t,()=>n("model")).open()},variant:"secondary",className:"tw-flex tw-w-full tw-items-center tw-justify-center tw-gap-2 sm:tw-w-auto sm:tw-justify-start"},"Set Keys",ze.default.createElement(C$,{className:"tw-size-4"})))),ze.default.createElement($t,{type:"select",title:"Default Chat Model",description:ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},ze.default.createElement("span",{className:"tw-leading-none"},"Select the Chat model to use"),ze.default.createElement(Nn,{content:ze.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2 tw-py-4"},ze.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-text-accent"},"Default model is OpenRouter Gemini 2.5 Flash"),ze.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"Set your OpenRouter API key in 'API keys' to use this model, or select a different model from another provider."))})),value:l?e.defaultModelKey:"Select Model",onChange:u=>{let d=e.activeModels.find(m=>m.enabled&&ln(m)===u);if(!d)return;let{hasApiKey:f,errorNotice:p}=kA(d,e);pe("defaultModelKey",u)},options:l?c:[{label:"Select Model",value:"Select Model"},...c],placeholder:"Model"}),ze.default.createElement($t,{type:"select",title:"Default Mode",description:ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},ze.default.createElement("span",{className:"tw-leading-none"},"Select the default chat mode"),ze.default.createElement(Nn,{content:ze.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2"},ze.default.createElement("ul",{className:"tw-pl-4 tw-text-sm tw-text-muted"},ze.default.createElement("li",null,ze.default.createElement("strong",null,"Chat:")," Regular chat mode for general conversations and tasks. ",ze.default.createElement("i",null,"Free to use with your own API key.")),ze.default.createElement("li",null,ze.default.createElement("strong",null,"Vault QA (Basic):")," Ask questions about your vault content with semantic search. ",ze.default.createElement("i",null,"Free to use with your own API key.")),ze.default.createElement("li",null,ze.default.createElement("strong",null,"Copilot Plus:")," Covers all features of the 2 free modes, plus advanced paid features including chat context menu, advanced search, AI agents, and more. Check out"," ",ze.default.createElement("a",{href:aye(Vy.MODE_SELECT_TOOLTIP),target:"_blank",rel:"noopener noreferrer",className:"tw-text-accent hover:tw-text-accent-hover"},"obsidiancopilot.com")," ","for more details.")))})),value:e.defaultChainType,onChange:u=>pe("defaultChainType",u),options:Object.entries(Wrn).map(([u,d])=>({label:d,value:u}))}),ze.default.createElement($t,{type:"select",title:"Open Plugin In",description:"Choose where to open the plugin",value:e.defaultOpenArea,onChange:u=>pe("defaultOpenArea",u),options:[{label:"Sidebar View",value:"view"},{label:"Editor",value:"editor"}]}),ze.default.createElement($t,{type:"select",title:"Send Shortcut",description:ze.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},ze.default.createElement("span",{className:"tw-leading-none"},"Choose keyboard shortcut to send messages"),ze.default.createElement(Nn,{content:ze.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2 tw-py-4"},ze.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-text-accent"},"Shortcut not working?"),ze.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"If your selected shortcut doesn't work, check",ze.default.createElement("strong",null," Obsidian's Settings \u2192 Hotkeys")," to see if another command is using the same key combination. ",ze.default.createElement("br",null),"You may need to remove or change the conflicting hotkey first."))})),value:e.defaultSendShortcut,onChange:u=>pe("defaultSendShortcut",u),options:[{label:"Enter",value:"enter"},{label:"Shift + Enter",value:"shift+enter"}]}),ze.default.createElement($t,{type:"switch",title:"Auto-Add Active Content to Context",description:"Automatically add the active note or Web Viewer tab (Desktop only) to chat context when sending messages.",checked:e.autoAddActiveContentToContext,onCheckedChange:u=>{pe("autoAddActiveContentToContext",u)}}),ze.default.createElement($t,{type:"switch",title:"Auto-Add Selection to Context",description:"Automatically add selected text from notes or Web Viewer (Desktop only) to chat context. Disable to use manual command instead.",checked:e.autoAddSelectionToContext,onCheckedChange:u=>{pe("autoAddSelectionToContext",u)}}),ze.default.createElement($t,{type:"switch",title:"Images in Markdown",description:"Pass embedded images in markdown to the AI along with the text. Only works with multimodal models.",checked:e.passMarkdownImages,onCheckedChange:u=>{pe("passMarkdownImages",u)}}),ze.default.createElement($t,{type:"switch",title:"Suggested Prompts",description:"Show suggested prompts in the chat view",checked:e.showSuggestedPrompts,onCheckedChange:u=>pe("showSuggestedPrompts",u)}),ze.default.createElement($t,{type:"switch",title:"Relevant Notes",description:"Show relevant notes in the chat view",checked:e.showRelevantNotes,onCheckedChange:u=>pe("showRelevantNotes",u)}))),ze.default.createElement("section",null,ze.default.createElement("div",{className:"tw-mb-3 tw-text-xl tw-font-bold"},"Saving Conversations"),ze.default.createElement("div",{className:"tw-space-y-4"},ze.default.createElement($t,{type:"switch",title:"Autosave Chat",description:"Automatically saves the chat after every user message and AI response.",checked:e.autosaveChat,onCheckedChange:u=>pe("autosaveChat",u)}),ze.default.createElement($t,{type:"switch",title:"Generate AI Chat Title on Save",description:"When enabled, uses an AI model to generate a concise title for saved chat notes. When disabled, uses the first 10 words of the first user message.",checked:e.generateAIChatTitleOnSave,onCheckedChange:u=>pe("generateAIChatTitleOnSave",u)}),ze.default.createElement($t,{type:"text",title:"Default Conversation Folder Name",description:"The default folder name where chat conversations will be saved. Default is 'copilot/copilot-conversations'",value:e.defaultSaveFolder,onChange:u=>pe("defaultSaveFolder",u),placeholder:"copilot/copilot-conversations"}),ze.default.createElement($t,{type:"text",title:"Default Conversation Tag",description:"The default tag to be used when saving a conversation. Default is 'ai-conversations'",value:e.defaultConversationTag,onChange:u=>pe("defaultConversationTag",u),placeholder:"ai-conversations"}),ze.default.createElement($t,{type:"custom",title:"Conversation Filename Template",description:ze.default.createElement("div",{className:"tw-flex tw-items-start tw-gap-1.5 "},ze.default.createElement("span",{className:"tw-leading-none"},"Customize the format of saved conversation note names."),ze.default.createElement(Nn,{content:ze.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2 tw-py-4"},ze.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-text-accent"},"Note: All the following variables must be included in the template."),ze.default.createElement("div",null,ze.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-text-muted"},"Available variables:"),ze.default.createElement("ul",{className:"tw-pl-4 tw-text-sm tw-text-muted"},ze.default.createElement("li",null,ze.default.createElement("strong",null,"{$date}"),": Date in YYYYMMDD format"),ze.default.createElement("li",null,ze.default.createElement("strong",null,"{$time}"),": Time in HHMMSS format"),ze.default.createElement("li",null,ze.default.createElement("strong",null,"{$topic}"),": Chat conversation topic")),ze.default.createElement("i",{className:"tw-mt-2 tw-text-sm tw-text-muted"},"Example: ","{$date}_{$time}__{$topic}"," \u2192 20250114_153232__polish_this_article_[[Readme]]")))}))},ze.default.createElement("div",{className:"tw-flex tw-w-[320px] tw-items-center tw-gap-1.5"},ze.default.createElement(Xn,{type:"text",className:oe("tw-min-w-[80px] tw-grow tw-transition-all tw-duration-200",r?"tw-w-[80px]":"tw-w-[120px]"),placeholder:"{$date}_{$time}__{$topic}",value:i,onChange:u=>s(u.target.value),disabled:r}),ze.default.createElement(X,{onClick:()=>a(),disabled:r,variant:"secondary"},r?ze.default.createElement(ze.default.Fragment,null,ze.default.createElement(Pr,{className:"tw-mr-2 tw-size-4 tw-animate-spin"}),"Apply"):"Apply"))))),ze.default.createElement("section",null,ze.default.createElement("div",{className:"tw-mb-3 tw-text-xl tw-font-bold"},"Sorting"),ze.default.createElement("div",{className:"tw-space-y-4"},ze.default.createElement($t,{type:"select",title:"Chat History Sort Strategy",description:"Sort order for the chat history list",value:e.chatHistorySortStrategy,onChange:u=>{aA(u)&&pe("chatHistorySortStrategy",u)},options:[{label:"Recency",value:"recent"},{label:"Created",value:"created"},{label:"Alphabetical",value:"name"}]}),ze.default.createElement($t,{type:"select",title:"Project List Sort Strategy",description:"Sort order for the project list",value:e.projectListSortStrategy,onChange:u=>{aA(u)&&pe("projectListSortStrategy",u)},options:[{label:"Recency",value:"recent"},{label:"Created",value:"created"},{label:"Alphabetical",value:"name"}]}))))};bi();It();RN();yp();ns();Se();var Tyt=require("obsidian"),Cn=N(U());var Bl=N(U());It();Se();var Syt=()=>{let t=Ht(),e=Vi.getInstance(),n=new Set(t.autonomousAgentEnabledToolIds||[]),r=e.getToolsByCategory(),o=e.getConfigurableTools(),i=(l,c)=>{let u=new Set(n);c?u.add(l):u.delete(l),pe("autonomousAgentEnabledToolIds",Array.from(u))},s=(l,c)=>{let u=new Set(n);for(let{metadata:d}of c)l?u.add(d.id):u.delete(d.id);pe("autonomousAgentEnabledToolIds",Array.from(u))},a=()=>Array.from(r.entries()).filter(([c,u])=>u.some(d=>o.includes(d))).map(([c,u])=>{let d=u.filter(f=>o.includes(f));if(d.length===0)return null;if(c==="cli"){let f=d.every(({metadata:p})=>n.has(p.id));return Bl.default.createElement("div",{key:"cli",className:"tw-flex tw-flex-col tw-gap-2 tw-rounded-md tw-border tw-border-border tw-pb-3"},Bl.default.createElement($t,{type:"switch",title:"Obsidian CLI (Experimental)",description:"Enable direct vault operations via the Obsidian desktop CLI",checked:f,onCheckedChange:p=>s(p,d)}),Bl.default.createElement("div",{className:"tw-ml-4 tw-flex tw-flex-col tw-gap-1 tw-border-l tw-border-border tw-px-3"},d.map(({metadata:p})=>Bl.default.createElement("div",{key:p.id,className:"tw-flex tw-flex-col"},Bl.default.createElement("span",{className:"tw-text-xs tw-font-medium tw-text-normal"},p.displayName),Bl.default.createElement("span",{className:"tw-text-xs tw-text-muted"},p.description)))))}return Bl.default.createElement(Bl.default.Fragment,{key:c},d.map(({metadata:f})=>Bl.default.createElement($t,{key:f.id,type:"switch",title:f.displayName,description:f.description,checked:n.has(f.id),onCheckedChange:p=>i(f.id,p)})))});return Bl.default.createElement(Bl.default.Fragment,null,Bl.default.createElement($t,{type:"slider",title:"Max Iterations",description:"Maximum number of reasoning iterations the autonomous agent can perform. Higher values allow for more complex reasoning but may take longer.",value:t.autonomousAgentMaxIterations??4,onChange:l=>{pe("autonomousAgentMaxIterations",l)},min:4,max:eW,step:1}),Bl.default.createElement("div",{className:"tw-mt-4 tw-rounded-lg tw-bg-secondary tw-p-4"},Bl.default.createElement("div",{className:"tw-mb-2 tw-text-sm tw-font-medium"},"Agent Accessible Tools"),Bl.default.createElement("div",{className:"tw-mb-4 tw-text-xs tw-text-muted"},"Toggle which tools the autonomous agent can use"),Bl.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},a())))};var Iyt=()=>{let t=tr(),e=Ht(),[n,r]=(0,Cn.useState)(!1),o=E5e(),i=async a=>{if(a){r(!0);let l=await A5e();if(r(!1),!l)return;pe("enableSelfHostMode",!0)}else pe("enableSelfHostMode",!1),pe("enableMiyo",!1)},s=async a=>{if(a===e.enableMiyo)return;if(!a){pe("enableMiyo",!1);return}r(!0);try{if(!await new wp().isBackendAvailable(Jm(e))){new Tyt.Notice("Miyo app is not available. Please start the Miyo app and try again.");return}}finally{r(!1)}let l=async()=>{a&&e.embeddingBatchSize!==Hn.embeddingBatchSize&&pe("embeddingBatchSize",Hn.embeddingBatchSize),pe("enableMiyo",a),a&&!e.enableSemanticSearchV3&&pe("enableSemanticSearchV3",!0),(e.enableSemanticSearchV3||a)&&await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0})};new Cr(t,l,`Enabling Miyo Search will use your current vault folder name as the Miyo folder identifier and request a scan from Miyo. Make sure this folder is already registered in Miyo. Embedding Batch Size will be reset to the default (${Hn.embeddingBatchSize}) for local stability. Continue?`,"Request Miyo Scan").open()};return Cn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Cn.default.createElement("section",{className:"tw-flex tw-flex-col tw-gap-4"},Cn.default.createElement("div",{className:"tw-flex tw-items-center tw-py-4"},Cn.default.createElement(ro,{variant:"secondary",className:"tw-text-accent"},"Plus Required")),Cn.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Cn.default.createElement("div",{className:"tw-pt-4 tw-text-xl tw-font-semibold"},"Autonomous Agent"),Cn.default.createElement($t,{type:"switch",title:"Enable Autonomous Agent",description:"Enable autonomous agent mode in Plus chat. The AI will reason step-by-step and decide which tools to use automatically, improving response quality for complex queries.",checked:e.enableAutonomousAgent,onCheckedChange:a=>{pe("enableAutonomousAgent",a)}}),e.enableAutonomousAgent&&Cn.default.createElement(Cn.default.Fragment,null,Cn.default.createElement(Syt,null)),Cn.default.createElement("div",{className:"tw-pt-4 tw-text-xl tw-font-semibold"},"Document Processor"),Cn.default.createElement($t,{type:"text",title:"Store converted markdown at",description:"When PDFs and other documents are processed, the converted markdown is saved to this folder. Leave empty to skip saving.",value:e.convertedDocOutputFolder,onChange:a=>{pe("convertedDocOutputFolder",a)},placeholder:"e.g. copilot/converteddocs"}),Cn.default.createElement("div",{className:"tw-pt-4 tw-text-xl tw-font-semibold"},"Memory (experimental)"),Cn.default.createElement($t,{type:"text",title:"Memory Folder Name",description:"Specify the folder where memory data is stored.",value:e.memoryFolderName,onChange:a=>{pe("memoryFolderName",a)},placeholder:"copilot/memory"}),Cn.default.createElement($t,{type:"switch",title:"Reference Recent Conversation",description:"When enabled, Copilot references your recent conversation history to provide more contextually relevant responses. All history data is stored locally in your vault.",checked:e.enableRecentConversations,onCheckedChange:a=>{pe("enableRecentConversations",a)}}),e.enableRecentConversations&&Cn.default.createElement($t,{type:"slider",title:"Max Recent Conversations",description:"Number of recent conversations to remember for context. Higher values provide more context but may slow down responses.",min:10,max:50,step:1,value:e.maxRecentConversations,onChange:a=>pe("maxRecentConversations",a)}),Cn.default.createElement($t,{type:"switch",title:"Reference Saved Memories",description:"When enabled, Copilot can access memories that you explicitly asked it to remember. Use this to store important facts, preferences, or context for future conversations.",checked:e.enableSavedMemory,onCheckedChange:a=>{pe("enableSavedMemory",a)}}),o&&Cn.default.createElement(Cn.default.Fragment,null,Cn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5 tw-pt-4 tw-text-xl tw-font-semibold"},"Self-Host Mode",Cn.default.createElement(Nn,{content:"Lifetime license required"})),Cn.default.createElement($t,{type:"switch",title:"Enable Self-Host Mode",description:Cn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Cn.default.createElement("span",{className:"tw-leading-none"},"Use your own infrastructure for LLMs, embeddings and local document understanding with our desktop app Miyo."),Cn.default.createElement(Nn,{content:Cn.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2 tw-py-4"},Cn.default.createElement("div",{className:"tw-text-sm tw-font-medium tw-text-accent"},"Self-Host Mode (Believer/Supporter only)"),Cn.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"Connect to your own self-hosted backend (e.g., Miyo) for complete control over your AI infrastructure. This allows offline usage and custom model deployments."),Cn.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"Requires re-validation every 15 days when online."))})),checked:e.enableSelfHostMode,onCheckedChange:a=>void i(a),disabled:n}),e.enableSelfHostMode&&Cn.default.createElement(Cn.default.Fragment,null,Cn.default.createElement($t,{type:"text",title:"Remote Miyo Server URL (Optional)",description:"Leave blank when accessing Miyo locally. Set this only when Miyo is running on a remote machine \u2014 it will override the local service discovery.",value:e.miyoServerUrl||"",onChange:a=>pe("miyoServerUrl",a)}),Cn.default.createElement($t,{type:"switch",title:"Enable Miyo",description:"Use Miyo as your local search, PDF parsing, and context hub. Copilot will send the current vault folder name to Miyo and can request scans, but folder registration is managed in Miyo.",checked:e.enableMiyo,onCheckedChange:a=>void s(a),disabled:n}),e.enableMiyo&&Cn.default.createElement(Cn.default.Fragment,null,Cn.default.createElement($t,{type:"switch",title:"Search everything in Miyo",description:"When enabled, Miyo searches all indexed content across all folders. When disabled, searches are limited to the current vault folder only.",checked:e.miyoSearchAll,onCheckedChange:a=>pe("miyoSearchAll",a)}),!e.miyoSearchAll&&Cn.default.createElement("div",{className:"tw-text-xs tw-text-muted"},"Folder identifier sent to Miyo:"," ",Cn.default.createElement("span",{className:"tw-font-medium tw-text-normal"},Jg(t)))),Cn.default.createElement($t,{type:"select",title:"Web Search Provider",description:"Choose which service to use for self-host web search.",value:e.selfHostSearchProvider,onChange:a=>pe("selfHostSearchProvider",a),options:[{label:"Firecrawl (default)",value:"firecrawl"},{label:"Perplexity Sonar",value:"perplexity"}]}),e.selfHostSearchProvider==="firecrawl"&&Cn.default.createElement($t,{type:"password",title:"Firecrawl API Key",description:Cn.default.createElement("span",null,"API key for web search via Firecrawl."," ",Cn.default.createElement("a",{href:"https://firecrawl.link/logan-yang",target:"_blank",rel:"noopener noreferrer",className:"tw-text-accent"},"Sign up \u2192")),value:e.firecrawlApiKey,onChange:a=>pe("firecrawlApiKey",a),placeholder:"fc-..."}),e.selfHostSearchProvider==="perplexity"&&Cn.default.createElement($t,{type:"password",title:"Perplexity API Key",description:Cn.default.createElement("span",null,"API key for web search via Perplexity Sonar."," ",Cn.default.createElement("a",{href:"https://docs.perplexity.ai",target:"_blank",rel:"noopener noreferrer",className:"tw-text-accent"},"Get API key \u2192")),value:e.perplexityApiKey,onChange:a=>pe("perplexityApiKey",a),placeholder:"pplx-..."}),Cn.default.createElement($t,{type:"password",title:"Supadata API Key",description:Cn.default.createElement("span",null,"API key for YouTube transcripts via Supadata."," ",Cn.default.createElement("a",{href:"https://supadata.ai/?ref=obcopilot",target:"_blank",rel:"noopener noreferrer",className:"tw-text-accent"},"Sign up \u2192")),value:e.supadataApiKey,onChange:a=>pe("supadataApiKey",a),placeholder:"sd-..."}))))))};bi();It();o0();ye();Se();rn();It();ye();Se();qe();It();Su();var Hrn="2023-06-01",Krn="bedrock-2023-05-31",HE="Hello!",WV="Hello!",Y0e=64,qrn=256,Grn=256,Yrn=256,Zrn=new Set(["openai","openai","openrouterai","groq","xai","siliconflow","siliconflow","3rd party (openai-format)","3rd party (openai-format)","lm-studio","lm-studio","mistralai","deepseek"]);function AS(t){return t.replace(/\/+$/g,"")}function Jrn(t){try{return new URL(t)}catch{return null}}function VV(t){return t.replace(/'/g,`'"'"'`)}function OQ(t){let e=Cu[t];return(e?.curlBaseURL??e?.host??"").trim()}async function Z1(t){let e=[],n=t?.trim()??"";if(!n)return e.push("API key is empty; using placeholder."),{apiKey:"<YOUR_API_KEY>",warnings:e};try{let r=(await pn(n))?.trim();return r?{apiKey:r,warnings:e}:(e.push("API key could not be decrypted; using placeholder."),{apiKey:"<YOUR_API_KEY>",warnings:e})}catch{return e.push("API key could not be decrypted; using placeholder."),{apiKey:"<YOUR_API_KEY>",warnings:e}}}function Xrn(t){let e=AS(t),n=["/chat/completions","/embeddings","/responses"];for(let r of n)if(e.endsWith(r))return e.slice(0,-r.length);return e}function Qrn(t){let e=AS(t);return e.endsWith("/models")&&(e=e.slice(0,-7)),!e.includes("/v1beta")&&!e.includes("/v1")&&(e=`${e}/v1beta`),e}function eon(t){let e=AS(t),n=["/api/v1","/v1","/api"];for(let r of n)if(e.endsWith(r))return e.slice(0,-r.length);return e}function WE(t){let e=[],n=VV(t.url);e.push(`curl --request ${t.method} '${n}'`);for(let s of t.curlArgs??[])e.push(`  ${s}`);let r=["Content-Type","Accept","Authorization","x-goog-api-key","api-key","x-api-key","anthropic-version","OpenAI-Organization"],o=t.headers??{},i=new Set;for(let s of r)o[s]!==void 0&&(i.add(s),e.push(`  --header '${VV(`${s}: ${o[s]}`)}'`));for(let s of Object.keys(o).sort())i.has(s)||e.push(`  --header '${VV(`${s}: ${o[s]}`)}'`);if(t.body!==void 0){let s=JSON.stringify(t.body,null,2);e.push(`  --data-raw '${VV(s)}'`)}return e.join(` \\
`)}async function ton(t,e){let n=[],r=t.provider?.trim()??"",o=OQ(r),i=t.baseUrl?.trim()??"",s=AS(i||o||"https://api.example.com/v1"),a=Xrn(s),l=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||n.push("Model name is empty; using placeholder.");let c=await Z1(t.apiKey);n.push(...c.warnings);let u={"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${c.apiKey}`};if(t.openAIOrgId?.trim())try{let d=(await pn(t.openAIOrgId))?.trim();d?u["OpenAI-Organization"]=d:n.push("OpenAI organization ID could not be decrypted; omitting header.")}catch{n.push("OpenAI organization ID could not be decrypted; omitting header.")}return r==="openrouterai"&&(u["HTTP-Referer"]="https://obsidiancopilot.com",u["X-Title"]="Obsidian Copilot"),e?{ok:!0,warnings:n,spec:{method:"POST",url:`${a}/embeddings`,headers:u,body:{model:l,input:WV}}}:{ok:!0,warnings:n,spec:{method:"POST",url:`${a}/chat/completions`,headers:u,body:{model:l,messages:[{role:"user",content:HE}],stream:!1,max_tokens:Y0e}}}}function non(t,e,n,r){let o=[],i=t.azureOpenAIApiInstanceName?.trim()||"[instance]";t.azureOpenAIApiInstanceName?.trim()||o.push("Azure instance name is empty; using placeholder.");let s=t.baseUrl?.trim();if(s){let a=Jrn(s);if(a){let l=AS(a.pathname||"");l.includes("/openai/deployments/")&&(l=l.split("/openai/deployments/")[0]);let c=`${a.origin}${l}`;return{warnings:o,url:`${c}/openai/deployments/${encodeURIComponent(e)}/${n}?api-version=${encodeURIComponent(r)}`}}}return{warnings:o,url:`https://${i}.openai.azure.com/openai/deployments/${encodeURIComponent(e)}/${n}?api-version=${encodeURIComponent(r)}`}}async function ron(t,e){let n=[],r=await Z1(t.apiKey);n.push(...r.warnings);let o=e?"embeddings":"chat/completions";if(t.baseUrl?.trim()){let{normalizeAzureUrl:c}=await Promise.resolve().then(()=>(eP(),Vve)),{baseUrl:u,apiVersion:d}=c(t.baseUrl.trim()),f=d||t.azureOpenAIApiVersion?.trim()||"2024-05-01-preview",p=`${u}/${o}?api-version=${encodeURIComponent(f)}`,m=t.name?.trim(),h=e?{input:WV,...m?{model:m}:{}}:{messages:[{role:"user",content:HE}],stream:!1,max_tokens:Y0e,...m?{model:m}:{}};return{ok:!0,warnings:n,spec:{method:"POST",url:p,headers:{"Content-Type":"application/json",Accept:"application/json","api-key":r.apiKey},body:h}}}let i=e?t.azureOpenAIApiEmbeddingDeploymentName?.trim()||"[deployment]":t.azureOpenAIApiDeploymentName?.trim()||"[deployment]";(!i||i==="[deployment]")&&n.push("Azure deployment name is empty; using placeholder.");let s=t.azureOpenAIApiVersion?.trim()||"[api-version]";t.azureOpenAIApiVersion?.trim()||n.push("Azure api-version is empty; using placeholder.");let a=non(t,i,o,s);n.push(...a.warnings);let l=e?{input:WV}:{messages:[{role:"user",content:HE}],stream:!1,max_tokens:Y0e};return{ok:!0,warnings:n,spec:{method:"POST",url:a.url,headers:{"Content-Type":"application/json",Accept:"application/json","api-key":r.apiKey},body:l}}}async function oon(t){let e=[],n=t.baseUrl?.trim()??"",r=OQ("anthropic"),o=AS(n||r||"https://api.anthropic.com"),i=["/v1/messages","/v1"];for(let c of i)if(o.endsWith(c)){o=o.slice(0,-c.length);break}let s=`${o}/v1/messages`,a=await Z1(t.apiKey);e.push(...a.warnings);let l=t.name?.trim()||"<MODEL_NAME>";return t.name?.trim()||e.push("Model name is empty; using placeholder."),{ok:!0,warnings:e,spec:{method:"POST",url:s,headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":a.apiKey,"anthropic-version":Hrn},body:{model:l,max_tokens:qrn,messages:[{role:"user",content:HE}]}}}}async function ion(t,e){let n=[],r=t.baseUrl?.trim()??"",o=OQ("google"),s=Qrn(r||o||"https://generativelanguage.googleapis.com"),a=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||n.push("Model name is empty; using placeholder.");let l=a.includes("/")?a:`models/${a}`,c=await Z1(t.apiKey);n.push(...c.warnings);let u={"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":c.apiKey};return e?{ok:!0,warnings:n,spec:{method:"POST",url:`${s}/${l}:embedContent`,headers:u,body:{content:{parts:[{text:WV}]}}}}:{ok:!0,warnings:n,spec:{method:"POST",url:`${s}/${l}:generateContent`,headers:u,body:{contents:[{role:"user",parts:[{text:HE}]}],generationConfig:{maxOutputTokens:Yrn}}}}}function son(t){return/(^|\.)anthropic\./.test(t)}async function aon(t){let e=[],n=t.name?.trim()||"<MODEL_ID>";t.name?.trim()||e.push("Model name is empty; using placeholder.");let r=t.bedrockRegion?.trim()||"us-east-1";t.bedrockRegion?.trim()||e.push("Bedrock region is empty; defaulting to us-east-1.");let o=t.baseUrl?.trim(),s=`${AS(o||`https://bedrock-runtime.${r}.amazonaws.com`)}/model/${encodeURIComponent(n)}/invoke`,a={messages:[{role:"user",content:[{type:"text",text:HE}]}],max_tokens:Grn};son(n)?a.anthropic_version=Krn:e.push("Model ID does not look like Anthropic; request body may need adjustment.");let l=await Z1(t.apiKey);e.push(...l.warnings);let c={method:"POST",url:s,headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${l.apiKey}`},body:a},u={method:"POST",url:s,curlArgs:[`--aws-sigv4 'aws:amz:${VV(r)}:bedrock'`,"--user '<AWS_ACCESS_KEY_ID>:<AWS_SECRET_ACCESS_KEY>'"],headers:{"Content-Type":"application/json",Accept:"application/json"},body:a};return{ok:!0,command:["# Amazon Bedrock InvokeModel","# Option A: Bearer token auth (matches Obsidian Copilot)",WE(c),"","# Option B: IAM auth (AWS SigV4)",WE(u)].join(`
`),warnings:e}}async function lon(t,e){let n=[],r=t.baseUrl?.trim()??"",o=OQ("ollama"),i=eon(AS(r||o||"http://localhost:11434")),s=t.name?.trim()||"<MODEL_NAME>";t.name?.trim()||n.push("Model name is empty; using placeholder.");let a={"Content-Type":"application/json",Accept:"application/json"};if(t.apiKey?.trim()){let c=await Z1(t.apiKey),u=c.warnings.filter(d=>!d.includes("API key is empty"));n.push(...u),a.Authorization=`Bearer ${c.apiKey}`}return e?{ok:!0,warnings:n,spec:{method:"POST",url:`${i}/api/embed`,headers:a,body:{model:s,input:WV,truncate:!0}}}:{ok:!0,warnings:n,spec:{method:"POST",url:`${i}/api/chat`,headers:a,body:{model:s,messages:[{role:"user",content:HE}],stream:!1}}}}async function Pyt(t){let e=[],n=t.provider?.trim();if(!n)return{ok:!1,error:"Provider is required to build a curl command.",warnings:e};let r=!!t.isEmbeddingModel;if(n==="azure openai"){let o=await ron(t,r);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}if(n==="anthropic"){if(r)return{ok:!1,error:"Anthropic does not support embeddings.",warnings:e};let o=await oon(t);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}if(n==="amazon-bedrock")return r?{ok:!1,error:"Bedrock embeddings are not supported by this generator.",warnings:e}:await aon(t);if(n==="google"||n==="google"){let o=await ion(t,r);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}if(n==="ollama"||n==="ollama"){let o=await lon(t,r);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}if(Zrn.has(n)){let o=await ton(t,r);return o.ok?{ok:!0,command:WE(o.spec),warnings:o.warnings}:o}return{ok:!1,error:`Provider "${n}" is not supported for curl generation.`,warnings:e}}vt();VS();var kS=require("obsidian"),Ae=N(U()),Z0e=({open:t,onOpenChange:e,onAdd:n,ping:r,isEmbeddingModel:o=!1})=>{let{modalContainer:i}=SS(),s=q(),a=o?"openai":"openrouterai",l=j=>j==="azure openai"&&!T.baseUrl,[c,u]=(0,Ae.useState)(null),[d,f]=(0,Ae.useState)(()=>l(a)),[p,m]=(0,Ae.useState)(!1),[h,g]=(0,Ae.useState)("idle"),[y,w]=(0,Ae.useState)({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1}),v=(j,G)=>{w(J=>({...J,[j]:G}))},x=()=>{w({name:!1,instanceName:!1,deploymentName:!1,embeddingDeploymentName:!1,apiVersion:!1,displayName:!1,bedrockRegion:!1})},b=()=>{let j=!0,G={...y};return G.name=!T.name,T.name||(j=!1),T.provider==="azure openai"&&(o||!T.baseUrl?.trim())&&(G.instanceName=!T.azureOpenAIApiInstanceName,G.apiVersion=!T.azureOpenAIApiVersion,o?(G.embeddingDeploymentName=!T.azureOpenAIApiEmbeddingDeploymentName,T.azureOpenAIApiEmbeddingDeploymentName||(j=!1)):(G.deploymentName=!T.azureOpenAIApiDeploymentName,T.azureOpenAIApiDeploymentName||(j=!1)),(!T.azureOpenAIApiInstanceName||!T.azureOpenAIApiVersion)&&(j=!1)),T.provider,"amazon-bedrock",G.bedrockRegion=!1,w(G),j},_=(j=a)=>{let G={name:"",provider:j,enabled:!0,isBuiltIn:!1,baseUrl:"",apiKey:Ad(j),isEmbeddingModel:o,capabilities:[]};if(!o){let J={...G,stream:!0};return j==="amazon-bedrock"?{...J,bedrockRegion:s.amazonBedrockRegion}:J}return G},[T,S]=(0,Ae.useState)(()=>_()),P=j=>{S(G=>({...G,...j})),g("idle")},A=j=>({...j,name:j.name?.trim(),baseUrl:j.baseUrl?.trim(),apiKey:j.apiKey?.trim(),openAIOrgId:j.openAIOrgId?.trim(),azureOpenAIApiInstanceName:j.azureOpenAIApiInstanceName?.trim(),azureOpenAIApiDeploymentName:j.azureOpenAIApiDeploymentName?.trim(),azureOpenAIApiEmbeddingDeploymentName:j.azureOpenAIApiEmbeddingDeploymentName?.trim(),azureOpenAIApiVersion:j.azureOpenAIApiVersion?.trim(),bedrockRegion:j.bedrockRegion?.trim()}),[O,D]=(0,Ae.useState)(()=>ew(a)),$=()=>!!(T.name&&T.provider),B=()=>p||!$(),W=()=>{if(!b()){new kS.Notice("Please fill in all required fields");return}let j=A(T);n(j),e(!1),S(_()),x(),g("idle"),f(!1)},F=j=>{D(ew(j)),g("idle"),S({...T,provider:j,apiKey:Ad(j),...j==="openai"?{openAIOrgId:s.openAIOrgId}:{},...j==="azure openai"?{azureOpenAIApiInstanceName:s.azureOpenAIApiInstanceName,azureOpenAIApiDeploymentName:s.azureOpenAIApiDeploymentName,azureOpenAIApiVersion:s.azureOpenAIApiVersion,azureOpenAIApiEmbeddingDeploymentName:s.azureOpenAIApiEmbeddingDeploymentName}:{},...j==="amazon-bedrock"?{bedrockRegion:s.amazonBedrockRegion}:{bedrockRegion:void 0}}),f(l(j))},Z=j=>{j||(S(_()),x(),g("idle"),f(!1)),e(j)},V=async()=>{if(!b()){new kS.Notice("Please fill in all required fields");return}m(!0),g("idle");try{let j=A(T);await r(j),g("success"),new kS.Notice("Model verification successful!")}catch(j){z(j);let G=Xt(j);g("failed"),new kS.Notice("Model verification failed: "+G)}finally{m(!1)}},H=async()=>{try{let j=A(T),G=await Pyt(j);if(!G.ok){new kS.Notice(G.error);return}await navigator.clipboard.writeText(G.command);let M=!G.warnings.some(L=>L.includes("placeholder"))?" Warning: contains real API key!":"",E=G.warnings.filter(L=>!L.includes("placeholder")),R=E.length>0?` (${E[0]})`:"";new kS.Notice(`Copied curl command.${M}${R}`)}catch(j){z(j),new kS.Notice("Failed to copy curl command: "+Xt(j))}},te=()=>{let G=(()=>{switch(T.provider){case"openai":return Ae.default.createElement(Zn,{label:"OpenAI Organization ID",description:"Enter OpenAI Organization ID if applicable"},Ae.default.createElement(Xn,{type:"text",placeholder:"Enter OpenAI Organization ID if applicable",value:T.openAIOrgId||"",onChange:J=>P({openAIOrgId:J.target.value})}));case"azure openai":return T.baseUrl?.trim()&&!o?null:Ae.default.createElement(Ae.default.Fragment,null,Ae.default.createElement(Zn,{label:"Instance Name",required:!0,error:y.instanceName,errorMessage:"Instance name is required"},Ae.default.createElement(Xn,{type:"text",placeholder:"Enter Azure OpenAI API Instance Name",value:T.azureOpenAIApiInstanceName||"",onChange:J=>{P({azureOpenAIApiInstanceName:J.target.value}),v("instanceName",!1)}})),o?Ae.default.createElement(Zn,{label:"Embedding Deployment Name",required:!0,error:y.embeddingDeploymentName,errorMessage:"Embedding deployment name is required"},Ae.default.createElement(Xn,{type:"text",placeholder:"Enter Azure OpenAI API Embedding Deployment Name",value:T.azureOpenAIApiEmbeddingDeploymentName||"",onChange:J=>{P({azureOpenAIApiEmbeddingDeploymentName:J.target.value}),v("embeddingDeploymentName",!1)}})):Ae.default.createElement(Zn,{label:"Deployment Name",required:!0,error:y.deploymentName,errorMessage:"Deployment name is required",description:"This is your actual model, no need to pass a model name separately."},Ae.default.createElement(Xn,{type:"text",placeholder:"Enter Azure OpenAI API Deployment Name",value:T.azureOpenAIApiDeploymentName||"",onChange:J=>{P({azureOpenAIApiDeploymentName:J.target.value}),v("deploymentName",!1)}})),Ae.default.createElement(Zn,{label:"API Version",required:!0,error:y.apiVersion,errorMessage:"API version is required"},Ae.default.createElement(Xn,{type:"text",placeholder:"Enter Azure OpenAI API Version",value:T.azureOpenAIApiVersion||"",onChange:J=>{P({azureOpenAIApiVersion:J.target.value}),v("apiVersion",!1)}})));case"amazon-bedrock":return Ae.default.createElement(Zn,{label:"Region (optional)",description:"Defaults to us-east-1 when left blank. With inference profiles (global., us., eu., apac.), region is auto-managed."},Ae.default.createElement("div",{className:"tw-flex tw-gap-2"},Ae.default.createElement(Xn,{className:"tw-flex-1",type:"text",placeholder:"Enter AWS region (e.g. us-east-1)",value:T.bedrockRegion||"",onChange:J=>{P({bedrockRegion:J.target.value}),v("bedrockRegion",!1)}}),Ae.default.createElement(ZP,{onValueChange:J=>{P({bedrockRegion:J}),v("bedrockRegion",!1)}},Ae.default.createElement(z_,{className:"tw-w-[140px]"},Ae.default.createElement(JP,{placeholder:"Presets"})),Ae.default.createElement(j_,{container:c},["us-east-1","us-west-2","eu-west-1","ap-northeast-1","ap-southeast-1"].map(J=>Ae.default.createElement(V_,{key:J,value:J},J))))));default:return null}})();return G?Ae.default.createElement(cs,{open:d,onOpenChange:f,className:"tw-rounded-lg tw-border tw-bg-secondary/30 tw-border-border/60"},Ae.default.createElement(hu,{asChild:!0},Ae.default.createElement("button",{type:"button",className:"tw-flex tw-w-full tw-cursor-pointer tw-items-center tw-justify-between tw-rounded-lg tw-p-3 tw-text-left hover:tw-bg-modifier-hover"},Ae.default.createElement("span",{className:"tw-text-sm tw-font-medium"},"Additional ",cl(T.provider)," Settings"),Ae.default.createElement(hr,{className:`tw-size-4 tw-text-muted tw-transition-transform tw-duration-200 ${d?"tw-rotate-180":""}`}))),Ae.default.createElement(us,{className:"tw-space-y-4 tw-px-3 tw-pb-3"},G)):null},fe=()=>{if(T.provider!=="azure openai")return O.host;let j=T.azureOpenAIApiInstanceName||"[instance]",G=o?T.azureOpenAIApiEmbeddingDeploymentName||"[deployment]":T.azureOpenAIApiDeploymentName||"[deployment]",J=T.azureOpenAIApiVersion||"[api-version]";return`https://${j}.openai.azure.com/openai/deployments/${G}/${o?"embeddings":"chat/completions"}?api-version=${J}`},me=Object.entries(Ex).map(([j,G])=>({id:j,label:j.charAt(0).toUpperCase()+j.slice(1),description:G}));return Ae.default.createElement(PQ,{open:t,onOpenChange:Z},Ae.default.createElement($V,{className:"tw-max-h-[80vh] tw-overflow-y-auto sm:tw-max-w-[425px]",container:i,ref:j=>u(j)},Ae.default.createElement(FV,null,Ae.default.createElement(UV,null,"Add Custom ",o?"Embedding":"Chat"," Model"),Ae.default.createElement(BV,null,"Add a new model to your collection.")),Ae.default.createElement("div",{className:"tw-space-y-3"},Ae.default.createElement(Zn,{label:"Model Name",required:!0,error:y.name,errorMessage:"Model name is required",description:T.provider==="amazon-bedrock"&&!o?"For Bedrock, use cross-region inference profile IDs (global., us., eu., or apac. prefix) for better reliability. Regional IDs without prefixes may fail.":void 0},Ae.default.createElement(Xn,{type:"text",placeholder:`Enter model name (e.g. ${T.provider==="amazon-bedrock"&&!o?"global.anthropic.claude-sonnet-4-6-v1:0":o?"text-embedding-3-small":"gpt-4"})`,value:T.name,onChange:j=>{P({name:j.target.value}),v("name",!1)}})),Ae.default.createElement(Zn,{label:Ae.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Ae.default.createElement("span",{className:"tw-leading-none"},"Display Name"),Ae.default.createElement(Nn,{content:Ae.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-0.5 tw-text-sm tw-text-muted"},Ae.default.createElement("div",{className:"tw-text-[12px] tw-font-bold"},"Suggested format:"),Ae.default.createElement("div",{className:"tw-text-accent"},"[Source]-[Payment]:[Pretty Model Name]"),Ae.default.createElement("div",{className:"tw-text-[12px]"},"Example:",Ae.default.createElement("li",null,"Direct-Paid:Ds-r1"),Ae.default.createElement("li",null,"OpenRouter-Paid:Ds-r1"),Ae.default.createElement("li",null,"Perplexity-Paid:lg"))),contentClassName:"tw-max-w-96"}))},Ae.default.createElement(Xn,{type:"text",placeholder:"Custom display name (optional)",value:T.displayName||"",onChange:j=>{S({...T,displayName:j.target.value})}})),Ae.default.createElement(Zn,{label:"Provider"},Ae.default.createElement(ZP,{value:T.provider,onValueChange:F},Ae.default.createElement(z_,null,Ae.default.createElement(JP,{placeholder:"Select provider"})),Ae.default.createElement(j_,{container:c},Object.values(o?XD(um,["COPILOT_PLUS","COPILOT_PLUS_JINA"]):XD(Ec,["COPILOT_PLUS"])).map(j=>Ae.default.createElement(V_,{key:j,value:j},cl(j)))))),Ae.default.createElement(Zn,{label:"Base URL",description:"Leave it blank, unless you are using a proxy."},Ae.default.createElement(Xn,{type:"text",placeholder:fe()||"https://api.example.com/v1",value:T.baseUrl||"",onChange:j=>P({baseUrl:j.target.value})})),Ae.default.createElement(Zn,{label:"API Key"},Ae.default.createElement(Fy,{placeholder:`Enter ${O.label} API Key`,value:T.apiKey||"",onChange:j=>P({apiKey:j})}),O.keyManagementURL&&Ae.default.createElement("p",{className:"tw-text-xs tw-text-muted"},Ae.default.createElement("a",{href:O.keyManagementURL,target:"_blank",rel:"noopener noreferrer"},"Get ",O.label," API Key"))),!o&&Ae.default.createElement(Zn,{label:Ae.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},Ae.default.createElement("span",{className:"tw-leading-none"},"Model Capabilities"),Ae.default.createElement(Nn,{content:Ae.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Only used to display model capabilities, does not affect model functionality"),contentClassName:"tw-max-w-96"}))},Ae.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-items-center tw-gap-x-6 tw-gap-y-2"},me.map(({id:j,label:G,description:J})=>Ae.default.createElement("div",{key:j,className:"tw-flex tw-items-center tw-gap-2"},Ae.default.createElement(To,{id:j,checked:T.capabilities?.includes(j),onCheckedChange:M=>{let E=T.capabilities||[];S({...T,capabilities:M?[...E,j]:E.filter(R=>R!==j)})}}),Ae.default.createElement(Nn,{content:J},Ae.default.createElement(hi,{htmlFor:j,className:"tw-text-sm"},G)))))),te()),Ae.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-3 sm:tw-flex-row sm:tw-items-center sm:tw-justify-between"},Ae.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-items-center tw-gap-3 sm:tw-flex-1"},Ae.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ae.default.createElement(To,{id:"enable-cors",checked:T.enableCors||!1,onCheckedChange:j=>S({...T,enableCors:j})}),Ae.default.createElement(hi,{htmlFor:"enable-cors",className:"tw-cursor-pointer"},Ae.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ae.default.createElement("span",{className:"tw-text-sm"},"CORS"),Ae.default.createElement(Nn,{content:Ae.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Only check this option when prompted that CORS is needed"),contentClassName:"tw-max-w-96"})))),(T.provider==="3rd party (openai-format)"||T.provider==="lm-studio")&&Ae.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Ae.default.createElement(To,{id:"stream-usage",checked:T.streamUsage||!1,onCheckedChange:j=>S({...T,streamUsage:j})}),Ae.default.createElement(hi,{htmlFor:"stream-usage",className:"tw-cursor-pointer"},Ae.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Ae.default.createElement("span",{className:"tw-text-sm"},"Stream Usage"),Ae.default.createElement(Nn,{content:Ae.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Enable if your provider supports stream_options for token usage tracking. Disable for providers that do not support it (e.g., Databricks, MLFlow)."),contentClassName:"tw-max-w-96"})))),Ae.default.createElement(uu,null,Ae.default.createElement(cn,null,Ae.default.createElement(un,{asChild:!0},Ae.default.createElement(X,{variant:"ghost",size:"sm",onClick:H,disabled:!T.name,className:"tw-text-muted hover:tw-text-normal"},"CURL")),Ae.default.createElement(on,null,Ae.default.createElement("p",null,"Copy curl command for testing"))))),Ae.default.createElement("div",{className:"tw-flex tw-shrink-0 tw-items-center tw-justify-end tw-gap-2"},h==="success"&&Ae.default.createElement(vm,{className:"tw-size-5 tw-text-success"}),h==="failed"&&Ae.default.createElement(sg,{className:"tw-size-5 tw-text-error"}),Ae.default.createElement(uu,null,Ae.default.createElement(cn,null,Ae.default.createElement(un,{asChild:!0},Ae.default.createElement(X,{variant:"secondary",size:"sm",onClick:V,disabled:B(),className:"tw-min-w-[72px]"},p?Ae.default.createElement(Ae.default.Fragment,null,Ae.default.createElement(Pr,{className:"tw-mr-1.5 tw-size-3.5 tw-animate-spin"}),"Test"):"Test")),Ae.default.createElement(on,null,Ae.default.createElement("p",null,"Optional: test API call")))),Ae.default.createElement(X,{variant:"default",size:"sm",onClick:W,disabled:B()},"Add Model")))))};rn();It();Kt();Se();qe();vt();var lt=N(U());VS();var con={reasoning:{icon:Cm,color:"tw-text-model-capabilities-blue",tooltip:Ex.reasoning},vision:{icon:ow,color:"tw-text-model-capabilities-green",tooltip:Ex.vision},websearch:{icon:Br,color:"tw-text-model-capabilities-blue",tooltip:Ex.websearch}},uon=["reasoning","vision","websearch"],don=({title:t,onRefresh:e,onAdd:n})=>lt.default.createElement("div",{className:"tw-mb-3 tw-flex tw-flex-col tw-gap-2 md:tw-flex-row md:tw-items-center md:tw-justify-between"},lt.default.createElement("h3",{className:"tw-text-xl tw-font-bold"},t),lt.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2 sm:tw-flex-row sm:tw-items-center sm:tw-justify-end"},e&&lt.default.createElement(X,{onClick:e,variant:"secondary",className:"tw-flex tw-items-center tw-gap-2"},lt.default.createElement(zf,{className:"tw-size-2 md:tw-size-4"}),"Refresh Built-ins"),lt.default.createElement(X,{onClick:n,variant:"default",className:"tw-flex tw-items-center tw-gap-2"},lt.default.createElement(Lc,{className:"tw-size-2 md:tw-size-4"}),"Add Model"))),fon=t=>lt.default.createElement("div",{className:"tw-mx-auto tw-grid tw-w-16 tw-grid-cols-3 tw-gap-1"},uon.map(e=>{let n=con[e];if(!n)return lt.default.createElement("div",{key:e,className:"tw-w-4"});let r=n.icon;return t.capabilities?.includes(e)?lt.default.createElement(Nn,{key:e,content:n.tooltip,side:"bottom"},lt.default.createElement("div",{className:"tw-flex tw-items-center tw-justify-center"},lt.default.createElement(r,{className:oe("tw-size-4",n.color)}))):lt.default.createElement("div",{key:e,className:"tw-flex tw-items-center tw-justify-center"},lt.default.createElement("div",{className:"tw-size-4"}))})),pon=({model:t,onEdit:e,onCopy:n,onDelete:r,onUpdateModel:o,id:i,containerRef:s})=>{let a=[];e&&a.push({icon:lt.default.createElement(nb,{className:"tw-size-4"}),label:"Edit",onClick:e}),n&&!t.core&&a.push({icon:lt.default.createElement(Eu,{className:"tw-size-4"}),label:"Copy",onClick:n}),t.core||a.push({icon:lt.default.createElement(ka,{className:"tw-size-4"}),label:"Delete",onClick:()=>r(ln(t)),variant:"destructive"});let l=lt.default.createElement("div",{className:"tw-flex tw-justify-around"},!t.isEmbeddingModel&&lt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},lt.default.createElement("span",{className:"tw-text-sm"},"Enabled"),lt.default.createElement(To,{checked:t.enabled,onCheckedChange:c=>o({...t,enabled:c})})),lt.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},lt.default.createElement("span",{className:"tw-text-sm"},"CORS"),lt.default.createElement(To,{checked:t.enableCors,onCheckedChange:c=>o({...t,enableCors:c})})));return lt.default.createElement(vQ,{id:i,item:t,title:t.displayName||t.name,subtitle:cl(t.provider,t),badge:t.capabilities&&t.capabilities.length>0?lt.default.createElement(abe,{capabilities:t.capabilities,iconSize:14}):void 0,isDraggable:!t.core,isExpandable:!0,expandedContent:l,primaryAction:e?{icon:lt.default.createElement(rb,{className:"tw-size-4"}),onClick:e,tooltip:"Edit Model"}:void 0,dropdownActions:a,containerRef:s})},mon=({model:t,onEdit:e,onCopy:n,onDelete:r,onUpdateModel:o,isEmbeddingModel:i,containerRef:s})=>{let{attributes:a,listeners:l,setNodeRef:c,transform:u,transition:d,isDragging:f}=K1({id:ln(t),disabled:t.core}),p={transform:om.Transform.toString(u),transition:d},m=e||!t.core||n&&!t.core;return lt.default.createElement(ES,{ref:c,style:p,className:oe("tw-transition-colors tw-duration-200 hover:tw-bg-interactive-accent/10",f&&"tw-relative tw-z-[100] tw-cursor-grabbing tw-shadow-lg tw-backdrop-blur-sm tw-border-accent/50 tw-bg-primary/90")},lt.default.createElement(Ic,{className:"tw-w-6 tw-px-2"},!t.core&&lt.default.createElement(X,{variant:"ghost",size:"icon",className:"tw-size-6 tw-cursor-grab tw-touch-none tw-p-0 hover:tw-cursor-grab active:tw-cursor-grabbing",...a,...l},lt.default.createElement(bm,{className:"tw-size-4 tw-transition-colors"}))),lt.default.createElement(Ic,{className:"tw-pl-0"},t.displayName||t.name),lt.default.createElement(Ic,null,cl(t.provider,t)),lt.default.createElement(Ic,null,fon(t)),!i&&lt.default.createElement(Ic,{className:"tw-text-center"},lt.default.createElement(To,{id:`${ln(t)}-enabled`,checked:t.enabled,disabled:t.enabled&&IAe(t),onCheckedChange:h=>o({...t,enabled:h}),className:"tw-mx-auto"})),lt.default.createElement(Ic,{className:"tw-text-center"},lt.default.createElement(To,{id:`${ln(t)}-enableCors`,checked:t.enableCors,onCheckedChange:h=>o({...t,enableCors:h}),className:"tw-mx-auto"})),lt.default.createElement(Ic,{className:"tw-text-center"},lt.default.createElement("div",{className:"tw-flex tw-justify-center tw-gap-2"},e&&lt.default.createElement(X,{variant:"ghost",size:"icon",onClick:()=>e(t),className:"tw-shadow-sm tw-transition-shadow hover:tw-shadow-md"},lt.default.createElement(rb,{className:"tw-size-4"})),m&&lt.default.createElement(xy,null,lt.default.createElement(by,{asChild:!0},lt.default.createElement(X,{variant:"ghost",size:"icon"},lt.default.createElement(lg,{className:"tw-size-4"}))),lt.default.createElement(sd,{align:"end",container:s.current},e&&lt.default.createElement(wr,{onClick:()=>e(t)},lt.default.createElement(nb,{className:"tw-mr-2 tw-size-4"}),"Edit"),n&&!t.core&&lt.default.createElement(wr,{onClick:()=>n(t)},lt.default.createElement(Eu,{className:"tw-mr-2 tw-size-4"}),"Copy"),!t.core&&lt.default.createElement(wr,{onClick:()=>r(ln(t)),className:"tw-text-error"},lt.default.createElement(ka,{className:"tw-mr-2 tw-size-4"}),"Delete"))))))},J0e=({models:t,onEdit:e,onCopy:n,onDelete:r,onAdd:o,onUpdateModel:i,onReorderModels:s,onRefresh:a,title:l})=>{let c=!!(t.length>0&&t[0].isEmbeddingModel),u=dQ(z1(PS),z1(IS,{coordinateGetter:wQ})),d=(0,lt.useRef)(null),f=t.findIndex(g=>!g.core),p=g=>y=>{let{transform:w,active:v,activeNodeRect:x,over:b}=y;if(!v||!x)return w;let _=t.findIndex(O=>ln(O)===v.id),T=t.filter(O=>!O.core).length,S=x.height,P=(f-_)*S,A=(f+T-1-_)*S;if(g&&b){let O=t.findIndex($=>ln($)===b.id);if(t[O].core||O<f)return{...w,x:0,y:0}}return{...w,x:0,y:Math.min(Math.max(P,w.y),A)}},m=g=>{let{active:y,over:w}=g;if(w&&y.id!==w.id){let v=t.findIndex(T=>ln(T)===y.id),x=t.findIndex(T=>ln(T)===w.id),b=t[x];if(x<f||b.core)return;let _=yQ(t,v,x);s?.(_)}},h=()=>lt.default.createElement("div",{className:"tw-relative md:tw-hidden"},lt.default.createElement(V1,{sensors:u,collisionDetection:j1,onDragEnd:m,modifiers:[p(!0)],autoScroll:{enabled:!0,acceleration:10,threshold:{x:0,y:.2}}},lt.default.createElement(H1,{items:t.map(g=>ln(g)),strategy:W1},lt.default.createElement("div",{className:"tw-relative tw-touch-auto tw-space-y-2 tw-overflow-auto tw-pb-2"},t.map(g=>lt.default.createElement(pon,{key:ln(g),id:ln(g),containerRef:d,model:g,onEdit:e,onCopy:n,onDelete:r,onUpdateModel:i}))))));return lt.default.createElement("div",{ref:d,className:"tw-mb-4"},lt.default.createElement(don,{title:l,onRefresh:a,onAdd:o}),lt.default.createElement("div",{className:"tw-hidden md:tw-block"},lt.default.createElement(V1,{sensors:u,collisionDetection:j1,onDragEnd:m,modifiers:[p(!1)]},lt.default.createElement("div",{className:"tw-relative tw-overflow-hidden"},lt.default.createElement(OV,null,lt.default.createElement(RV,null,lt.default.createElement(ES,null,lt.default.createElement(wu,{className:"tw-w-6 tw-px-2"}),lt.default.createElement(wu,{className:"tw-pl-0"},"Model"),lt.default.createElement(wu,null,"Provider"),lt.default.createElement(wu,{className:"tw-text-center"},"Capabilities"),!c&&lt.default.createElement(wu,{className:"tw-text-center"},"Enable"),lt.default.createElement(wu,{className:"tw-text-center"},"CORS"),lt.default.createElement(wu,{className:"tw-w-[100px] tw-text-center"},"Actions"))),lt.default.createElement(LV,{className:"tw-relative"},lt.default.createElement(H1,{items:t.map(g=>ln(g)),strategy:W1},t.map(g=>lt.default.createElement(mon,{key:ln(g),containerRef:d,model:g,onEdit:e,onCopy:n,onDelete:r,onUpdateModel:i,isEmbeddingModel:c})))))))),h())};qe();var RQ=require("obsidian"),Cd=N(U()),Eyt=()=>{let t=tr(),e=Ht(),[n,r]=(0,Cd.useState)(!1),[o,i]=(0,Cd.useState)(!1),s=(g,y=!1)=>{let w={...XD(g,["isBuiltIn","core","projectEnabled","plusExclusive","believerExclusive","capabilities","displayName","dimensions"]),name:`${g.name} (copy)`},v=y?"activeEmbeddingModels":"activeModels";pe(v,[...e[v],w])},a=(g,y=!1)=>{pe(y?"activeEmbeddingModels":"activeModels",g)},l=g=>{let[y,w]=g.split("|"),v=e.activeModels.filter(b=>!(b.name===y&&b.provider===w)),x=e.defaultModelKey;if(g===e.defaultModelKey){let b=v.find(_=>_.enabled);x=b?`${b.name}|${b.provider}`:""}Ls({activeModels:v,defaultModelKey:x})},c=(g,y,w)=>{let v=g?"activeEmbeddingModels":"activeModels",x=e[v].findIndex(b=>b.name===y.name&&b.provider===y.provider);if(x!==-1){let b=[...e[v]];b[x]=w,pe(v,b)}else new RQ.Notice("Could not find model to update"),z("Could not find model to update:",y)},u=g=>{let y=e.activeModels.map(w=>w.name===g.name&&w.provider===g.provider?g:w);pe("activeModels",y)},d=g=>{let[y,w]=g.split("|"),v=e.activeEmbeddingModels.filter(x=>!(x.name===y&&x.provider===w));pe("activeEmbeddingModels",v)},f=g=>{let y=e.activeEmbeddingModels.map(w=>w.name===g.name&&w.provider===g.provider?g:w);pe("activeEmbeddingModels",y)},p=()=>{let g=e.activeModels.filter(w=>!w.isBuiltIn),y=[...Gh,...g];pe("activeModels",y),new RQ.Notice("Chat models refreshed successfully")},m=()=>{let g=e.activeEmbeddingModels.filter(w=>!w.isBuiltIn),y=[...OS,...g];pe("activeEmbeddingModels",y),new RQ.Notice("Embedding models refreshed successfully")},h=(g,y=!1)=>{new y1(t,g,y,c).open()};return Cd.default.createElement("div",{className:"tw-space-y-4"},Cd.default.createElement("section",null,Cd.default.createElement(J0e,{models:e.activeModels,onEdit:g=>h(g),onCopy:g=>s(g),onDelete:l,onAdd:()=>r(!0),onUpdateModel:u,onReorderModels:g=>a(g),onRefresh:p,title:"Chat Models"}),Cd.default.createElement(Z0e,{open:n,onOpenChange:r,onAdd:g=>{let y=[...e.activeModels,g];pe("activeModels",y)},ping:g=>Sl.instance.getCurrentChainManager().chatModelManager.ping(g)}),Cd.default.createElement("div",{className:"tw-space-y-4"},Cd.default.createElement($t,{type:"slider",title:"Conversation turns in context",description:"The number of previous conversation turns to include in the context. Default is 15 turns, i.e. 30 messages.",value:e.contextTurns,onChange:g=>pe("contextTurns",g),min:1,max:50,step:1}),Cd.default.createElement($t,{type:"slider",title:"Auto-compact threshold",description:"Automatically summarize context when it exceeds this token count. Set to maximum to make it less aggressive.",min:64e3,max:1e6,step:64e3,value:e.autoCompactThreshold,onChange:g=>pe("autoCompactThreshold",g)}))),Cd.default.createElement("section",null,Cd.default.createElement(J0e,{models:e.activeEmbeddingModels,onEdit:g=>h(g,!0),onDelete:d,onCopy:g=>s(g,!0),onAdd:()=>i(!0),onUpdateModel:f,onReorderModels:g=>a(g,!0),onRefresh:m,title:"Embedding Models"}),Cd.default.createElement(Z0e,{open:o,onOpenChange:i,onAdd:g=>{let y=[...e.activeEmbeddingModels,g];pe("activeEmbeddingModels",y)},isEmbeddingModel:!0,ping:g=>is.getInstance().ping(g)})))};var yn=N(U()),Myt=require("obsidian");var LQ=class extends Cr{constructor(e,n){super(e,n,"Changing this setting means you have to rebuild the index for your entire vault, do you wish to proceed?","Rebuild Index")}};bi();It();Se();var sn=N(U());vt();var $Q=require("obsidian");Qi();qe();It();var DQ=class extends T1{constructor({app:e,onNoteSelect:n,excludeNotePaths:r,titleOnly:o=!1,chainType:i="copilot_plus"}){super(e,i),this.onNoteSelect=n,this.availableNotes=this.getOrderedNotes(r),this.titleOnly=o}getItems(){if(this.titleOnly){let e=new Map;return this.availableNotes.forEach(n=>{e.set(n.basename,n)}),Array.from(e.values())}return this.availableNotes}getItemText(e){let n=e.path===this.activeNote?.path;return this.formatNoteTitle(e.basename,n,e.extension)}onChooseItem(e,n){if(!PA(e,this.chainType)){new $Q.Notice(XE.NON_MARKDOWN_FILES_RESTRICTED);return}this.onNoteSelect(e)}renderSuggestion(e,n){let r=n.createDiv({cls:"pointer-events-none"});if(e.item instanceof $Q.TFile){let o=r.createDiv(),i=e.item;o.setText(this.formatNoteTitle(i.basename,i===this.activeNote,i.extension)),this.titleOnly||r.createDiv({cls:"mt-1 text-muted text-xs"}).setText(i.path)}}};var Ayt=require("obsidian"),Wh=N(U());rn();ws();function hon({onConfirm:t,onCancel:e}){let[n,r]=(0,Wh.useState)("");return Wh.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Wh.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},Wh.default.createElement("div",null,"Comma separated list of paths, tags, note titles or file extension e.g. folder1, folder1/folder2, #tag1, #tag2, [[note1]], [[note2]], *.jpg, *.excallidraw.md"),Wh.default.createElement(Xn,{placeholder:"Enter the pattern",value:n,onChange:i=>r(i.target.value),onKeyDown:i=>{i.key==="Enter"&&t(n)}})),Wh.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},Wh.default.createElement(X,{variant:"secondary",onClick:e},"Cancel"),Wh.default.createElement(X,{variant:"default",onClick:()=>t(n)},"Confirm")))}var FQ=class extends Ayt.Modal{constructor(n,r){super(n);this.onConfirm=r;this.setTitle("Add Custom Pattern")}onOpen(){let{contentEl:n}=this;this.root=sr(n,this.app);let r=i=>{this.onConfirm(i),this.close()},o=()=>{this.close()};this.root.render(Wh.default.createElement(hon,{onConfirm:r,onCancel:o}))}onClose(){this.root.unmount()}};var kyt=require("obsidian"),cm=N(U());rn();ws();function gon({onConfirm:t,onCancel:e}){let[n,r]=(0,cm.useState)(""),[o,i]=(0,cm.useState)(null),s=l=>{if(l.includes(" ")){i("Extension cannot contain spaces");return}i(null),t(l)};return cm.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-4"},cm.default.createElement("div",{className:"tw-flex tw-flex-col tw-gap-2"},cm.default.createElement(Xn,{placeholder:"Enter the extension (e.g. txt, excalidraw.md)",value:n,onChange:l=>{r(l.target.value),i(null)},onKeyDown:l=>{l.key==="Enter"&&(l.preventDefault(),l.stopPropagation(),s(n))}}),o&&cm.default.createElement("p",{className:"tw-text-sm tw-text-error"},o)),cm.default.createElement("div",{className:"tw-flex tw-justify-end tw-gap-2"},cm.default.createElement(X,{variant:"secondary",onClick:e},"Cancel"),cm.default.createElement(X,{variant:"default",onClick:()=>s(n)},"Confirm")))}var UQ=class extends kyt.Modal{constructor(n,r){super(n);this.onConfirm=r;this.setTitle("Add Extension")}onOpen(){let{contentEl:n}=this;this.root=sr(n,this.app);let r=i=>{this.onConfirm(i),this.close()},o=()=>{this.close()};this.root.render(cm.default.createElement(gon,{onConfirm:r,onCancel:o}))}onClose(){this.root.unmount()}};rn();bi();Kt();fc();var yon={folder:{icon:es,label:"Folder",colorClass:"tw-text-context-manager-yellow"},tag:{icon:_m,label:"Tag",colorClass:"tw-text-context-manager-orange"},note:{icon:Ur,label:"Note",colorClass:"tw-text-context-manager-blue"},extension:{icon:cg,label:"Extension",colorClass:"tw-text-context-manager-green"}},X0e=({value:t,onChange:e,maxCollapsedHeight:n=84,maxExpandedHeight:r=200})=>{let o=tr(),[i,s]=(0,sn.useState)(!1),[a,l]=(0,sn.useState)(!1),[c,u]=(0,sn.useState)(0),d=(0,sn.useRef)(null),f=(0,sn.useRef)(null),p=(0,sn.useRef)(t);p.current=t;let m=V=>[...new Set(eh(V))],h=(0,sn.useMemo)(()=>m(t),[t]),{tagPatterns:g,extensionPatterns:y,folderPatterns:w,notePatterns:v}=(0,sn.useMemo)(()=>ey(h),[h]);(0,sn.useLayoutEffect)(()=>{let V=d.current;if(!V)return;let H=()=>{let fe=V.scrollHeight;u(fe),l(fe>n)};if(H(),typeof ResizeObserver>"u")return;let te=new ResizeObserver(H);return te.observe(V),()=>te.disconnect()},[n,h]);let x=a&&!i,b=i?Math.min(c,r):n,_=V=>{let H=ty({tagPatterns:V.tagPatterns??g,extensionPatterns:V.extensionPatterns??y,folderPatterns:V.folderPatterns??w,notePatterns:V.notePatterns??v});e(H)},T=(V,H)=>{let te=fe=>fe!==V;switch(H){case"folder":_({folderPatterns:w.filter(te)});break;case"tag":_({tagPatterns:g.filter(te)});break;case"note":_({notePatterns:v.filter(te)});break;case"extension":_({extensionPatterns:y.filter(te)});break}},S=()=>ey(m(p.current)),P=(V,H)=>{let te=S();if(!te[V].includes(H)){let fe=ty({...te,[V]:[...te[V],H]});e(fe)}},A=()=>{new S1(o,V=>{P("folderPatterns",V)}).open()},O=()=>{new I1(o,V=>{P("tagPatterns",tB(V))}).open()},D=()=>{new DQ({app:o,onNoteSelect:V=>{P("notePatterns",KN(V))},excludeNotePaths:[],titleOnly:!0}).open()},$=()=>{new UQ(o,V=>{P("extensionPatterns",Hge(V))}).open()},B=()=>{new FQ(o,V=>{let H=S(),te=m(V),{tagPatterns:fe,extensionPatterns:me,folderPatterns:j,notePatterns:G}=ey(te),J=ty({tagPatterns:[...H.tagPatterns,...fe.filter(M=>!H.tagPatterns.includes(M))],extensionPatterns:[...H.extensionPatterns,...me.filter(M=>!H.extensionPatterns.includes(M))],folderPatterns:[...H.folderPatterns,...j.filter(M=>!H.folderPatterns.includes(M))],notePatterns:[...H.notePatterns,...G.filter(M=>!H.notePatterns.includes(M))]});e(J)}).open()},W=(V,H)=>{let te=yon[H],fe=te.icon;return sn.default.createElement(ro,{key:`${H}:${V}`,variant:"secondary",className:"tw-group tw-flex tw-h-7 tw-items-center tw-gap-1.5 tw-py-1 tw-pl-2 tw-pr-1.5 sm:tw-h-6 sm:tw-py-0.5 sm:tw-pl-1.5"},sn.default.createElement(fe,{className:oe("tw-size-4 tw-shrink-0 sm:tw-size-3",te.colorClass)}),sn.default.createElement(go,{className:"tw-max-w-[100px] sm:tw-max-w-[120px]"},V),sn.default.createElement(X,{variant:"ghost2",size:"fit","aria-label":`Remove ${V}`,className:"tw-h-auto tw-p-0",onClick:()=>T(V,H)},sn.default.createElement(Sn,{className:"tw-size-4 tw-shrink-0 tw-text-muted hover:tw-text-warning sm:tw-size-3"})))},F=(0,sn.useMemo)(()=>{let V=[];return w.forEach(H=>V.push({pattern:H,type:"folder"})),g.forEach(H=>V.push({pattern:H,type:"tag"})),v.forEach(H=>V.push({pattern:H,type:"note"})),y.forEach(H=>V.push({pattern:H,type:"extension"})),V},[w,g,v,y]),Z=h.length>0;return sn.default.createElement("div",{ref:f,className:"tw-flex tw-w-full tw-flex-col tw-gap-2"},sn.default.createElement("div",{className:"tw-relative tw-rounded-md tw-border tw-border-solid tw-border-border tw-p-2"},sn.default.createElement("div",{ref:d,className:oe("tw-transition-[max-height] tw-duration-300 tw-ease-in-out",i&&c>r?"tw-overflow-y-auto":"tw-overflow-hidden"),style:{maxHeight:a?b:void 0}},!Z&&sn.default.createElement("div",{className:"tw-py-2 tw-text-center tw-text-sm tw-italic tw-text-muted"},"No patterns configured"),Z&&sn.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-gap-1.5"},F.map(V=>W(V.pattern,V.type)))),x&&sn.default.createElement("div",{className:"copilot-fade-mask-bottom tw-pointer-events-none tw-absolute tw-inset-x-0 tw-bottom-0 tw-h-10 tw-rounded-b-md"})),sn.default.createElement("div",{className:"tw-flex tw-flex-row tw-items-center tw-justify-between"},a?sn.default.createElement(X,{variant:"ghost2",size:"sm",onClick:()=>s(V=>!V),className:"tw-h-9 tw-gap-1 tw-px-3 tw-text-accent sm:tw-h-auto sm:tw-px-2"},i?sn.default.createElement(sn.default.Fragment,null,"Show less ",sn.default.createElement($s,{className:"tw-size-4 sm:tw-size-3"})):sn.default.createElement(sn.default.Fragment,null,"Show ",F.length," items ",sn.default.createElement(hr,{className:"tw-size-4 sm:tw-size-3"}))):sn.default.createElement("div",null),sn.default.createElement(xy,null,sn.default.createElement(by,{asChild:!0},sn.default.createElement(X,{size:"sm",className:"tw-h-9 tw-gap-1 tw-px-3 sm:tw-h-auto sm:tw-px-2"},sn.default.createElement(Lc,{className:"tw-size-5 sm:tw-size-4"}),"Add...")),sn.default.createElement(sd,{align:"end",container:f.current},sn.default.createElement(wr,{onSelect:A,className:"tw-py-2.5 sm:tw-py-1.5"},sn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},sn.default.createElement(es,{className:"tw-size-5 tw-text-context-manager-yellow sm:tw-size-4"}),"Folder")),sn.default.createElement(wr,{onSelect:O,className:"tw-py-2.5 sm:tw-py-1.5"},sn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},sn.default.createElement(_m,{className:"tw-size-5 tw-text-context-manager-orange sm:tw-size-4"}),"Tag")),sn.default.createElement(wr,{onSelect:D,className:"tw-py-2.5 sm:tw-py-1.5"},sn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},sn.default.createElement(Ur,{className:"tw-size-5 tw-text-context-manager-blue sm:tw-size-4"}),"Note")),sn.default.createElement(wr,{onSelect:$,className:"tw-py-2.5 sm:tw-py-1.5"},sn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},sn.default.createElement(cg,{className:"tw-size-5 tw-text-context-manager-green sm:tw-size-4"}),"Extension")),sn.default.createElement(wr,{onSelect:B,className:"tw-py-2.5 sm:tw-py-1.5"},sn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},sn.default.createElement(Nd,{className:"tw-size-5 tw-text-context-manager-purple sm:tw-size-4"}),"Custom"))))))};var Nyt=()=>{let t=tr(),e=Ht(),n=e.enableMiyo,r=e.activeEmbeddingModels,o=async i=>{if(i!==e.embeddingModelKey){if(e.enableSemanticSearchV3){new LQ(t,async()=>{pe("embeddingModelKey",i),await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0})}).open();return}pe("embeddingModelKey",i),new Myt.Notice("Embedding model saved. Enable Semantic Search to build the index.")}};return yn.default.createElement("div",{className:"tw-space-y-4"},yn.default.createElement("section",null,yn.default.createElement("div",{className:"tw-space-y-4"},yn.default.createElement($t,{type:"switch",title:"Enable Semantic Search",description:"Enable semantic search for meaning-based document retrieval. When disabled, uses fast lexical search only. Use 'Refresh Vault Index' or 'Force Reindex Vault' to build the embedding index.",checked:e.enableSemanticSearchV3,onCheckedChange:i=>{new _1(t,async()=>{pe("enableSemanticSearchV3",i),!i&&e.enableMiyo&&pe("enableMiyo",!1),i&&await(await Promise.resolve().then(()=>(ei(),ji))).default.getInstance().indexVaultToVectorStore(!1,{userInitiated:!0})},i).open()}}),yn.default.createElement($t,{type:"switch",title:"Enable Inline Citations (experimental)",description:"When enabled, AI responses will include footnote-style citations within the text and numbered sources at the end. This is an experimental feature and may not work as expected for all models.",checked:e.enableInlineCitations,onCheckedChange:i=>pe("enableInlineCitations",i)}),yn.default.createElement($t,{type:"select",title:"Embedding Model",description:yn.default.createElement("div",{className:"tw-space-y-2"},yn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},yn.default.createElement("span",{className:"tw-font-medium tw-leading-none tw-text-accent"},"Powers Semantic Vault Search and Relevant Notes. Enable Semantic Search to use it."),yn.default.createElement(Nn,{content:yn.default.createElement("div",{className:"tw-flex tw-max-w-96 tw-flex-col tw-gap-2"},yn.default.createElement("div",{className:"tw-pt-2 tw-text-sm tw-text-muted"},"This model converts text into vector representations, essential for semantic search and Question Answering (QA) functionality. Changing the embedding model will:"),yn.default.createElement("ul",{className:"tw-pl-4 tw-text-sm tw-text-muted"},yn.default.createElement("li",null,"Require rebuilding your vault's vector index"),yn.default.createElement("li",null,"Affect semantic search quality"),yn.default.createElement("li",null,"Impact Question Answering feature performance")))})),n&&yn.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Miyo search is enabled, so embeddings are generated by Miyo and this setting is ignored.")),value:e.embeddingModelKey,onChange:o,options:r.map(i=>({label:OR(i),value:ln(i)})),placeholder:"Model",disabled:n}),yn.default.createElement($t,{type:"select",title:"Auto-Index Strategy",description:yn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},yn.default.createElement("span",{className:"tw-leading-none"},"Decide when you want the vault to be indexed."),yn.default.createElement(Nn,{content:yn.default.createElement("div",{className:"tw-space-y-2 tw-py-2"},yn.default.createElement("div",{className:"tw-space-y-1"},yn.default.createElement("div",{className:"tw-text-sm tw-text-muted"},"Choose when to index your vault:"),yn.default.createElement("ul",{className:"tw-list-disc tw-space-y-1 tw-pl-2 tw-text-sm"},yn.default.createElement("li",null,yn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},yn.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"NEVER:"),yn.default.createElement("span",null,"Manual indexing via command or refresh only"))),yn.default.createElement("li",null,yn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},yn.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"ON STARTUP:"),yn.default.createElement("span",null,"Index updates when plugin loads or reloads"))),yn.default.createElement("li",null,yn.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},yn.default.createElement("strong",{className:"tw-inline-block tw-whitespace-nowrap"},"ON MODE SWITCH:"),yn.default.createElement("span",null,"Updates when entering QA mode (Recommended)"))))),yn.default.createElement("p",{className:"tw-text-sm tw-text-callout-warning"},"Warning: Cost implications for large vaults with paid models"))})),value:e.indexVaultToVectorStore,onChange:i=>{pe("indexVaultToVectorStore",i)},options:hPe.map(i=>({label:i,value:i})),placeholder:"Strategy"}),yn.default.createElement($t,{type:"slider",title:"Max Sources",description:"Copilot goes through your vault to find relevant notes and passes the top N to the LLM. Default for N is 30. Increase if you want more notes included in the answer generation step.",min:1,max:128,step:1,value:e.maxSourceChunks,onChange:i=>pe("maxSourceChunks",i)}),e.enableSemanticSearchV3&&yn.default.createElement(yn.default.Fragment,null,yn.default.createElement($t,{type:"slider",title:"Requests per Minute",description:"Default is 60. Decrease if you are rate limited by your embedding provider.",min:10,max:60,step:10,value:Math.min(e.embeddingRequestsPerMin,60),onChange:i=>pe("embeddingRequestsPerMin",i)}),yn.default.createElement($t,{type:"slider",title:"Embedding Batch Size",description:"Default is 16. Increase if you are rate limited by your embedding provider.",min:1,max:128,step:1,value:e.embeddingBatchSize,onChange:i=>pe("embeddingBatchSize",i)}),yn.default.createElement($t,{type:"select",title:"Number of Partitions",description:"Number of partitions for Copilot index. Default is 1. Increase if you have issues indexing large vaults. Warning: Changes require clearing and rebuilding the index!",value:String(e.numPartitions||1),onChange:i=>pe("numPartitions",Number(i)),options:[{label:"1",value:"1"},{label:"2",value:"2"},{label:"4",value:"4"},{label:"8",value:"8"},{label:"16",value:"16"},{label:"32",value:"32"},{label:"40",value:"40"}],placeholder:"Select partitions"})),yn.default.createElement($t,{type:"slider",title:"Lexical Search RAM Limit",description:"Maximum RAM usage for full-text search index. Lower values use less memory but may limit search performance on large vaults. Default is 100 MB.",min:20,max:1e3,step:20,value:e.lexicalSearchRamLimit||100,onChange:i=>pe("lexicalSearchRamLimit",i),suffix:" MB"}),yn.default.createElement($t,{type:"switch",title:"Enable Folder and Graph Boosts",description:"Enable folder and graph-based relevance boosts for lexical search results. When disabled, provides pure keyword-based relevance scoring without folder or connection-based adjustments.",checked:e.enableLexicalBoosts,onCheckedChange:i=>pe("enableLexicalBoosts",i)}),yn.default.createElement($t,{type:"custom",title:"Exclusions",description:"Exclude folders, tags, note titles or file extensions from being indexed. Previously indexed files will remain until a force re-index is performed."},yn.default.createElement(X0e,{value:e.qaExclusions,onChange:i=>pe("qaExclusions",i)})),yn.default.createElement($t,{type:"custom",title:"Inclusions",description:"Index only the specified paths, tags, or note titles. Exclusions take precedence over inclusions. Previously indexed files will remain until a force re-index is performed."},yn.default.createElement(X0e,{value:e.qaInclusions,onChange:i=>pe("qaInclusions",i)})),yn.default.createElement($t,{type:"switch",title:"Enable Obsidian Sync for Copilot index",description:`If enabled, store the semantic index in ${t.vault.configDir} so it syncs with Obsidian Sync. If disabled, store it under .copilot/ at the vault root.`,checked:e.enableIndexSync,onCheckedChange:i=>pe("enableIndexSync",i)}),yn.default.createElement($t,{type:"switch",title:"Disable index loading on mobile",description:"When enabled, Copilot index won't be loaded on mobile devices to save resources. Only chat mode will be available. Any existing index from desktop sync will be preserved. Uncheck to enable QA modes on mobile.",checked:e.disableIndexOnMobile,onCheckedChange:i=>pe("disableIndexOnMobile",i)}))))};var Ryt=["basic","model","QA","command","plus","advanced"],won={basic:Sr.default.createElement(d$,{className:"tw-size-5"}),model:Sr.default.createElement(p$,{className:"tw-size-5"}),QA:Sr.default.createElement(xm,{className:"tw-size-5"}),command:Sr.default.createElement(Qx,{className:"tw-size-5"}),plus:Sr.default.createElement(ql,{className:"tw-size-5"}),advanced:Sr.default.createElement(Nd,{className:"tw-size-5"})},von={basic:()=>Sr.default.createElement(_yt,null),model:()=>Sr.default.createElement(Eyt,null),QA:()=>Sr.default.createElement(Nyt,null),command:()=>Sr.default.createElement(uyt,null),plus:()=>Sr.default.createElement(Iyt,null),advanced:()=>Sr.default.createElement(pyt,null)},Oyt=Ryt.map(t=>({id:t,icon:won[t],label:t.charAt(0).toUpperCase()+t.slice(1)})),xon=()=>{let{selectedTab:t,setSelectedTab:e}=SS();return Sr.default.createElement("div",{className:"tw-flex tw-flex-col"},Sr.default.createElement("div",{className:"tw-flex tw-flex-wrap tw-rounded-lg"},Oyt.map((n,r)=>Sr.default.createElement(Uht,{key:n.id,tab:n,isSelected:t===n.id,onClick:()=>e(n.id),isFirst:r===0,isLast:r===Oyt.length-1}))),Sr.default.createElement("div",{className:"tw-w-full tw-border tw-border-solid"}),Sr.default.createElement("div",null,Ryt.map(n=>{let r=von[n];return Sr.default.createElement(Bht,{key:n,id:n,isSelected:t===n},Sr.default.createElement(r,null))})))},bon=({plugin:t})=>{let[e,n]=Sr.default.useState(0),{latestVersion:r,hasUpdate:o}=gX(t.manifest.version),i=()=>{new nQ(t.app,()=>{jee(),n(a=>a+1)}).open()};return Sr.default.createElement(jht,null,Sr.default.createElement("div",null,Sr.default.createElement("div",{className:"tw-mb-4 tw-flex tw-flex-col tw-gap-2"},Sr.default.createElement("div",{role:"heading","aria-level":1,className:"tw-flex tw-flex-col tw-gap-2 tw-text-base tw-font-semibold sm:tw-flex-row sm:tw-items-center sm:tw-justify-between"},Sr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-2"},Sr.default.createElement("span",null,"Copilot Settings"),Sr.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},Sr.default.createElement("span",{className:"tw-text-xs tw-font-normal tw-text-muted"},"v",t.manifest.version),r&&Sr.default.createElement(Sr.default.Fragment,null,o?Sr.default.createElement("a",{href:"obsidian://show-plugin?id=copilot",target:"_blank",rel:"noopener noreferrer",className:"tw-text-xs tw-font-normal tw-text-accent hover:tw-underline"},"(Update to v",r,")"):Sr.default.createElement("span",{className:"tw-text-xs tw-font-normal tw-text-normal"}," ","(up to date)")))),Sr.default.createElement("div",{className:"tw-self-end sm:tw-self-auto"},Sr.default.createElement(X,{variant:"secondary",size:"sm",onClick:i},"Reset Settings")))),Sr.default.createElement(xon,{key:e})))},Lyt=bon;ws();var BQ=class extends HV.PluginSettingTab{constructor(e,n){super(e,n),this.plugin=n}async reloadPlugin(){try{let e=this.app.workspace.getLeavesOfType(No)[0]?.view;if(e&&q().enableRecentConversations)try{let o=this.plugin.projectManager.getCurrentChainManager().chatModelManager.getChatModel();this.plugin.userMemoryManager.addRecentConversation(this.plugin.chatUIState.getMessages(),o)}catch(r){k("Failed to analyze chat messages for memory:",r)}e&&q().autosaveChat&&await this.plugin.autosaveCurrentChat();let n=this.plugin.app;await n.plugins.disablePlugin("copilot"),await n.plugins.enablePlugin("copilot"),n.setting.openTabById("copilot").display(),new HV.Notice("Plugin reloaded successfully.")}catch(e){new HV.Notice("Failed to reload the plugin. Please reload manually."),z("Error reloading plugin:",e)}}display(){let{containerEl:e}=this;e.empty(),e.addClass("tw-select-text");let n=e.createDiv("div");sr(n,this.app).render(Dyt.default.createElement(Lyt,{plugin:this.plugin}))}};Se();ye();var zQ=class{constructor(e){this.chatManager=e;this.listeners=new Set;this.chatManager.setOnMessageCreatedCallback(()=>{this.notifyListeners()})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>{try{e()}catch(n){k("[ChatUIState] Error in listener:",n)}})}async sendMessage(e,n,r,o=!1,i=!1,s,a){let l=await this.chatManager.sendMessage(e,n,r,o,i,s,a);return this.notifyListeners(),l}async editMessage(e,n,r,o=!1){let i=await this.chatManager.editMessage(e,n,r,o);return i&&this.notifyListeners(),i}async regenerateMessage(e,n,r){let o=await this.chatManager.regenerateMessage(e,n,i=>{r(i),this.notifyListeners()},()=>{this.notifyListeners()});return o&&this.notifyListeners(),o}async deleteMessage(e){let n=await this.chatManager.deleteMessage(e);return n&&this.notifyListeners(),n}clearMessages(){this.chatManager.clearMessages(),this.notifyListeners()}async truncateAfterMessageId(e){await this.chatManager.truncateAfterMessageId(e),this.notifyListeners()}getMessages(){return this.chatManager.getDisplayMessages()}getMessage(e){return this.chatManager.getMessage(e)}getLLMMessage(e){return this.chatManager.getLLMMessage(e)}getLLMMessages(){return this.chatManager.getLLMMessages()}get chatHistory(){return this.getMessages()}addMessage(e){this.chatManager.addMessage(e),this.notifyListeners()}clearChatHistory(){this.clearMessages()}async replaceMessages(e){await this.chatManager.loadMessages(e),this.notifyListeners()}getDebugInfo(){return this.chatManager.getDebugInfo()}async loadMessages(e){await this.chatManager.loadMessages(e),this.notifyListeners()}async handleProjectSwitch(){await this.chatManager.handleProjectSwitch(),this.notifyListeners()}async saveChat(e){await this.chatManager.saveChat(e)}async loadChatHistory(e){await this.chatManager.loadChatHistory(e),this.notifyListeners()}};var twt=require("obsidian");var Xyt=require("@codemirror/state"),Qyt=require("@codemirror/view");var Zyt=N(U());var KV=new WeakMap;function Con(t){return t.startsWith("--")?t:t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}var $yt=new Set(["z-index","zIndex","opacity","flex","flex-grow","flexGrow","flex-shrink","flexShrink","font-weight","fontWeight","line-height","lineHeight","order","orphans","widows","tab-size","tabSize","column-count","columnCount"]);function _on(t){let e=new Map;for(let[n,r]of Object.entries(t)){if(r==null)continue;let o=Con(n),i;typeof r=="number"&&!n.startsWith("--")?i=$yt.has(n)||$yt.has(o)?String(r):`${r}px`:i=String(r),e.set(o,i)}return e}function Fyt(t,e){if(!e)return;let n=`${e}-`;Array.from(t.classList).filter(o=>o.startsWith(n)).forEach(o=>{t.classList.remove(o)})}function jQ(t,e,n){if(!t)return;let r=_on(n),o=KV.get(t);o&&o.prefix&&o.prefix!==e&&Fyt(t,o.prefix);let i=o?.properties??new Set,s=new Set,a={};if(i.forEach(l=>{r.has(l)||(a[l]="")}),r.forEach((l,c)=>{a[c]=l,s.add(c)}),Object.keys(a).length>0&&t.setCssProps(a),s.size===0){KV.delete(t);return}KV.set(t,{properties:s,prefix:e})}function Uyt(t){let e=KV.get(t);if(!e)return;let n={};e.properties.forEach(r=>{n[r]=""}),Object.keys(n).length>0&&t.setCssProps(n),e.prefix&&Fyt(t,e.prefix),KV.delete(t)}var an=N(U()),KE=require("obsidian");vt();Ir();Se();qe();var Tf=N(U()),Q0e=require("obsidian");qh();qe();ye();function Byt(t){let{selectedText:e,selectedModelKey:n,includeNoteContext:r,settings:o}=t,[i,s]=(0,Tf.useState)([]),a=(0,Tf.useRef)(!0);(0,Tf.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let l=(0,Tf.useMemo)(()=>{try{let w=$f(n,o.activeModels);return w.enabled?w:(ee("Selected model is disabled; falling back to first enabled model.",{selectedModelKey:n}),o.activeModels.find(v=>v.enabled)??null)}catch{return ee("Selected model not found; falling back to first enabled model."),o.activeModels.find(w=>w.enabled)??null}},[n,o.activeModels]),{isStreaming:c,streamingText:u,runTurn:d,stop:f,reset:p}=aZ({model:l,systemPrompt:Q9,excludeThinking:!0,onNoModel:()=>{z("No active model is configured. Please configure a model in Copilot settings."),new Q0e.Notice("No active model configured. Please configure a model in Copilot settings.")},onNonAbortError:w=>{z("Error generating response:",w),new Q0e.Notice("Error generating response. Please try again.")}}),m=(0,Tf.useCallback)(async w=>{if(!w.trim())return;let v={id:si(),role:"user",content:w,timestamp:Date.now()};s(b=>[...b,v]);let x=await d(async b=>{let _=w;return b.isFirstTurn&&(_=eY(w,r)),b.signal.aborted?"":await Tj(_,e,!b.isFirstTurn)});if(a.current)if(x){let b={id:si(),role:"assistant",content:x,timestamp:Date.now()};s(_=>[..._,b])}else s(b=>b[b.length-1]?.id===v.id?b.slice(0,-1):b)},[r,d,e]),h=(0,Tf.useCallback)(()=>{f()},[f]),g=(0,Tf.useCallback)(()=>{s([]),p()},[p]);return{messages:(0,Tf.useMemo)(()=>!c||!u?i:[...i,{id:"streaming",role:"assistant",content:u,timestamp:Date.now()}],[i,c,u]),isStreaming:c,sendMessage:m,stop:h,clear:g}}var ms=N(U()),zyt=require("obsidian");vt();rn();ye();var jyt=ms.default.memo(function({message:e,isStreaming:n,isLastAssistantMessage:r,onCopy:o,onInsert:i,onReplace:s,hasSelection:a,isReplaceValid:l,replaceInvalidReason:c,isDisabledDueToStreaming:u,filePathSnapshot:d,plugin:f}){let p=(0,ms.useRef)(null);if((0,ms.useEffect)(()=>{if(e.role!=="assistant"||n)return;let h=!1;return(async()=>{let y=p.current;if(!y)return;y.empty();let w=d??"";try{let v=oL(e.content);await zyt.MarkdownRenderer.renderMarkdown(v,y,w,f)}catch(v){if(z("Failed to render markdown:",v),h)return;y.empty(),y.textContent=e.content}h||y.classList.add("markdown-rendered")})(),()=>{h=!0}},[e.content,e.role,n,d,f]),e.role==="user")return ms.default.createElement("div",{className:"tw-max-w-[85%] tw-self-end tw-rounded-lg tw-rounded-br-sm tw-bg-interactive-accent tw-px-3 tw-py-2 tw-text-on-accent"},ms.default.createElement("div",{"data-quick-ask-selectable":!0,className:"tw-whitespace-pre-wrap tw-break-words tw-text-sm"},e.content));if(n)return ms.default.createElement("div",{className:"tw-max-w-[95%] tw-self-start tw-rounded-lg tw-rounded-bl-sm tw-bg-secondary tw-px-3 tw-py-2"},ms.default.createElement("div",{"data-quick-ask-selectable":!0,className:"tw-whitespace-pre-wrap tw-break-words tw-text-sm tw-text-normal"},e.content,ms.default.createElement("span",{className:"tw-animate-pulse tw-text-accent"},"\u258A")));let m=r?"tw-opacity-100":"tw-opacity-0 group-hover/message:tw-opacity-100";return ms.default.createElement("div",{className:"tw-group/message tw-max-w-[95%] tw-self-start"},ms.default.createElement("div",{className:"tw-rounded-lg tw-rounded-bl-sm tw-bg-secondary tw-px-3 tw-py-2"},ms.default.createElement("div",{ref:p,"data-quick-ask-selectable":!0,className:"tw-text-sm [&.markdown-rendered]:tw-text-sm [&_code]:tw-text-xs [&_p]:tw-my-1 [&_pre]:tw-my-2"})),e.content&&ms.default.createElement("div",{className:`tw-mt-1 tw-flex tw-items-center tw-gap-0.5 tw-transition-opacity ${m}`},ms.default.createElement(X,{variant:"ghost2",size:"icon",className:"tw-size-5 hover:tw-bg-modifier-hover",onClick:()=>o(e.id),title:"Copy to clipboard"},ms.default.createElement(Eu,{className:"tw-size-3"})),ms.default.createElement(X,{variant:"ghost2",size:"icon",className:"tw-size-5 hover:tw-bg-modifier-hover",onClick:()=>i(e.id),title:"Insert at cursor"},ms.default.createElement(KS,{className:"tw-size-3"})),a&&ms.default.createElement(X,{variant:"ghost2",size:"icon",className:"tw-size-5 hover:tw-bg-modifier-hover",onClick:()=>s(e.id),disabled:!l,title:u?"Stop generating to replace":l?"Replace selection":rL(c)},ms.default.createElement(E$,{className:"tw-size-3"}))))});var Mo=N(U());Kt();ye();It();var Vyt=Mo.default.memo(function({value:e,onChange:n,onSubmit:r,sendShortcut:o="enter",placeholder:i="Ask a question...",disabled:s=!1,className:a="",onNotesChange:l,onNotesRemoved:c,onFoldersChange:u,onFoldersRemoved:d,onActiveNoteAdded:f,onActiveNoteRemoved:p,onEditorReady:m,currentActiveFile:h=null}){let[g,y]=(0,Mo.useState)(null),w=(0,Mo.useCallback)(_=>{y(()=>_)},[]);(0,Mo.useEffect)(()=>{if(g){let _=window.setTimeout(()=>{g()},50);return()=>window.clearTimeout(_)}},[g]);let v=Mo.default.useMemo(()=>({namespace:"QuickAskEditor",theme:{root:"tw-outline-none",paragraph:"tw-m-0"},nodes:[aS,cS,fx,px,uS],onError:_=>{z("QuickAskInput Lexical error:",_)},editable:!s}),[s]),x=(0,Mo.useCallback)(_=>{_.read(()=>{let S=mr().getTextContent();n(S)})},[n]),b=(0,Mo.useCallback)(_=>{m?.(_)},[m]);return Mo.default.createElement(TJ,{initialConfig:v},Mo.default.createElement(wJ,{currentActiveFile:h},Mo.default.createElement("div",{className:oe("tw-relative",a)},Mo.default.createElement(OJ,{contentEditable:Mo.default.createElement(RJ,{className:"tw-max-h-48 tw-min-h-12 tw-w-full tw-resize-none tw-overflow-y-auto tw-border-none tw-bg-transparent tw-px-1 tw-py-2 tw-pr-8 tw-text-sm tw-text-normal tw-outline-none","aria-label":"Quick Ask input"}),placeholder:Mo.default.createElement("div",{className:"tw-pointer-events-none tw-absolute tw-left-1 tw-top-2 tw-select-none tw-text-sm tw-text-muted/60"},i),ErrorBoundary:zJ}),Mo.default.createElement(BJ,{onChange:x}),Mo.default.createElement(FJ,null),Mo.default.createElement(YJ,{onSubmit:r,sendShortcut:o}),Mo.default.createElement(ZJ,{value:e}),Mo.default.createElement(JJ,{onFocus:w,onEditorReady:b}),Mo.default.createElement(QJ,{onNotesChange:l,onNotesRemoved:c}),Mo.default.createElement(eX,{onFoldersChange:u,onFoldersRemoved:d}),Mo.default.createElement(tX,{onActiveNoteAdded:f,onActiveNoteRemoved:p}),Mo.default.createElement(GJ,null),Mo.default.createElement(qJ,{isCopilotPlus:!1,currentActiveFile:h}))))});rn();function Wyt({plugin:t,view:e,selectedText:n,replaceGuard:r,onClose:o,onDragOffset:i,onResizeStart:s,hasCustomHeight:a}){let[l,c]=(0,an.useState)(""),u=(0,an.useRef)(null),d=(0,an.useRef)(null),f=(0,an.useRef)(!0),p=t.app.workspace.getActiveFile(),h=(0,an.useRef)(p?.path??null).current,g=Ht(),[y]=qx(),w=g.quickCommandModelKey??y,[v,x]=(0,an.useState)(()=>g.quickCommandIncludeNoteContext),{messages:b,isStreaming:_,sendMessage:T,stop:S,clear:P}=Byt({selectedText:n,selectedModelKey:w,includeNoteContext:v,settings:g}),A=b.length>0,O=r.getRange(),D=!!O&&O.from!==O.to,$=b[b.length-1]?.id,B=(0,an.useMemo)(()=>b.reduce((Y,re,ae)=>re.role==="assistant"?ae:Y,-1),[b]),W=(0,an.useCallback)(()=>{let Y=d.current?.getBoundingClientRect();return Y?{x:Y.left,y:Y.top}:{x:0,y:0}},[]),F=(0,an.useCallback)(Y=>{i?.(Y)},[i]),{handleMouseDown:Z}=nY({dragRef:d,bounds:null,writeToDom:!1,getPosition:W,onPositionChange:F}),V=(0,an.useCallback)(Y=>re=>{re.preventDefault(),re.stopPropagation(),s?.(Y,{x:re.clientX,y:re.clientY})},[s]),H=(0,an.useCallback)(async()=>{if(!l.trim()||_)return;let Y=l;c(""),await T(Y)},[l,_,T]),te=(0,an.useCallback)(Y=>{Y.stopPropagation(),Y.key==="Escape"&&!Y.defaultPrevented&&(Y.preventDefault(),o())},[o]),fe=(0,an.useCallback)(Y=>{Y.stopPropagation()},[]);(0,an.useEffect)(()=>{let Y=u.current;if(!Y)return;let re=24,ae=()=>Y.scrollHeight-Y.scrollTop-Y.clientHeight<=re,ve=()=>{f.current=ae()};return f.current=ae(),Y.addEventListener("scroll",ve),()=>{Y.removeEventListener("scroll",ve)}},[A]),(0,an.useEffect)(()=>{let Y=u.current;Y&&f.current&&(Y.scrollTop=Y.scrollHeight)},[b]);let me=(0,an.useCallback)(async Y=>{let re=b.find(ae=>ae.id===Y);if(re&&re.role==="assistant"){let ae=ng(re.content);try{await navigator.clipboard.writeText(ae),new KE.Notice("Copied to clipboard")}catch{new KE.Notice("Failed to copy to clipboard")}}},[b]),j=(0,an.useCallback)(Y=>{let re=b.find(ae=>ae.id===Y);if(!(!re||re.role!=="assistant"))try{let ae=ng(re.content),ve=e.state.selection.main.to,Te=e.state.toText(ae);e.dispatch({changes:{from:ve,to:ve,insert:Te},selection:{anchor:ve,head:ve+Te.length}}),e.focus(),new KE.Notice("Inserted"),o()}catch{new KE.Notice("Failed to insert. Editor may have changed.")}},[b,e,o]),G=(0,an.useCallback)(Y=>{let re=b.find(Te=>Te.id===Y);if(!re||re.role!=="assistant")return;let ae=ng(re.content),ve=r.replace(ae);if(!ve.ok){new KE.Notice(ve.message??"Cannot replace.");return}new KE.Notice("Replaced"),o()},[b,r,o]),J=(0,an.useCallback)(Y=>{pe("quickCommandModelKey",Y)},[]),M=(0,an.useCallback)(Y=>{x(Y),pe("quickCommandIncludeNoteContext",Y)},[]),E=D&&!_?r.validate():null,R=!!E?.ok,L=E?.reason??null,K=D&&_;return an.default.createElement("div",{ref:d,className:`tw-group tw-relative tw-flex tw-size-full tw-flex-col tw-rounded-lg tw-rounded-b-none tw-border tw-border-solid tw-border-border tw-bg-primary tw-shadow-lg${A&&!a?" tw-max-h-[min(500px,70vh)]":""}`,onKeyDown:te,onKeyUp:fe,onBeforeInput:fe,onInput:fe,onMouseDown:fe,onMouseUp:fe,onClick:fe},an.default.createElement("div",{className:"tw-relative tw-flex-none"},an.default.createElement("div",{className:"tw-flex tw-h-4 tw-cursor-grab tw-items-center tw-justify-center hover:tw-bg-[color-mix(in_srgb,var(--background-modifier-hover)_20%,transparent)] active:tw-cursor-grabbing",onMouseDown:Z},an.default.createElement("div",{className:"tw-h-[5px] tw-w-16 tw-rounded-sm tw-bg-[color-mix(in_srgb,var(--text-muted)_40%,transparent)] hover:tw-bg-[color-mix(in_srgb,var(--text-muted)_65%,transparent)]"})),an.default.createElement(X,{className:"tw-absolute tw-right-2 tw-top-1 tw-rounded tw-p-1 tw-text-normal",variant:"ghost2",onClick:o,title:"Close"},an.default.createElement(Sn,{className:"tw-size-4"}))),A&&an.default.createElement("div",{ref:u,"data-quick-ask-scroll":"true",className:"tw-flex tw-min-h-0 tw-flex-1 tw-flex-col tw-gap-2 tw-overflow-y-auto tw-px-3 tw-py-2"},b.map((Y,re)=>an.default.createElement(jyt,{key:Y.id,message:Y,isStreaming:_&&Y.id===$&&Y.role==="assistant",isLastAssistantMessage:Y.role==="assistant"&&re===B,onCopy:me,onInsert:j,onReplace:G,hasSelection:D,isReplaceValid:R,replaceInvalidReason:L,isDisabledDueToStreaming:K,filePathSnapshot:h,plugin:t}))),!A&&a&&an.default.createElement("div",{className:"tw-flex-1"}),an.default.createElement("div",{className:"tw-px-3 tw-pb-1 tw-pt-2"},an.default.createElement(Vyt,{value:l,onChange:c,onSubmit:H,sendShortcut:g.defaultSendShortcut,placeholder:_?"Generating...":"Ask a question... ",currentActiveFile:p})),an.default.createElement("div",{className:"tw-mt-auto tw-flex tw-items-center tw-justify-between tw-gap-2 tw-border-t tw-border-solid tw-border-border tw-px-3 tw-py-1.5"},an.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},an.default.createElement(eL,{size:"sm",variant:"ghost",value:w,onChange:J,disabled:_}),an.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1.5"},an.default.createElement(To,{id:"quickAskIncludeContext",checked:v,onCheckedChange:Y=>M(!!Y),className:"tw-size-3.5",disabled:_}),an.default.createElement("label",{htmlFor:"quickAskIncludeContext",className:"tw-cursor-pointer tw-text-xs tw-text-muted"},"Note"),an.default.createElement(Nn,{content:"Include the active note's content as context",side:"top"}))),an.default.createElement("div",{className:"tw-flex tw-items-center tw-gap-1"},A&&an.default.createElement(X,{variant:"ghost2",size:"icon",className:"hover:tw-bg-modifier-hover",onClick:P,title:"Clear conversation"},an.default.createElement(T$,{className:"tw-size-4"})),_?an.default.createElement(X,{variant:"destructive",size:"icon",onClick:S,title:"Stop generating"},an.default.createElement(QS,{className:"tw-size-4"})):an.default.createElement(X,{variant:"default",size:"icon",onClick:H,disabled:!l.trim(),title:"Send message"},an.default.createElement(JS,{className:"tw-size-4"})))),an.default.createElement("div",{className:"tw-absolute tw-right-0 tw-top-4 tw-h-[calc(100%-16px)] tw-w-1 tw-cursor-ew-resize",onMouseDown:V("right")}),an.default.createElement("div",{className:"tw-absolute tw-bottom-0 tw-left-0 tw-h-1 tw-w-full tw-cursor-ns-resize",onMouseDown:V("bottom")}),an.default.createElement("div",{className:"quick-ask-resize-indicator-left tw-absolute tw-bottom-0 tw-left-0 tw-size-3 tw-cursor-nesw-resize",onMouseDown:V("bottom-left")}),an.default.createElement("div",{className:"quick-ask-resize-indicator-right tw-absolute tw-bottom-0 tw-right-0 tw-z-[10] tw-size-3 tw-cursor-nwse-resize",onMouseDown:V("bottom-right")}))}ws();var vu=12,MS=6,Hyt=.83,Kyt=.9,qyt=420,Gyt=560,ePe=300,Yyt=200,Os=class Os{constructor(e){this.options=e;this.root=null;this.overlayContainer=null;this.cleanupCallbacks=[];this.overlayHost=null;this.ownerDocument=null;this.ownerWindow=null;this.rafId=null;this.panelRerenderRafId=null;this.resizeObserver=null;this.isClosing=!1;this.closeAnimationTimeout=null;this.dragPosition=null;this.resizeSize=null;this.hasUserResizedHeight=!1;this.bottomAnchorPos=null;this.topAnchorPos=null;this.focusAnchorPos=null;this.placementSide=null;this.isResizing=!1;this.resizeDirection=null;this.resizeStartRect=null;this.resizeStartMouse=null;this.resizeRafId=null;this.closeWithAnimation=()=>{if(!this.isClosing)if(this.isClosing=!0,this.overlayContainer){this.overlayContainer.classList.add("closing");let e=r=>{r.target!==this.overlayContainer||r.animationName!=="copilot-quick-ask-fade-out"||(this.overlayContainer?.removeEventListener("animationend",e),this.closeAnimationTimeout!==null&&(window.clearTimeout(this.closeAnimationTimeout),this.closeAnimationTimeout=null),this.options.onClose())};this.overlayContainer.addEventListener("animationend",e);let n=this.ownerWindow??window;this.closeAnimationTimeout=n.setTimeout(()=>{this.overlayContainer?.removeEventListener("animationend",e),this.closeAnimationTimeout=null,this.options.onClose()},300)}else this.options.onClose()};this.handleDragOffset=e=>{this.dragPosition=e,this.updateDragPosition()};this.handleResizeStart=(e,n)=>{if(this.isResizing)return;let r=this.overlayContainer?.getBoundingClientRect();if(!r)return;this.isResizing=!0,this.resizeDirection=e,this.resizeStartRect=r,this.resizeStartMouse=n;let o=this.ownerDocument??activeDocument,i=o.body,s={right:"ew-resize",bottom:"ns-resize","bottom-left":"nesw-resize","bottom-right":"nwse-resize"};i.setCssProps({"--copilot-resize-cursor":s[e]??"default"}),i.classList.add("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]"),o.addEventListener("mousemove",this.handleResizeMove,!0),o.addEventListener("mouseup",this.handleResizeEnd,!0)};this.handleResizeMove=e=>{if(!this.isResizing||!this.resizeStartRect||!this.resizeStartMouse)return;let n=this.ownerWindow??window;this.resizeRafId!==null&&n.cancelAnimationFrame(this.resizeRafId),this.resizeRafId=n.requestAnimationFrame(()=>{this.resizeRafId=null,this.applyResize(e.clientX,e.clientY)})};this.handleResizeEnd=()=>{this.cleanupResize(),this.renderPanel()}}mount(e,n,r){this.bottomAnchorPos=e,this.topAnchorPos=typeof n=="number"?n:null,this.focusAnchorPos=typeof r=="number"?r:null,this.placementSide=null,Os.currentInstance=this,this.mountOverlay(),this.setupGlobalListeners(),this.schedulePositionUpdate()}destroy(){Os.currentInstance===this&&(Os.currentInstance=null);let e=this.ownerWindow??window;this.closeAnimationTimeout!==null&&(e.clearTimeout(this.closeAnimationTimeout),this.closeAnimationTimeout=null),this.cleanupResize();for(let r of this.cleanupCallbacks)try{r()}catch{}this.cleanupCallbacks=[],this.rafId!==null&&(e.cancelAnimationFrame(this.rafId),this.rafId=null),this.panelRerenderRafId!==null&&(e.cancelAnimationFrame(this.panelRerenderRafId),this.panelRerenderRafId=null),this.resizeObserver?.disconnect(),this.resizeObserver=null,this.root?.unmount(),this.root=null,this.overlayContainer?.parentNode&&this.overlayContainer.parentNode.removeChild(this.overlayContainer),this.overlayContainer&&Uyt(this.overlayContainer),this.overlayContainer=null;let n=Os.overlayRoot;if(n&&n.childElementCount===0){let r=n.parentElement;n.remove(),Os.overlayRoot=null,r?.classList.remove("copilot-quick-ask-overlay-host")}this.bottomAnchorPos=null,this.topAnchorPos=null,this.focusAnchorPos=null,this.placementSide=null,this.ownerDocument=null,this.ownerWindow=null}updatePosition(e,n,r){typeof e=="number"&&(this.bottomAnchorPos=e),typeof n=="number"?this.topAnchorPos=n:n===null&&(this.topAnchorPos=null),typeof r=="number"?this.focusAnchorPos=r:r===null&&(this.focusAnchorPos=null),this.placementSide=null,this.schedulePositionUpdate()}getReplaceGuard(){return this.options.replaceGuard}schedulePanelRerender(){if(this.panelRerenderRafId!==null)return;let e=this.ownerWindow??window;this.panelRerenderRafId=e.requestAnimationFrame(()=>{this.panelRerenderRafId=null,this.renderPanel()})}renderPanel(){this.root&&this.root.render(Zyt.default.createElement(Wyt,{plugin:this.options.plugin,editor:this.options.editor,view:this.options.view,selectedText:this.options.selectedText,replaceGuard:this.options.replaceGuard,onClose:this.closeWithAnimation,onDragOffset:this.handleDragOffset,onResizeStart:this.handleResizeStart,hasCustomHeight:this.hasUserResizedHeight}))}static closeCurrentWithAnimation(){return Os.currentInstance?(Os.currentInstance.closeWithAnimation(),!0):!1}static getOverlayRoot(e){if(Os.overlayRoot&&Os.overlayRoot.parentElement!==e&&(Os.overlayRoot.parentElement?.classList.remove("copilot-quick-ask-overlay-host"),Os.overlayRoot.remove(),Os.overlayRoot=null),Os.overlayRoot)return Os.overlayRoot;let r=e.doc.createElement("div");return r.className="copilot-quick-ask-overlay-root",e.appendChild(r),e.classList.add("copilot-quick-ask-overlay-host"),Os.overlayRoot=r,r}mountOverlay(){let e=this.options.view.dom??activeDocument.body;this.overlayHost=e;let n=e.doc,r=n.defaultView??window;this.ownerDocument=n,this.ownerWindow=r;let o=Os.getOverlayRoot(e),i=n.createElement("div");i.className="copilot-quick-ask-overlay",o.appendChild(i),this.overlayContainer=i,this.root=sr(i,this.options.plugin.app),this.renderPanel();let s=()=>{this.placementSide=null,this.schedulePositionUpdate()};r.addEventListener("scroll",s,!0),this.cleanupCallbacks.push(()=>r.removeEventListener("scroll",s,!0));let a=()=>{this.placementSide=null,this.schedulePositionUpdate()};r.addEventListener("resize",a),this.cleanupCallbacks.push(()=>r.removeEventListener("resize",a));let l=this.options.view?.scrollDOM;l&&(l.addEventListener("scroll",s),this.cleanupCallbacks.push(()=>l.removeEventListener("scroll",s))),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{this.placementSide=null,this.schedulePositionUpdate()}),l&&this.resizeObserver.observe(l))}setupGlobalListeners(){let e=r=>{if(r.key!=="Escape"||r.defaultPrevented)return;let i=(this.ownerDocument??activeDocument).activeElement;i&&this.overlayContainer?.contains(i)||(r.preventDefault(),r.stopPropagation(),this.closeWithAnimation())},n=this.ownerWindow??window;n.addEventListener("keydown",e),this.cleanupCallbacks.push(()=>n.removeEventListener("keydown",e))}schedulePositionUpdate(){if(this.rafId!==null)return;let e=this.ownerWindow??window;this.rafId=e.requestAnimationFrame(()=>{this.rafId=null,this.updateOverlayPosition()})}isAnchorRectVisible(e,n){return e.bottom>=n.top&&e.top<=n.bottom&&e.right>=n.left&&e.left<=n.right}resolveVisibleAnchors(e,n){let r=n??e,o=i=>{if(typeof i!="number")return null;let s=this.options.view.coordsAtPos(i);return s&&this.isAnchorRectVisible(s,r)?s:null};return{bottomRect:o(this.bottomAnchorPos),topRect:o(this.topAnchorPos),focusRect:o(this.focusAnchorPos)}}computeVerticalPlacement(e,n,r,o,i,s,a,l){let c;if(this.placementSide==="below"&&e)c=e.bottom-r.top+MS;else if(this.placementSide==="above"&&n)c=n.top-r.top-MS-a;else if(e){let f=e.bottom-r.top+MS;if(i-(e.bottom-r.top)-MS>=a+vu)c=f,this.placementSide="below";else if(n){let m=n.top-r.top-MS-a;n.top-r.top-MS-o>=a+vu?(c=m,this.placementSide="above"):(c=o+(s-a)/2,this.placementSide=null)}else c=o+(s-a)/2,this.placementSide=null}else if(n){let f=n.top-r.top-MS-a;n.top-r.top-MS-o>=a+vu?(c=f,this.placementSide="above"):(c=o+(s-a)/2,this.placementSide=null)}else c=o+(s-a)/2,this.placementSide=null;let u=i-vu-a,d=Math.max(l,u);return Math.max(l,Math.min(c,d))}updateOverlayPosition(){if(!this.overlayContainer||this.bottomAnchorPos===null)return;if(this.dragPosition){this.updateDragPosition();return}let e=this.ownerDocument??activeDocument,n=this.overlayHost?.getBoundingClientRect()??e.body.getBoundingClientRect(),r=n.width,o=this.options.view.scrollDOM,i=o?.getBoundingClientRect(),a=o?.querySelector(".cm-sizer")?.getBoundingClientRect(),{bottomRect:l,topRect:c,focusRect:u}=this.resolveVisibleAnchors(n,i),d=Math.min(qyt,r*Hyt),f=Math.min(Gyt,r*Kyt),p=Math.min(ePe,r-vu*2),m=this.resizeSize?.width??Math.max(p,Math.min(d,f)),h=this.resizeSize?.height,g=(a?.left??i?.left??n.left+vu)-n.left,y=a?.width??i?.width??r-vu*2,w=g+y,v=this.topAnchorPos!==null&&this.bottomAnchorPos!==null&&this.topAnchorPos===this.bottomAnchorPos,x=typeof this.topAnchorPos=="number"?this.options.view.coordsAtPos(this.topAnchorPos):null,b=typeof this.bottomAnchorPos=="number"?this.options.view.coordsAtPos(this.bottomAnchorPos):null,_=Math.min((x?.bottom??0)-(x?.top??0),(b?.bottom??0)-(b?.top??0)),T=!v&&!!x&&!!b&&Math.abs(x.top-b.top)>Math.max(_/2,2),S=u??l??c,P=T?g+(y-m)/2:S?S.left-n.left:g+(y-m)/2;P=Math.min(P,w-m),P=Math.max(P,g),P=Math.min(P,r-vu-m),P=Math.max(P,vu);let A=(i?.top??n.top)-n.top,O=(i?.bottom??n.bottom)-n.top,D=O-A,$=A+vu;jQ(this.overlayContainer,"copilot-quick-ask-overlay-pos",{width:m,...typeof h=="number"?{height:h}:{},left:Math.round(P),top:Math.round($)});let B=typeof h=="number"?h:this.overlayContainer.getBoundingClientRect().height||Yyt,W=this.computeVerticalPlacement(l,c,n,A,O,D,B,$);jQ(this.overlayContainer,"copilot-quick-ask-overlay-pos",{width:m,...typeof h=="number"?{height:h}:{},left:Math.round(P),top:Math.round(W)})}cleanupResize(){let e=this.ownerWindow??window;if(this.resizeRafId!==null&&(e.cancelAnimationFrame(this.resizeRafId),this.resizeRafId=null),this.isResizing){let n=this.ownerDocument??activeDocument,r=n.body;n.removeEventListener("mousemove",this.handleResizeMove,!0),n.removeEventListener("mouseup",this.handleResizeEnd,!0),r.classList.remove("tw-select-none","tw-cursor-[var(--copilot-resize-cursor)]"),r.setCssProps({"--copilot-resize-cursor":""})}this.isResizing=!1,this.resizeDirection=null,this.resizeStartRect=null,this.resizeStartMouse=null}applyResize(e,n){if(!this.resizeStartRect||!this.resizeStartMouse||!this.resizeDirection)return;let r=this.ownerDocument??activeDocument,o=this.overlayHost?.getBoundingClientRect()??r.body.getBoundingClientRect(),i=e-this.resizeStartMouse.x,s=n-this.resizeStartMouse.y,a=this.resizeStartRect,l=this.resizeDirection,c=o.width,u=Math.min(ePe,c-vu*2),d=Yyt,f=o.left+vu,p=o.right-vu,m=o.bottom-vu,h=a.width,g=a.height,y,w,v=l!=="right";switch(l){case"right":h=a.width+i;break;case"bottom":g=a.height+s;break;case"bottom-right":h=a.width+i,g=a.height+s;break;case"bottom-left":h=a.width-i,g=a.height+s,y=a.left+i,w=a.top;break}let x=p-a.left,b=a.right-f,_=m-a.top;l==="bottom-left"?(h=Math.max(u,Math.min(h,b)),y=a.right-h,y<f&&(y=f,h=a.right-f)):h=Math.max(u,Math.min(h,x)),v&&(g=Math.max(d,Math.min(g,_)));let T=this.resizeSize?.height,S={width:h};v?S.height=g:this.hasUserResizedHeight&&typeof T=="number"&&(S.height=T),this.resizeSize=S;let P=this.hasUserResizedHeight;v&&(this.hasUserResizedHeight=!0),this.hasUserResizedHeight!==P&&this.renderPanel(),l==="bottom-left"&&y!==void 0?(this.dragPosition={x:y,y:w??a.top},this.updateDragPosition()):this.dragPosition?this.updateDragPosition():this.schedulePositionUpdate()}updateDragPosition(){if(!this.overlayContainer||!this.dragPosition)return;let e=this.ownerDocument??activeDocument,n=this.overlayHost?.getBoundingClientRect()??e.body.getBoundingClientRect(),r=n.width,o=Math.min(qyt,r*Hyt),i=Math.min(Gyt,r*Kyt),s=Math.min(ePe,r-vu*2),a=this.resizeSize?.width??Math.max(s,Math.min(o,i)),l=this.resizeSize?.height;jQ(this.overlayContainer,"copilot-quick-ask-overlay-pos",{width:a,...l?{height:l}:{},left:Math.round(this.dragPosition.x-n.left),top:Math.round(this.dragPosition.y-n.top)})}};Os.overlayRoot=null,Os.currentInstance=null;var J1=Os;function Jyt(t,e){let{bottomAnchorPos:n,topAnchorPos:r,focusAnchorPos:o}=t;if(n!==null&&n===r){let s=e.mapPos(n,1);return{bottomAnchorPos:s,topAnchorPos:s,focusAnchorPos:s}}let i=o===r?1:-1;return{bottomAnchorPos:n!==null?e.mapPos(n,-1):null,topAnchorPos:r!==null?e.mapPos(r,1):null,focusAnchorPos:o!==null?e.mapPos(o,i):null}}var qE=Xyt.StateEffect.define(),ewt=Qyt.ViewPlugin.fromClass(class{constructor(t){this.view=t;this.overlay=null;this.bottomAnchorPos=null;this.topAnchorPos=null;this.focusAnchorPos=null}update(t){for(let e of t.transactions)for(let n of e.effects){if(!n.is(qE))continue;let r=n.value;if(!r){this.overlay?.destroy(),this.overlay=null,this.bottomAnchorPos=null,this.topAnchorPos=null,this.focusAnchorPos=null;continue}this.overlay?.destroy(),this.bottomAnchorPos=r.bottomAnchorPos,this.topAnchorPos=typeof r.topAnchorPos=="number"?r.topAnchorPos:null,this.focusAnchorPos=typeof r.focusAnchorPos=="number"?r.focusAnchorPos:null,this.overlay=new J1(r.options),this.overlay.mount(r.bottomAnchorPos,this.topAnchorPos,this.focusAnchorPos)}if(this.overlay&&t.docChanged){let e=this.overlay.getReplaceGuard();e?.onDocChanged&&e.onDocChanged(t.changes);let n=Jyt({bottomAnchorPos:this.bottomAnchorPos,topAnchorPos:this.topAnchorPos,focusAnchorPos:this.focusAnchorPos},t.changes);this.bottomAnchorPos=n.bottomAnchorPos,this.topAnchorPos=n.topAnchorPos,this.focusAnchorPos=n.focusAnchorPos,this.bottomAnchorPos!==null&&this.overlay.updatePosition(this.bottomAnchorPos,this.topAnchorPos,this.focusAnchorPos),this.overlay.schedulePanelRerender()}}destroy(){this.overlay?.destroy(),this.overlay=null,this.bottomAnchorPos=null,this.topAnchorPos=null,this.focusAnchorPos=null}});ye();var qV=class{constructor(e){this.quickAskWidgetState=null;this.plugin=e}close(e=!0){let n=this.quickAskWidgetState;if(!n)return;if(!e){this.quickAskWidgetState=null;try{let o=[qE.of(null),...ld.buildEffects(n.view,null)];n.view.dispatch({effects:o})}catch(o){ee("Failed to dispatch close effect:",o)}return}if(this.quickAskWidgetState=null,!J1.closeCurrentWithAnimation())try{let o=[qE.of(null),...ld.buildEffects(n.view,null)];n.view.dispatch({effects:o}),n.view.focus()}catch(o){ee("Failed to dispatch close effect or focus:",o)}}show(e,n){let r=n.state.selection.main,o=e.editor,i=e.leaf,s=e.file?.path??null,a=n.state.doc.sliceString(r.from,r.to),l=r.from,c=r.to;this.close(!1);let u=mrt({editorView:n,leafSnapshot:i,filePathSnapshot:s,selectedTextSnapshot:a,initialRange:{from:l,to:c},getLeafState:()=>{let f=i.view;return f instanceof twt.MarkdownView?{leaf:i,editorView:f.editor?.cm??null,filePath:f.file?.path??null}:{leaf:null,editorView:null,filePath:null}}}),d=(f=!0)=>{let p=!this.quickAskWidgetState||this.quickAskWidgetState.view===n;p&&(this.quickAskWidgetState=null);try{let m=[qE.of(null),...ld.buildEffects(n,null)];n.dispatch({effects:m}),p&&f&&n.focus()}catch(m){ee("Failed to dispatch close effect or focus:",m)}};try{let f=sZ(r,n.state.doc);n.dispatch({effects:[qE.of(null),...ld.buildEffects(n,null),qE.of({bottomAnchorPos:f.bottomPos,topAnchorPos:f.topPos,focusAnchorPos:f.focusPos,options:{plugin:this.plugin,editor:o,view:n,selectedText:a,selectionFrom:l,selectionTo:c,replaceGuard:u,onClose:()=>d(!0)}}),...ld.buildEffects(n,{from:l,to:c})]}),this.quickAskWidgetState={view:n,close:d}}catch(f){ee("Failed to show Quick Ask panel:",f),this.quickAskWidgetState=null}}isOpen(){return this.quickAskWidgetState!==null}createExtension(){return[ewt]}};var X1=require("obsidian");It();ye();var VQ=oZ("copilot-chat-selection-highlight");function tPe(t){try{let e=VQ.buildEffects(t,null);e.length>0&&t.dispatch({effects:e})}catch{}}var GV=class{constructor(e,n){this.lastActiveMarkdownLeaf=null;this.lastActiveLeafWasMarkdown=!1;this.snapshot=null;this.plugin=e,this.closeQuickAskOnChatFocus=n?.closeQuickAskOnChatFocus??!1}initialize(){let e=this.plugin.app.workspace.getActiveViewOfType(X1.MarkdownView),n=e?.leaf??null;this.lastActiveLeafWasMarkdown=!!e,this.lastActiveLeafWasMarkdown&&n&&(this.lastActiveMarkdownLeaf=n)}cleanup(){this.clear(),this.lastActiveMarkdownLeaf=null,this.lastActiveLeafWasMarkdown=!1}handleActiveLeafChange(e){let n=this.lastActiveLeafWasMarkdown,r=e?.getViewState().type??null,o=e?.view instanceof X1.MarkdownView;this.lastActiveLeafWasMarkdown=o,o&&e&&(this.lastActiveMarkdownLeaf=e),this.snapshot&&r!==No&&this.clear(),r===No&&n&&(this.closeQuickAskOnChatFocus&&this.plugin.quickAskController?.close(!1),this.persist({useFallback:!0}))}persistFromPointerDown(){this.plugin.app.workspace.getActiveViewOfType(X1.MarkdownView)&&this.persist({useFallback:!1})}clearIfNoNoteContexts(e){e.some(n=>n.sourceType==="note")||this.clear()}clearForNewChat(){this.clear()}persist(e){let n=this.getEditorView(e.useFallback);if(!n)return;let r=n.state.selection.main;if(r.from===r.to)return;let o=r.from,i=r.to,s=this.getHighlightRange(n);if(this.snapshot?.view===n&&this.snapshot.from===o&&this.snapshot.to===i&&s?.from===o&&s?.to===i)return;this.snapshot&&this.snapshot.view!==n&&(this.hideHighlight(this.snapshot.view),this.snapshot=null),this.showHighlight(n,o,i)&&(this.snapshot={view:n,from:o,to:i})}clear(){this.snapshot&&(this.hideHighlight(this.snapshot.view),this.snapshot=null)}getEditorView(e){let n=this.plugin.app.workspace.getActiveViewOfType(X1.MarkdownView);return n?.editor?.cm?n.editor.cm:e&&this.lastActiveMarkdownLeaf?.view instanceof X1.MarkdownView?this.lastActiveMarkdownLeaf.view.editor?.cm??null:null}showHighlight(e,n,r){try{let o=VQ.buildEffects(e,{from:n,to:r});return o.length===0?!1:(e.dispatch({effects:o}),!0)}catch(o){return z("ChatSelectionHighlight show failed:",o),!1}}hideHighlight(e){try{let n=VQ.buildEffects(e,null);n.length>0&&e.dispatch({effects:n})}catch(n){ee("ChatSelectionHighlight hide failed (view may be destroyed):",n)}}getHighlightRange(e){return VQ.getRange(e)}};var Oi=require("obsidian");Ky();av();qh();var WQ=class extends Oi.Plugin{constructor(){super(...arguments);this.userMessageHistory=[];this.chatHistoryLastAccessedAtManager=new sA}async onload(){Nht(),vd.resetInstance(),vd.getInstance(this.app),await this.loadSettings(),this.settingsUnsubscriber=Ho((s,a)=>{(async()=>{try{await Fht(a,l=>this.saveData(l),s)}catch(l){z("Failed to persist settings.",l),new Oi.Notice("Copilot failed to save settings. Check logs and try again.")}n_e(this,s,a)})()}),this.addSettingTab(new BQ(this.app,this)),yR(this.app.vault),this.brevilabsClient=di.getInstance(),this.brevilabsClient.setPluginVersion(this.manifest.version),_p(),k5e(),this.projectManager=Sl.getInstance(this.app,this),this.vectorStoreManager=Cp.getInstance(),H4.getInstance().initialize(),this.fileParserManager=new iy(this.brevilabsClient,this.app.vault);let r=new R1,o=this.projectManager.getCurrentChainManager(),i=new GX(r,o,this.fileParserManager,this);if(this.chatUIState=new zQ(i),this.userMemoryManager=new o_(this.app),this.quickAskController=new qV(this),this.registerEditorExtension(this.quickAskController.createExtension()),this.chatSelectionHighlightController=new GV(this,{closeQuickAskOnChatFocus:!1}),this.chatSelectionHighlightController.initialize(),Oi.Platform.isDesktopApp){let{activeLeafRef:s,layoutRef:a}=t_e(this.app,{preserveOnViewTypes:[No]});this.registerEvent(s),this.registerEvent(a)}this.registerView(No,s=>new xS(s,this)),this.registerView(bz,s=>new X8(s)),this.initActiveLeafChangeHandler(),this.addRibbonIcon("message-square","Open Copilot Chat",s=>{this.activateView()}),n_e(this,void 0,q()),this.registerEvent(this.app.workspace.on("editor-menu",s=>{hht(s,this.app)})),this.registerEvent(this.app.workspace.on("active-leaf-change",s=>{if(this.chatSelectionHighlightController.handleActiveLeafChange(s??null),s&&s.view instanceof Oi.MarkdownView&&s.view.file){let l=this.app.workspace.getLeavesOfType(No).find(c=>c.view instanceof xS)?.view;if(l){let c=new CustomEvent(kf.ACTIVE_LEAF_CHANGE);l.eventTarget.dispatchEvent(c)}}})),this.customCommandRegister=new jX(this,this.app.vault),this.systemPromptRegister=new o4(this,this.app.vault),this.projectRegister=new VX(this.app),this.app.workspace.onLayoutReady(()=>{this.projectRegister.initialize().catch(s=>{z("[Projects] ProjectRegister initialization failed",s),new Oi.Notice("Failed to load projects. Check console for details.")}),this.customCommandRegister.initialize().then(ght).then(yht),this.systemPromptRegister.initialize().then(()=>l_e(this.app.vault))}),this.initSelectionHandler(),this.initWebSelectionWatcher()}async onunload(){await Lht(),this.clearAllPersistentSelectionHighlights(),this.chatSelectionHighlightController?.cleanup(),this.projectManager&&this.projectManager.onunload(),H4.getInstance().cleanup(),this.customCommandRegister.cleanup(),this.systemPromptRegister.cleanup(),this.projectRegister.cleanup(),this.settingsUnsubscriber?.(),this.cleanupSelectionHandler(),this.cleanupWebSelectionWatcher(),this.clearSelectionContext();try{ls(this.app).stopActiveWebTabTracking()}catch{}await Ds.flush(),k("Copilot plugin unloaded")}clearAllPersistentSelectionHighlights(){try{let n=this.app.workspace.getLeavesOfType("markdown");for(let r of n){let o=r.view;if(!(o instanceof Oi.MarkdownView))continue;let i=o.editor?.cm;i&&(ld.hide(i),tPe(i))}}catch(n){ee("Failed to clear persistent selection highlights:",n)}}updateUserMessageHistory(n){this.userMessageHistory=[...this.userMessageHistory,n]}async autosaveCurrentChat(){if(q().autosaveChat){let n=this.app.workspace.getLeavesOfType(No)[0]?.view;n&&await n.saveChat()}}async processText(n,r,o,i=!0){let s=n.getSelection();this.app.workspace.getLeavesOfType(No).length>0||await this.activateView(),window.setTimeout(()=>{let l=this.app.workspace.getLeavesOfType(No).find(c=>c.view instanceof xS)?.view;if(l&&(!i||s)){let c=new CustomEvent(r,{detail:{selectedText:s,eventSubtype:o}});l.eventTarget.dispatchEvent(c)}},0)}processSelection(n,r,o){this.processText(n,r,o)}emitChatIsVisible(){let n=this.app.workspace.getLeavesOfType(No).find(r=>r.view instanceof xS)?.view;if(n){let r=new CustomEvent(kf.CHAT_IS_VISIBLE);n.eventTarget.dispatchEvent(r)}}initActiveLeafChangeHandler(){this.registerEvent(this.app.workspace.on("active-leaf-change",n=>{n&&n.getViewState().type===No&&this.emitChatIsVisible()}))}initSelectionHandler(){this.selectionChangeHandler=()=>{this.selectionDebounceTimer&&window.clearTimeout(this.selectionDebounceTimer),this.selectionDebounceTimer=window.setTimeout(()=>{this.handleSelectionChange()},500)},this.selectionListenerDocument=activeDocument,this.selectionListenerDocument.addEventListener("selectionchange",this.selectionChangeHandler)}cleanupSelectionHandler(){this.selectionDebounceTimer&&window.clearTimeout(this.selectionDebounceTimer),this.selectionChangeHandler&&this.selectionListenerDocument&&this.selectionListenerDocument.removeEventListener("selectionchange",this.selectionChangeHandler),this.selectionListenerDocument=void 0}clearSelectionContext(){og([])}clearWebSelectionContextForUrl(n){let r=wm(),o=r.filter(i=>i.sourceType!=="web"||i.url!==n);o.length!==r.length&&og(o)}setSelectionContext(n){og([n])}handleSelectionChange(){if(!q().autoAddSelectionToContext)return;let r=this.app.workspace.getActiveViewOfType(Oi.MarkdownView);if(!r||!r.editor)return;let o=r.editor,i=this.app.workspace.getActiveFile(),s=o.listSelections()[0];if(!s)return;let a=i?`${i.path}:${s.anchor.line}:${s.anchor.ch}:${s.head.line}:${s.head.ch}`:"";if(a===this.lastSelectionSignature)return;this.lastSelectionSignature=a;let l=o.getSelection();if(!l||!l.trim()){let m=wm(),h=m.filter(g=>g.sourceType!=="note");m.length!==h.length&&og(h);return}if(!i)return;let c=s.anchor.line+1,u=s.head.line+1,d=Math.min(c,u),f=Math.max(c,u),p={id:si(),content:l,sourceType:"note",noteTitle:i.basename,notePath:i.path,startLine:d,endLine:f};this.setSelectionContext(p)}initWebSelectionWatcher(){if(!Oi.Platform.isDesktopApp)return;let n=ls(this.app);this.webSelectionTracker=new tQ({intervalMs:500,emptySelectionDebounceCount:2,isEnabled:()=>q().autoAddSelectionToContext,getLeaf:()=>n.getActiveLeaf()??n.getLastActiveLeaf(),getActiveLeaf:()=>n.getActiveLeaf(),onSelectionChange:r=>{this.setSelectionContext(r)},onSelectionClear:({url:r})=>{this.clearWebSelectionContextForUrl(r)}}),this.webSelectionTracker.start()}cleanupWebSelectionWatcher(){this.webSelectionTracker?.stop(),this.webSelectionTracker=void 0}suppressCurrentWebSelection(n){if(n&&n.trim()){this.webSelectionTracker?.suppressSelectionForUrl(n);return}this.webSelectionTracker?.suppressCurrentSelection()}getCurrentEditorOrDummy(){let n=this.app.workspace.getActiveViewOfType(Oi.MarkdownView);return{getSelection:()=>{let r=n?.editor?.getSelection();if(r)return r;let o=this.app.workspace.getActiveFile();return o?this.app.vault.read(o):""},replaceSelection:n?.editor?.replaceSelection.bind(n.editor)||(()=>{})}}processCustomPrompt(n,r){let o=this.getCurrentEditorOrDummy();this.processText(o,n,r,!1)}toggleView(){this.app.workspace.getLeavesOfType(No).length>0?this.deactivateView():this.activateView()}async activateView(){let n=this.app.workspace.getLeavesOfType(No);n.length===0?q().defaultOpenArea==="view"?await this.app.workspace.getRightLeaf(!1).setViewState({type:No,active:!0}):await this.app.workspace.getLeaf(!0).setViewState({type:No,active:!0}):this.app.workspace.revealLeaf(n[0]),window.setTimeout(()=>{this.emitChatIsVisible()},50)}async deactivateView(){this.app.workspace.detachLeavesOfType(No)}async loadSettings(){let n=await this.loadData(),r=await Dht(n,o=>this.saveData(o));Ls(r)}mergeActiveModels(n,r){let o=new Map;return n.forEach(i=>{let s=ln(i),a=o.get(s);a?o.set(s,{...i,isBuiltIn:a.isBuiltIn||i.isBuiltIn}):o.set(s,i)}),Array.from(o.values())}async loadCopilotChatHistory(){let n=await this.getChatHistoryFiles();if(n.length===0){new Oi.Notice("No chat history found.");return}new zX(this.app,n,this.chatHistoryLastAccessedAtManager,this.loadChatHistory.bind(this)).open()}async getChatHistoryFiles(){let n=await dB(this.app,q().defaultSaveFolder);if(n.length===0)return[];let r=br();return BX(this.app,n,r?.id)}async getChatHistoryItems(){return(await this.getChatHistoryFiles()).map(r=>{let o=wV(r),i=vV(r),s=this.chatHistoryLastAccessedAtManager.getEffectiveLastUsedAt(r.path,i??o.getTime()),a=new Date(s);return{id:r.path,title:yV(r),createdAt:o,lastAccessedAt:a}})}async touchChatHistoryLastAccessedAt(n){try{this.chatHistoryLastAccessedAtManager.touch(n.path);let r=vV(n),o=this.chatHistoryLastAccessedAtManager.shouldPersist(n.path,r);if(o===null)return;let i=o;this.app.fileManager?.processFrontMatter&&this.app.vault.getAbstractFileByPath(n.path)!=null?await this.app.fileManager.processFrontMatter(n,s=>{let a=Number(s.lastAccessedAt),l=Number.isFinite(a)&&a>0?a:0;i=Math.max(l,o),l!==i&&(s.lastAccessedAt=i)}):await LC(this.app,n.path,{lastAccessedAt:i}),this.chatHistoryLastAccessedAtManager.markPersisted(n.path,i)}catch(r){ee(`[CopilotPlugin] Failed to update chat lastAccessedAt for ${n.path}`,r)}}getChatHistoryLastAccessedAtManager(){return this.chatHistoryLastAccessedAtManager}async loadChatHistory(n){await this.autosaveCurrentChat();let r=this.app.workspace.getLeavesOfType(No)[0];r||await this.activateView(),await this.chatUIState.loadChatHistory(n),this.touchChatHistoryLastAccessedAt(n);let o=(r||this.app.workspace.getLeavesOfType(No)[0])?.view;o&&o.updateView()}async loadChatById(n){let r=await I0(this.app,n);if(r)await this.loadChatHistory(r);else throw new Error("Chat file not found.")}async openChatSourceFile(n){let r=this.app.vault.getAbstractFileByPath(n);if(r instanceof Oi.TFile)await this.app.workspace.getLeaf(!0).openFile(r);else if(await this.app.vault.adapter.exists(n))new Oi.Notice("Cannot open source files from hidden directories. To open chat notes in the editor, save them to a non-hidden folder in settings.");else throw new Error("Chat file not found.")}async updateChatTitle(n,r){let o=this.app.vault.getAbstractFileByPath(n);if(o instanceof Oi.TFile)await this.app.fileManager.processFrontMatter(o,i=>{i.topic=r}),await new Promise(i=>{let s=l=>{l.path===n&&(this.app.metadataCache.off("changed",s),window.clearTimeout(a),i())};this.app.metadataCache.on("changed",s);let a=window.setTimeout(()=>{this.app.metadataCache.off("changed",s),i()},500)}),new Oi.Notice("Chat title updated.");else if(await I0(this.app,n))await LC(this.app,n,{topic:r.trim()}),new Oi.Notice("Chat title updated.");else throw new Error("Chat file not found.")}async deleteChatHistory(n){let r=this.app.vault.getAbstractFileByPath(n);if(r instanceof Oi.TFile)await Qc(this.app,r),new Oi.Notice("Chat deleted.");else if(await this.app.vault.adapter.exists(n))await this.app.vault.adapter.remove(n),new Oi.Notice("Chat deleted.");else throw new Error("Chat file not found.")}async handleNewChat(){if(sO(),await Ds.clear(),q().enableRecentConversations)try{let o=this.projectManager.getCurrentChainManager().chatModelManager.getChatModel();this.userMemoryManager.addRecentConversation(this.chatUIState.getMessages(),o)}catch(r){k("Failed to analyze chat messages for memory:",r)}await this.autosaveCurrentChat();let n=this.app.workspace.getLeavesOfType(No)[0];if(n){let r=n.view,o=new CustomEvent(kf.ABORT_STREAM,{detail:{reason:"new-chat"}});r.eventTarget.dispatchEvent(o)}this.chatUIState.clearMessages(),n?n.view.updateView():await this.activateView()}async newChat(){await this.handleNewChat()}async customSearchDB(n,r,o){let i=q(),{FilterRetriever:s}=await Promise.resolve().then(()=>(U8(),O9e)),{mergeFilterAndSearchResults:a}=await Promise.resolve().then(()=>(B8(),R9e)),c=await new s(this.app,{salientTerms:r,maxK:20}).getRelevantDocuments(n),d=await(i.enableSemanticSearchV3?new(await Promise.resolve().then(()=>(Kve(),M9e))).MergedSemanticRetriever(this.app,{minSimilarityScore:.3,maxK:20,salientTerms:r,textWeight:o,returnAll:!1}):new(await Promise.resolve().then(()=>(fz(),k9e))).TieredLexicalRetriever(this.app,{minSimilarityScore:.3,maxK:20,salientTerms:r,textWeight:o,returnAll:!1,useRerankerThreshold:void 0})).getRelevantDocuments(n),{filterResults:f,searchResults:p}=a(c,d);return[...f,...p].map(h=>({content:h.pageContent,metadata:h.metadata}))}};
/*! Bundled license information:

ieee754/index.js:
  (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)

buffer/index.js:
  (*!
   * The buffer module from node.js, for the browser.
   *
   * @author   Feross Aboukhadijeh <https://feross.org>
   * @license  MIT
   *)

react/cjs/react.production.min.js:
  (**
   * @license React
   * react.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react/cjs/react-jsx-runtime.production.min.js:
  (**
   * @license React
   * react-jsx-runtime.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/shared/src/utils.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/defaultAttributes.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/Icon.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/createLucideIcon.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/arrow-big-up.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/arrow-right.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/arrow-up-right.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/book-open.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/brain.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/check.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/chevron-down.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/chevron-right.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/chevron-up.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-alert.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-check-big.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-check.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-dashed.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-help.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-plus.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-stop.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle-x.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/circle.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/clipboard-paste.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/clock.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/cog.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/coins.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/command.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/copy-plus.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/copy.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/corner-down-left.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/cpu.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/database.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/download.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/ellipsis-vertical.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/ellipsis.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/external-link.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/eye-off.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/eye.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/file-audio.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/file-clock.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/file-image.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/file-input.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/file-output.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/file-text.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/file-video.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/folder-open.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/folder.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/globe.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/grip-vertical.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/hash.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/history.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/image.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/info.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/key.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/library-big.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/lightbulb.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/link.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/loader-circle.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/lock-open.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/message-circle-plus.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/message-circle.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/message-square-x.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/message-square.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/pause.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/pen-line.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/pen.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/pencil-line.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/pencil.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/play.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/plus.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/refresh-ccw.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/refresh-cw.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/replace.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/rotate-ccw.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/rotate-cw.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/search.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/send.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/settings.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/shield-check.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/smartphone.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/sparkles.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/square-arrow-out-up-right.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/square-pen.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/square.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/tag.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/text-cursor-input.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/trash-2.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/triangle-alert.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/wrench.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/x.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/zap-off.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/icons/zap.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

lucide-react/dist/esm/lucide-react.js:
  (**
   * @license lucide-react v0.462.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   *)

scheduler/cjs/scheduler.production.min.js:
  (**
   * @license React
   * scheduler.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

react-dom/cjs/react-dom.production.min.js:
  (**
   * @license React
   * react-dom.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   *)

@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
  (*!
  * https://github.com/Starcounter-Jack/JSON-Patch
  * (c) 2017-2022 Joachim Wester
  * MIT licensed
  *)

@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
  (*!
  * https://github.com/Starcounter-Jack/JSON-Patch
  * (c) 2013-2021 Joachim Wester
  * MIT license
  *)

@langchain/core/dist/utils/js-sha256/hash.js:
  (**
  * [js-sha256]{@link https://github.com/emn178/js-sha256}
  *
  * @version 0.11.1
  * @author Chen, Yi-Cyuan [emn178@gmail.com]
  * @copyright Chen, Yi-Cyuan 2014-2025
  * @license MIT
  *)

@langchain/core/dist/utils/sax-js/sax.js:
  (*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)

@google/generative-ai/dist/index.mjs:
  (**
   * @license
   * Copyright 2024 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   *)

mustache/mustache.mjs:
  (*!
   * mustache.js - Logic-less {{mustache}} templates with JavaScript
   * http://github.com/janl/mustache.js
   *)
*/

/* nosourcemap */